问:
Regex query efficient?
I came up with the below regex expression to look for terms like Password,Passphrase,Pass001 etc and the word following it. Is it efficient or can it be made better? Thanks for the help

```<code>"([Pp][aA][sS][Ss]([wW][oO][rR][dD][sS]?|[Pp][hH][rR][aA][sS][eE])?|[Pp]([aA][sS]([sS])?)?[wW][Dd])[0-9]?[0-9]?[0-9]?[\s\:\-\=\_\/\@\&\'\[\(\+\*\r\n\)\]]+\S*"
</code>```

I will be using it to scan files upto 300K for these terms. When I try now to scan with these expression a whole C: drive it takes 5 hours or worse case I have encountered, 5 days

答:
You may use the following enhancement:

```<code>(?i)p(?:ass(?:words?|phrase)?|(?:ass?)?wd)[0-9]{0,3}[-\s:=_\/@&'\]\[()+*\r\n]\S*
</code>```

See the regex demo

Instead of [sS], you may make the regex case insensitive by adding (?i) case insensitive modifier. Use corresponding option in your software if it does not work like this.

Make sure your alternations do not match at the same location in the string. It is not quite easy here, but p at the start of each alternative in the first group decreases the regex efficiency. So, move it outside (e.g. (?:pass|port) => p(ass|ort)).

Use non-capturing groups rather than capturing ones if you are not going to access submatches, that also has a slight impact on performance.

Use limiting quantifiers instead of repeating ? quantified patterns. Instead of a?a?a?, use a{0,3}.

Do not overescape chars inside the character class. I only left \/, \] and \[ as I am not sure what regex flavor you are using, it might appear you can avoid escaping at all.

Note that a performance penalty is big if you have consecutive non-fixed width patterns that may match the same type of chars. You have [\s\:\-\=\_\/\@\&\'\[\(\+\*\r\n\)\]]+\S*: [\s\:\-\=\_\/\@\&\'\[\(\+\*\r\n\)\]]+ matches 1 or more special chars and \S* matches 0 or more chars other than whitespace that also matches some chars matched by the preceding pattern. Remove the + from the preceding subpattern.

Title: Regex query efficient?

Body:
I came up with the below regex expression to look for terms like Password,Passphrase,Pass001 etc and the word following it. Is it efficient or can it be made better? Thanks for the help

"([Pp][aA][sS][Ss]([wW][oO][rR][dD][sS]?|[Pp][hH][rR][aA][sS][eE])?|[Pp]([aA][sS]([sS])?)?[wW][Dd])[0-9]?[0-9]?[0-9]?[\s\:\-\=\_\/\@\&\'\[\(\+\*\r\n\)\]]+\S*"

I will be using it to scan files upto 300K for these terms. When I try now to scan with these expression a whole C: drive it takes 5 hours or worse case I have encountered, 5 days

Body:
You may use the following enhancement:

(?i)p(?:ass(?:words?|phrase)?|(?:ass?)?wd)[0-9]{0,3}[-\s:=_\/@&'\]\[()+*\r\n]\S*

See the regex demo

Instead of [sS], you may make the regex case insensitive by adding (?i) case insensitive modifier. Use corresponding option in your software if it does not work like this.

Make sure your alternations do not match at the same location in the string. It is not quite easy here, but p at the start of each alternative in the first group decreases the regex efficiency. So, move it outside (e.g. (?:pass|port) => p(ass|ort)).

Use non-capturing groups rather than capturing ones if you are not going to access submatches, that also has a slight impact on performance.

Use limiting quantifiers instead of repeating ? quantified patterns. Instead of a?a?a?, use a{0,3}.

Do not overescape chars inside the character class. I only left \/, \] and \[ as I am not sure what regex flavor you are using, it might appear you can avoid escaping at all.

Note that a performance penalty is big if you have consecutive non-fixed width patterns that may match the same type of chars. You have [\s\:\-\=\_\/\@\&\'\[\(\+\*\r\n\)\]]+\S*: [\s\:\-\=\_\/\@\&\'\[\(\+\*\r\n\)\]]+ matches 1 or more special chars and \S* matches 0 or more chars other than whitespace that also matches some chars matched by the preceding pattern. Remove the + from the preceding subpattern.


来源: stackexchange

问:
How to Find Words Not Containing Specific Letters?
I'm trying to write a code using regex and my text file. My file contains these words line by line:

```<code>nana
abab
nanac
eded
</code>```

My purpose is: displaying the words which does not contain the letters which are given as substring's letters.

For example, if my substring is "bn", my output should be only eded. Because nana and nanac contains "n" and abab contains "b".

I have written a code but it only checks first letter of my substring:

```<code>import re

substring = "bn"
def xstring():
    with open("deneme.txt") as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                for letter in substring:
                    if len(re.findall(letter, word)) == 0:
                        print(word)
                        #yield word
xstring()
</code>```

How do I solve this problem?

答:
If you want to check if a string has a set of letters, use brackets.

For example using [bn] will match words that contain one of those letters.

import re
substring = "bn"
regex = re.compile('[' + substring + ']')
def xstring():
    with open("dename.txt") as f:
        for line in f:
            if(re.search(regex, line) is None):
                print(line)
xstring()
```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a code using regex and my text file. My file contains these words line by line:

nana
abab
nanac
eded

My purpose is: displaying the words which does not contain the letters which are given as substring's letters.

For example, if my substring is "bn", my output should be only eded. Because nana and nanac contains "n" and abab contains "b".

I have written a code but it only checks first letter of my substring:

import re

substring = "bn"
def xstring():
    with open("deneme.txt") as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                for letter in substring:
                    if len(re.findall(letter, word)) == 0:
                        print(word)
                        #yield word
xstring()

How do I solve this problem?


问:
How to slow down first program in pipe until second program is ready
I have a script running as so:

```<code>cat in | prog1 2>log1 | prog2 2>log2 | prog3 2>log3 > out
</code>```

<in> can have millions of lines and I want each program to only produce output on STDOUT when the next program's STDIN has been consumed.

This is because prog1 uses system resources that prog2 cleans up once it's done with it.

So basically I want cat to "pause" between line writes until said lines have been consumed by prog1, and onward down the line.

I have tried using stdbuf but that doesn't appear to have any effect, i.e.:

```<code>stdbuf -o0 cat in | stdbuf -o0 -i0 prog1 2>log1 | stdbuf -o0 -i0 prog2 2>log2 | stdbuf -o0 i0 prog3 2>log3 > out
</code>```

Using pv -l between each pipe confirms the speed difference, and also tail -f of the different log files.

Is there a way to do this?

I am aware that this will adversely affect performance.

PS I also want the whole pipe to exit when any of the programs exit, and each of the programs are legacy written in either perl or python, so they can't just be combined.

Thanks in advance!

答:
Why do you insist on using pipes? The whole point of piping data is "First In, First Out". If you want regimented processes, use temporary files.

```<code>prog1 < in 2>log1 > $(mktemp)
prog2 < $_ 2>log2 > $(mktemp)
# etc...
</code>```

edit: In this context, $_ means "the last argument of the last command line".

Body:
I have a script running as so:

cat in | prog1 2>log1 | prog2 2>log2 | prog3 2>log3 > out

<in> can have millions of lines and I want each program to only produce output on STDOUT when the next program's STDIN has been consumed.

This is because prog1 uses system resources that prog2 cleans up once it's done with it.

So basically I want cat to "pause" between line writes until said lines have been consumed by prog1, and onward down the line.

I have tried using stdbuf but that doesn't appear to have any effect, i.e.:

stdbuf -o0 cat in | stdbuf -o0 -i0 prog1 2>log1 | stdbuf -o0 -i0 prog2 2>log2 | stdbuf -o0 i0 prog3 2>log3 > out

Using pv -l between each pipe confirms the speed difference, and also tail -f of the different log files.

Is there a way to do this?

I am aware that this will adversely affect performance.

PS I also want the whole pipe to exit when any of the programs exit, and each of the programs are legacy written in either perl or python, so they can't just be combined.

Thanks in advance!

Body:
Why do you insist on using pipes? The whole point of piping data is "First In, First Out". If you want regimented processes, use temporary files.

prog1 < in 2>log1 > $(mktemp)
prog2 < $_ 2>log2 > $(mktemp)
# etc...

edit: In this context, $_ means "the last argument of the last command line".


问:
My Laravel project don't conect to XAMPP DataBase
I've followed good tutorials on the web and I do make, I've made step by step its advices and I don't achive to conect my laravel framework to XAMPP.. I don't have idea what's going on.. I've written down the .env and config/database.php with the same data configurations (DB_DATABASE= styde_curso, DB_USERNAME= root, and DB_PASSWORD= ).

.env

```<code>APP_NAME=Prueba
APP_ENV=local
APP_KEY=base64:MWU6YadaT17Ga1m3hrtOQqYq6pIwOgrNWQe+mJazyw0=
APP_DEBUG=true
APP_URL=homestead.test
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=styde_curso
DB_USERNAME=root
DB_PASSWORD=
</code>```

config/database.php

```<code>'mysql' => [

            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'styde_curso'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
</code>```

Although I'd applied "php artisan config:clear" I'm getting the same result "ERROR" I've copied the error that git hub notices me:

vagrant@homestead:~/code/Prueba$ php artisan config:clear
  Configuration cache cleared! vagrant@homestead:~/code/Prueba$ php
  artisan migrate

Illuminate\Database\QueryException  : SQLSTATE[HY000] [1045] Access
  denied for user 'root'@'localhost' (using password: NO) (SQL: select *
  from information_schema.tables where table_schema = styde_curso and
  table_name = migrations)

at

/home/vagrant/code/Prueba/vendor/laravel/framework/src/Illuminate/Database/Connection.php:
  664

```<code>660|         // If an exception occurs when attempting to run a query, we'll format the error
661|         // message to include the bindings with SQL, which will make this exception a
662|         // lot more helpful to the developer instead of just the database's errors.

663|         catch (Exception $e) {
664|             throw new QueryException(
665|                 $query, $this->prepareBindings($bindings), $e
666|             );
667|         }
668|
</code>```

Exception trace:

1   PDOException::("SQLSTATE[HY000] [1045] Access denied for user
  'root'@'localhost' (using password: NO)")
  /home/vagrant/code/Prueba/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php
  : 68

2

  PDO::__construct("mysql:host=localhost;port=3306;dbname=styde_curso",
  "root", "", [])
        /home/vagrant/code/Prueba/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php
  : 68

I'll wait your help or whomever can help me..
    Thanx.

答:
I would suggest setting your DB_HOST to 127.0.0.1

```<code>DB_HOST=127.0.0.1
</code>```

I would also suggest setting a password for the database root user if you have not already, this is just good practice. Be sure to update the .env file with the new password if you choose to do so.

The error is telling you the login failed:

```<code>SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
</code>```

The error is most likely either as a result of incorrect credentials (missing or wrong username/password). Or incorrect access, in other words, your user (in this case root) may have privileges as root@127.0.0.1 but not as root@localhost.

ContentLicense: CC BY-SA 3.0

Body:
I've followed good tutorials on the web and I do make, I've made step by step its advices and I don't achive to conect my laravel framework to XAMPP.. I don't have idea what's going on.. I've written down the .env and config/database.php with the same data configurations (DB_DATABASE= styde_curso, DB_USERNAME= root, and DB_PASSWORD= ).

.env

APP_NAME=Prueba
APP_ENV=local
APP_KEY=base64:MWU6YadaT17Ga1m3hrtOQqYq6pIwOgrNWQe+mJazyw0=
APP_DEBUG=true
APP_URL=homestead.test
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=styde_curso
DB_USERNAME=root
DB_PASSWORD=

config/database.php

'mysql' => [

            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'styde_curso'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

Although I'd applied "php artisan config:clear" I'm getting the same result "ERROR" I've copied the error that git hub notices me:

vagrant@homestead:~/code/Prueba$ php artisan config:clear
  Configuration cache cleared! vagrant@homestead:~/code/Prueba$ php
  artisan migrate

Illuminate\Database\QueryException  : SQLSTATE[HY000] [1045] Access
  denied for user 'root'@'localhost' (using password: NO) (SQL: select *
  from information_schema.tables where table_schema = styde_curso and
  table_name = migrations)

at

/home/vagrant/code/Prueba/vendor/laravel/framework/src/Illuminate/Database/Connection.php:
  664

660|         // If an exception occurs when attempting to run a query, we'll format the error
661|         // message to include the bindings with SQL, which will make this exception a
662|         // lot more helpful to the developer instead of just the database's errors.

663|         catch (Exception $e) {
664|             throw new QueryException(
665|                 $query, $this->prepareBindings($bindings), $e
666|             );
667|         }
668|

Exception trace:

1   PDOException::("SQLSTATE[HY000] [1045] Access denied for user
  'root'@'localhost' (using password: NO)")
  /home/vagrant/code/Prueba/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php
  : 68

2

  PDO::__construct("mysql:host=localhost;port=3306;dbname=styde_curso",
  "root", "", [])
        /home/vagrant/code/Prueba/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php
  : 68

I'll wait your help or whomever can help me..
    Thanx.

Body:
I would suggest setting your DB_HOST to 127.0.0.1

DB_HOST=127.0.0.1

I would also suggest setting a password for the database root user if you have not already, this is just good practice. Be sure to update the .env file with the new password if you choose to do so.

The error is telling you the login failed:

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

The error is most likely either as a result of incorrect credentials (missing or wrong username/password). Or incorrect access, in other words, your user (in this case root) may have privileges as root@127.0.0.1 but not as root@localhost.


问:
In R, find non-linear lines from two sets of points and then find the intersection of those points
Using R, I want to estimate two curves using points from two vectors, and then find the x and y coordinates where those estimated curves intersect.

In a strategic setting with players "t" and "p", I am simulating best responses for both players in response to what the other would pick in a strategic setting (game theory). The problem is that I don't have functions or lines, I have two sets of points originating from simulation, with one set of points corresponding to the player's best response to given actions by the other player. The actual math was too difficult for me (or matlab) to solve, which is why I'm using this simulated visual approach. I want to estimate best response functions (i.e. create non-linear curves) using the points, and then take the two estimated curves and find where they intersect in order to identify nash equilibrium (where the best response curves intersect).

As an example, here are two such vectors I am working with:

```<code>t=c(10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0)

p=c(12.3,12.3,12.3,12.3,12.3,12.3,12.4,12.4,12.4,12.5,12.5,12.5,12.6,12.6,12.7,12.7,12.8,12.8,12.9,12.9,13.0,13.1,13.1,13.2,13.3,13.4,13.5,13.4,13.5,13.6,13.6,13.7,13.8,13.8,13.9,13.9,13.9,14.0,14.0,14.0,14.0)
</code>```

For the first line, the sample is made up of (t,a), and for the second line, the sample is made up of (a,p) where a is a third vector given by

```<code>a = seq(10, 14, by = 0.1)
</code>```

For example, the first point for the sample corresponding to the first vector would be (10.0,10.0) and the second point would be (10.0,10.1). The first point for the sample corresponding to the second vector would be (10.0,12.3) and the second point would be (10.1,12.3).

What I originally tried to do is estimate the lines using polynomials produced by lm models, but those don't seem to always work:

```<code>plot(a,t, xlim=c(10,14), ylim=c(10,14), col="purple")
points(p,a, col="red")

fit4p <- lm(a~poly(p,3,raw=TRUE))
fit4t <- lm(t~poly(a,3,raw=TRUE))
lines(a, predict(fit4t, data.frame(x=a)), col="purple", xlim=c(10,14), ylim=c(10,14),type="l",xlab="p",ylab="t")
lines(p, predict(fit4p, data.frame(x=a)), col="green")

fit4pCurve <- function(x) coef(fit4p)[1] +x*coef(fit4p)[2]+x^2*coef(fit4p)[3]+x^3*coef(fit4p)[4]
fit4tCurve <- function(x) coef(fit4t)[1] +x*coef(fit4t)[2]+x^2*coef(fit4t)[3]+x^3*coef(fit4t)[4]

a_opt1 = optimise(f=function(x) abs(fit4pCurve(x)-fit4tCurve(x)), c(10,14))$minimum
b_opt1 = as.numeric(fit4pCurve(a_opt1))
</code>```

EDIT:
After fixing the type, I get the correct answer, but it doesn't always work if the samples don't come back as cleanly.

So my question can be broken down a few ways. First, is there a better way to accomplish what I'm trying to do. I know what I'm doing isn't perfectly accurate by any means, but it seems like a decent approximation for my purposes. Second, if there isn't a better way, is there a way I could improve on the methodology I have listed above.

答:
Restart your R session, make sure all variables are cleared and copy/paste this code. I found a few mistakes in referenced variables. Also note that R is case sensitive. My suspicion is that you've been overwriting variables.

```<code>plot(a,t, xlim=c(10,14), ylim=c(10,14), col="purple")
points(p,a, col="red")

fit4p <- lm(a~poly(p,3,raw=TRUE))
fit4t <- lm(t~poly(a,3,raw=TRUE))
lines(a, predict(fit4t, data.frame(x=a)), col="purple", xlim=c(T,P), ylim=c(10,14),type="l",xlab="p",ylab="t")
lines(p, predict(fit4p, data.frame(x=a)), col="green")

fit4pCurve <- function(x) coef(fit4p)[1] +x*coef(fit4p)[2]+x^2*coef(fit4p)[3]+x^3*coef(fit4p)[4]
fit4tCurve <- function(x) coef(fit4t)[1] +x*coef(fit4t)[2]+x^2*coef(fit4t)[3]+x^3*coef(fit4t)[4]

a_opt = optimise(f=function(x) abs(fit4pCurve(x)-fit4tCurve(x)), c(T,P))$minimum
b_opt = as.numeric(fit4pCurve(a_opt))
</code>```

As you will see:

```<code>> a_opt
[1] 12.24213
> b_opt
[1] 10.03581
</code>```

Body:
Using R, I want to estimate two curves using points from two vectors, and then find the x and y coordinates where those estimated curves intersect.

In a strategic setting with players "t" and "p", I am simulating best responses for both players in response to what the other would pick in a strategic setting (game theory). The problem is that I don't have functions or lines, I have two sets of points originating from simulation, with one set of points corresponding to the player's best response to given actions by the other player. The actual math was too difficult for me (or matlab) to solve, which is why I'm using this simulated visual approach. I want to estimate best response functions (i.e. create non-linear curves) using the points, and then take the two estimated curves and find where they intersect in order to identify nash equilibrium (where the best response curves intersect).

As an example, here are two such vectors I am working with:

t=c(10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.1,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0,10.0)

p=c(12.3,12.3,12.3,12.3,12.3,12.3,12.4,12.4,12.4,12.5,12.5,12.5,12.6,12.6,12.7,12.7,12.8,12.8,12.9,12.9,13.0,13.1,13.1,13.2,13.3,13.4,13.5,13.4,13.5,13.6,13.6,13.7,13.8,13.8,13.9,13.9,13.9,14.0,14.0,14.0,14.0)

For the first line, the sample is made up of (t,a), and for the second line, the sample is made up of (a,p) where a is a third vector given by

a = seq(10, 14, by = 0.1)

For example, the first point for the sample corresponding to the first vector would be (10.0,10.0) and the second point would be (10.0,10.1). The first point for the sample corresponding to the second vector would be (10.0,12.3) and the second point would be (10.1,12.3).

What I originally tried to do is estimate the lines using polynomials produced by lm models, but those don't seem to always work:

plot(a,t, xlim=c(10,14), ylim=c(10,14), col="purple")
points(p,a, col="red")

fit4p <- lm(a~poly(p,3,raw=TRUE))
fit4t <- lm(t~poly(a,3,raw=TRUE))
lines(a, predict(fit4t, data.frame(x=a)), col="purple", xlim=c(10,14), ylim=c(10,14),type="l",xlab="p",ylab="t")
lines(p, predict(fit4p, data.frame(x=a)), col="green")

fit4pCurve <- function(x) coef(fit4p)[1] +x*coef(fit4p)[2]+x^2*coef(fit4p)[3]+x^3*coef(fit4p)[4]
fit4tCurve <- function(x) coef(fit4t)[1] +x*coef(fit4t)[2]+x^2*coef(fit4t)[3]+x^3*coef(fit4t)[4]

a_opt1 = optimise(f=function(x) abs(fit4pCurve(x)-fit4tCurve(x)), c(10,14))$minimum
b_opt1 = as.numeric(fit4pCurve(a_opt1))

EDIT:
After fixing the type, I get the correct answer, but it doesn't always work if the samples don't come back as cleanly.

So my question can be broken down a few ways. First, is there a better way to accomplish what I'm trying to do. I know what I'm doing isn't perfectly accurate by any means, but it seems like a decent approximation for my purposes. Second, if there isn't a better way, is there a way I could improve on the methodology I have listed above.

Body:
Restart your R session, make sure all variables are cleared and copy/paste this code. I found a few mistakes in referenced variables. Also note that R is case sensitive. My suspicion is that you've been overwriting variables.

plot(a,t, xlim=c(10,14), ylim=c(10,14), col="purple")
points(p,a, col="red")

fit4p <- lm(a~poly(p,3,raw=TRUE))
fit4t <- lm(t~poly(a,3,raw=TRUE))
lines(a, predict(fit4t, data.frame(x=a)), col="purple", xlim=c(T,P), ylim=c(10,14),type="l",xlab="p",ylab="t")
lines(p, predict(fit4p, data.frame(x=a)), col="green")

fit4pCurve <- function(x) coef(fit4p)[1] +x*coef(fit4p)[2]+x^2*coef(fit4p)[3]+x^3*coef(fit4p)[4]
fit4tCurve <- function(x) coef(fit4t)[1] +x*coef(fit4t)[2]+x^2*coef(fit4t)[3]+x^3*coef(fit4t)[4]

a_opt = optimise(f=function(x) abs(fit4pCurve(x)-fit4tCurve(x)), c(T,P))$minimum
b_opt = as.numeric(fit4pCurve(a_opt))

As you will see:

> a_opt
[1] 12.24213
> b_opt
[1] 10.03581


问:
Show div on click of another div - not working
I'm trying to make div .PA show when clicking on #toggle_pa and make it all save, but it won't work.

I don't know what to edit.

```<code>var $content0 = $('.PA');

if (localStorage.getItem('isVisible') === 'true') {
    $content0.addClass('pa_visible');
    $content0.removeClass('pa_content');
}

$('#toggle_PA').on('click', function() {
    $content0.toggleClass('pa_visible');
    $content0.addClass('pa_content');
    localStorage.setItem('isVisible', $content0.hasClass('pa_visible'));
});
</code>```

Full code:
https://codepen.io/mSyx/pen/yWGxNZ

Here, clicking on #toggle_PA won't do anything.
Any idea ?

答:
From the console of the codepen:

```<code>Uncaught ReferenceError: $ is not defined
</code>```

Adding this code into the top of your html made the pen work and do as expected:

```<code><script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</code>```

Body:
I'm trying to make div .PA show when clicking on #toggle_pa and make it all save, but it won't work.

I don't know what to edit.

var $content0 = $('.PA');

if (localStorage.getItem('isVisible') === 'true') {
    $content0.addClass('pa_visible');
    $content0.removeClass('pa_content');
}

$('#toggle_PA').on('click', function() {
    $content0.toggleClass('pa_visible');
    $content0.addClass('pa_content');
    localStorage.setItem('isVisible', $content0.hasClass('pa_visible'));
});

Full code:
https://codepen.io/mSyx/pen/yWGxNZ

Here, clicking on #toggle_PA won't do anything.
Any idea ?

Body:
From the console of the codepen:

Uncaught ReferenceError: $ is not defined

Adding this code into the top of your html made the pen work and do as expected:

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>


问:
Can I call separate function in useEffect?
Can I call another separate function in useEffect?

I am calling another function in useEffect but after saving the file it is automatically adding that function in array parameters of useEffect.

See the code below for proper understanding.

Before saving file:

useEffect(() => {
  getData()
  console.log("useEffect ran...");
}, [query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
  .then(response => response.json())
  .then(json => setData(json));
}
```
<p>after saving file:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
  getData();
  console.log("useEffect ran...");
}, [getData, query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
    .then(response => response.json())
    .then(json => setData(json));
}
</code>```

it is running again and again.

答: If you move your getData function inside useEffect, you won’t have to include it as a dependency, and useEffect will only run when query changes.

Body:
Can I call another separate function in useEffect?

I am calling another function in useEffect but after saving the file it is automatically adding that function in array parameters of useEffect.

See the code below for proper understanding.

Before saving file:

useEffect(() => {
  getData()
  console.log("useEffect ran...");
}, [query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
  .then(response => response.json())
  .then(json => setData(json));
}

after saving file:

useEffect(() => {
  getData();
  console.log("useEffect ran...");
}, [getData, query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
    .then(response => response.json())
    .then(json => setData(json));
}

it is running again and again.


问:
error messages in ES6 class instantiation
After years of using JavaScript, I am about to write my first JS class (!). What I'd like to do is to throw an error if a required constructor parameter is not provided. Kinda like so

class Foo {
    constructor(options) {
        super(options);

        if (!(this.reqd = options.reqd)) {
            return 'error: 'reqd' is required'
        }

        this.optional = options.optional;
    }
}
```

const f = new Foo({optional: 'frob'}) would throw an error, but const f = new Foo({reqd: 'blub'}) or const f = new Foo({reqd: 'blub', optional: 'frob'}) would work.

Can this be done?

答:
Check that the options object has a reqd property with hasOwnProperty, and if it doesn't, throw an error:

class Foo {
    constructor(options) {
        // super(options);
        if (!options.hasOwnProperty('reqd')) {
          throw new Error('reqd property is required');
        }
        this.reqd = options.reqd;
        // if you don't want to assign `undefined` for a non-existent optional property,
        // use a hasOwnProperty check before assigning
        this.optional = options.optional;
    }
}

const f1 = new Foo({ reqd: 'val' });
console.log('next');
const f2 = new Foo({ optional: 'val' });```

If you want an error to be thrown, you have to explicitly throw it, else there won't be an error (or, at least not until later). Just returning a string is not erroneous.

Body:
After years of using JavaScript, I am about to write my first JS class (!). What I'd like to do is to throw an error if a required constructor parameter is not provided. Kinda like so

class Foo {
    constructor(options) {
        super(options);

        if (!(this.reqd = options.reqd)) {
            return 'error: 'reqd' is required'
        }

        this.optional = options.optional;
    }
}

const f = new Foo({optional: 'frob'}) would throw an error, but const f = new Foo({reqd: 'blub'}) or const f = new Foo({reqd: 'blub', optional: 'frob'}) would work.

Can this be done?

Body:
Check that the options object has a reqd property with hasOwnProperty, and if it doesn't, throw an error:

class Foo {
    constructor(options) {
        // super(options);
        if (!options.hasOwnProperty('reqd')) {
          throw new Error('reqd property is required');
        }
        this.reqd = options.reqd;
        // if you don't want to assign `undefined` for a non-existent optional property,
        // use a hasOwnProperty check before assigning
        this.optional = options.optional;
    }
}

const f1 = new Foo({ reqd: 'val' });
console.log('next');
const f2 = new Foo({ optional: 'val' });

If you want an error to be thrown, you have to explicitly throw it, else there won't be an error (or, at least not until later). Just returning a string is not erroneous.


问:
How to move all non-null values to the top of my column?
I have the following data in my table:

```<code>   | Id  |  lIST_1      |
   ----------------------
   | 1   |  NULL        |
   | 2   |  JASON       |
   | 3   |  NULL        |
   | 4   |  BANDORAN    |
   | 5   |  NULL        |
   | 6   |  NULL        |
   | 7   |  SMITH       |
   | 8   |  NULL        |
</code>```

How can I write a query to get the output below?

```<code>   | Id  |  lIST_1
   -----------------------
   | 1   |  JASON        |
   | 2   |  BANDORAN     |
   | 3   |  SMITH        |
   | 4   |  NULL         |
   | 5   |  NULL         |
   | 6   |  NULL         |
   | 7   |  NULL         |
   | 8   |  NULL         |
</code>```

答:
You can use order by:

```<code>select row_number() over (order by (select null)) as id, t.list_1
from t
order by (case when list_1 is not null then 1 else 2 end)
</code>```

It is unclear why you would want id to change values, but you can use row_number() for that.

EDIT:

If you want to change the id, then you can do:

```<code>with toupdate as (
      select row_number() over (order by (case when list_id is not null then 1 else 2 end), id
                               ) as new_id,
             t.*
      from t
     )
update toupdate
    set id = new_id
    where id <> new_id;  -- no need to update if the value remains the same
</code>```

Body:
I have the following data in my table:

   | Id  |  lIST_1      |
   ----------------------
   | 1   |  NULL        |
   | 2   |  JASON       |
   | 3   |  NULL        |
   | 4   |  BANDORAN    |
   | 5   |  NULL        |
   | 6   |  NULL        |
   | 7   |  SMITH       |
   | 8   |  NULL        |

How can I write a query to get the output below?

   | Id  |  lIST_1
   -----------------------
   | 1   |  JASON        |
   | 2   |  BANDORAN     |
   | 3   |  SMITH        |
   | 4   |  NULL         |
   | 5   |  NULL         |
   | 6   |  NULL         |
   | 7   |  NULL         |
   | 8   |  NULL         |

Body:
You can use order by:

select row_number() over (order by (select null)) as id, t.list_1
from t
order by (case when list_1 is not null then 1 else 2 end)

It is unclear why you would want id to change values, but you can use row_number() for that.

EDIT:

If you want to change the id, then you can do:

with toupdate as (
      select row_number() over (order by (case when list_id is not null then 1 else 2 end), id
                               ) as new_id,
             t.*
      from t
     )
update toupdate
    set id = new_id
    where id <> new_id;  -- no need to update if the value remains the same


问:
Git remote clone
I've git repo on remote server. I have ssh access to this server. When I try to clone the repo with command git clone ssh://nick@ip_addres:9022/repo.git I can't clone it. Error that appear is
git clone ssh://nick@ip_address:9022/repo.git
Cloning into repo...
fatal: '/repo.git' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

答:
Just a (legitimate ;)) guess

```<code>git clone ssh://nick@ip_adress:9022/~nick/repo.git
</code>```

This is a consequence from @Matthieu answer. I dont assume, that there is really a directory repo.git in the root of your server. This answer expects, that the repo is in 'nick's home.

Title: Git remote clone

Body:
Just a (legitimate ;)) guess

git clone ssh://nick@ip_adress:9022/~nick/repo.git

This is a consequence from @Matthieu answer. I dont assume, that there is really a directory repo.git in the root of your server. This answer expects, that the repo is in 'nick's home.


问:
How to choose HTTP status code for unavailable event
Description:

The user inquires about the availability of the event on a given day.

Question:
Which response code should I send back if new event can not be created on this day? 404? 400? 422?

My choice:
I chose the "404 Not Found" status code:

```<code>{
  "statusCode": 404,
  "error": "Not Found",
  "message": "The event can not be created on the selected date."
}
</code>```

答: Your question is entirely opinion based. You should try learning about various status codes and their reasons. In your case, you may find status code 410 useful, but again, this is entirely opinion based. </p>

Body:
Description:

The user inquires about the availability of the event on a given day.

Question:
Which response code should I send back if new event can not be created on this day? 404? 400? 422?

My choice:
I chose the "404 Not Found" status code:

{
  "statusCode": 404,
  "error": "Not Found",
  "message": "The event can not be created on the selected date."
}


问:
Issue with postgres copy of very large CSV freezing Ubuntu
I'm having issues populating postgres tables with a very large csv file (~40gb) using the COPY command. This is my first time really using SQL/postgres, but I have several years experience in R/python/linux.

```<code>CREATE DATABASE exampledb OWNER exampleuser;

#create schema
\c exampledb;
CREATE SCHEMA exampledbSC;
set search_path to exampledbSC;

#this creates the tables
psql 'dbname=exampledb user=exampleuser options=--search_path=exampledbSC' -f postgres_create_tables.sql

#this populates the tables with csv data
psql 'dbname=exampledb user=exampleuser options=--search_path=exampledbSC' -f postgres_load_data.sql -v data_dir='/home/user/datafolder'
</code>```

The inside of the last script has several \copy calls between the csvs and tables like so:

```<code>--  Load Data for Table table1
\copy table1 FROM 'table1.csv' DELIMITER ',' CSV HEADER NULL ''
--  Load Data for Table table2
\copy table2 from 'table2.csv' delimiter ',' csv header NULL ''
</code>```

The first 3 \copy execute fine, but the 4th is the 40gb file - eventually I loose control of my keyboard and clicking ability in Ubuntu (but can move mouse). I have left the program in this state for about ~8hours as the readme specifically states it could be a multi hour process, but this seems abnormal. I am on a local machine with 16 cores, 32gb RAM access data on a M.2 nvme drive.Any help is appreciated!

答: The issue had something to do with me running postgres-10, but the table building script being for previous versions. There was a second version 10 of the script I used that finished in under an hour. </p>

Body:
I'm having issues populating postgres tables with a very large csv file (~40gb) using the COPY command. This is my first time really using SQL/postgres, but I have several years experience in R/python/linux.

CREATE DATABASE exampledb OWNER exampleuser;

#create schema
\c exampledb;
CREATE SCHEMA exampledbSC;
set search_path to exampledbSC;

#this creates the tables
psql 'dbname=exampledb user=exampleuser options=--search_path=exampledbSC' -f postgres_create_tables.sql

#this populates the tables with csv data
psql 'dbname=exampledb user=exampleuser options=--search_path=exampledbSC' -f postgres_load_data.sql -v data_dir='/home/user/datafolder'

The inside of the last script has several \copy calls between the csvs and tables like so:

--  Load Data for Table table1
\copy table1 FROM 'table1.csv' DELIMITER ',' CSV HEADER NULL ''
--  Load Data for Table table2
\copy table2 from 'table2.csv' delimiter ',' csv header NULL ''

The first 3 \copy execute fine, but the 4th is the 40gb file - eventually I loose control of my keyboard and clicking ability in Ubuntu (but can move mouse). I have left the program in this state for about ~8hours as the readme specifically states it could be a multi hour process, but this seems abnormal. I am on a local machine with 16 cores, 32gb RAM access data on a M.2 nvme drive.Any help is appreciated!


问:
Unable to change varchar column to date type
I have a table in my SQL Server 2017 database that contains a varchar(10) column whose values all conform precisely to date. Here are some sample values, but there are many more:

```<code>2014-06-30
2004-05-06
2014-06-30
2001-08-18
2004-05-06
2009-06-30
2001-08-18
2004-05-06
2009-06-30
2001-08-18
2004-05-06
</code>```

I am trying to convert this column to a date:

```<code>alter table SourceTable1 alter column END_DATE date;
</code>```

...but I always get this error:

Conversion failed when converting date and/or time from character
  string.

I have examined the data and 100% of the column values conform to the date type. How can I change the column to date type?

答:
I did a simple test and it worked:

```<code>create table #t (t varchar(10))
insert into #t values ('2001-08-18')

alter table #t alter column t date
</code>```

Another with something that looks like date but it isn't (got the same error as you):

```<code>create table #tt (t varchar(10))
insert into #tt values ('2001-08-32')

alter table #tt alter column t date
</code>```

For sure you have a row that contains a varchar(10) that is not convertable. You can find this values by using a select like this:

```<code>select try_cast(yourColumn as date) as tryCastyourColumn,  yourColumn
from Yourtable
where try_cast(yourColumn as date) is null
</code>```

Body:
I have a table in my SQL Server 2017 database that contains a varchar(10) column whose values all conform precisely to date. Here are some sample values, but there are many more:

2014-06-30
2004-05-06
2014-06-30
2001-08-18
2004-05-06
2009-06-30
2001-08-18
2004-05-06
2009-06-30
2001-08-18
2004-05-06

I am trying to convert this column to a date:

alter table SourceTable1 alter column END_DATE date;

...but I always get this error:

Conversion failed when converting date and/or time from character
  string.

I have examined the data and 100% of the column values conform to the date type. How can I change the column to date type?

Body:
I did a simple test and it worked:

create table #t (t varchar(10))
insert into #t values ('2001-08-18')

alter table #t alter column t date

Another with something that looks like date but it isn't (got the same error as you):

create table #tt (t varchar(10))
insert into #tt values ('2001-08-32')

alter table #tt alter column t date

For sure you have a row that contains a varchar(10) that is not convertable. You can find this values by using a select like this:

select try_cast(yourColumn as date) as tryCastyourColumn,  yourColumn
from Yourtable
where try_cast(yourColumn as date) is null


问:
How to change FontAwesome's glyph color inside JFXButton through hover selector in CSS?
I have a toolbar (VBox) with several JFXButtons. All button's caption and glyphs are white. I want to change only glyph color when mousepointer is over the button.

The CSS file:

```<code>.button {
    -fx-text-fill: white;
    -fx-fill: white;
}

.button .glyph-icon:hover {
    -fx-background-color: derive(black, 15%);
    -fx-fill: #cc8f1e;
}
</code>```

答: change the 'color' property for glyph</p>

Body:
I have a toolbar (VBox) with several JFXButtons. All button's caption and glyphs are white. I want to change only glyph color when mousepointer is over the button.

The CSS file:

.button {
    -fx-text-fill: white;
    -fx-fill: white;
}

.button .glyph-icon:hover {
    -fx-background-color: derive(black, 15%);
    -fx-fill: #cc8f1e;
}

Body: change the 'color' property for glyph


问:
Editing Date field - RoR
all,

Am new to RoR and hence needed some guidance w.r.t Date field.

Background:

1 > I create a model object using rails generate scaffold <Model> name:string remainderDate: date

2 > Now when I have deployed the model to DB using rake db:migrate and on opening the URL: localhost:3000/<Model>s/new, the displayed date field is in the format YYYY MM DD, all 3 separate fields with dropdown with

YYYY values >=2006 and <=2016

MM values >= January and <= December (obvious)

DD values >= 1 and <=31

Question 1:

1> Where is the code for setting the values to these fields?

2> Can I change the format to MM DD YYYY?

3> Can I restrict the values being added to the list? i.e. for the current year 2011, only months starting from April should be shown and only dates starting current day should be shown

4> Where can I change the display text for the new form? I opened up new.html.erb and could not understand where the display text is set. I also opened up _form.html.erb and could not locate where necessary changes can be done?

答:
Regarding formats of the date field you want to pass the string in the way rails already is because mysql accepts it without modification.  That said you can certainly change how the user enters the data on the form for a new record.  Look for the view code in</p>

```<code>app/views/<model>/_form.html.erb
</code>```

Title: Editing Date field - RoR

Body:
Regarding formats of the date field you want to pass the string in the way rails already is because mysql accepts it without modification.  That said you can certainly change how the user enters the data on the form for a new record.  Look for the view code in

app/views/<model>/_form.html.erb


问:
Angular --- How to reset countdown timer on Websocket message?
I used a countdown timer solution from this example: Stackblitz --- It is from accepted answer of this question.

The difference is I don't use html input to reset my timer but Websocket message like this (the switch is the difference):

turn-timer.directive.ts:

```<code>@Directive({
  selector: '[counter]'
})
export class CounterDirective implements OnChanges, OnDestroy {

  private counter$ = new Subject<any>();
  private countSub$: SubscriptionLike;

  @Input() counter: number;
  @Input() interval: number;
  @Output() value = new EventEmitter<number>();

  constructor(private client: ClientService)
  {

    this.countSub$ = this.counter$.pipe(
      switchMap((options: any) =>
        timer(0, options.interval).pipe(
          take(options.count),
          tap(() => this.value.emit(--options.count))
        )
      )
    ).subscribe();

    this.client.messages.subscribe(msg =>
    {
      switch (msg.SUBJECT)
      {
        case 'TT_UPDATE':
        {
          this.counter = msg.COUNTER;
        }
        break;
        default:
        break;
      }
    });
  }

  ngOnChanges() {
    this.counter$.next({ count: this.counter, interval: this.interval });
  }
  ngOnDestroy() {
    this.countSub$.unsubscribe();
  }
}
</code>```

That did not reset timer at all so I tried sending the message to initial component but that reseted timer only the first time it was sent.

turn-timer.component.ts:

```<code>@Component({
  selector: 'app-turn-timer',
  templateUrl: './turn-timer.component.html',
  styleUrls: ['../../../../angry_styles.css']
})

export class TurnTimerComponent implements OnInit
{
    public counter : number = 60;
    interval = 1000;
    public current_player: string;

    constructor (private ll: LL, private client: ClientService, private players: PlayersInfo)
    {
        this.client.messages.subscribe(msg =>
        {
            switch (msg.SUBJECT)
            {
                case 'TT_UPDATE':
                {
                    this.counter = msg.COUNTER;
                    this.current_player = msg.PLAYER_ON_TURN;
                }
                break;
                default:
                break;
            }
        });
    }
    ngOnInit(): void {}
}
</code>```

There is the html:

```<code><ng-container [counter]="counter" [interval]="interval" (value)="value = $event">
    <span>{{ value }}</span>
</ng-container>
</code>```

The original author of the answer had

```<code><input type="number" [(ngModel)]="counter"/>
</code>```

in his html and every time value of this

```<code><input>
</code>```

changed, the countdown timer was reseted to that value. However in my app it should be reseted by C# server that sends Websocket messages.

So what result I expect: On every "TT_UPDATE" message I expect the {{ value }} in HTML to change to the value of msg.COUNTER. The this.counter$.pipe then decrements {{value}}. That is working fine. Just the reseting part does not work.

Btw. Every message was received successfully, I checked the names of the fields. Here is definition of messages:

```<code>export interface Message {
  SUBJECT: string;
  COUNTER?: number;       // This is the problematic field.
  PLAYER_ON_TURN?: string;
}

@Injectable()
export class ClientService
{
  public messages: Subject < Message > ;

  constructor(wsService: WebsocketService) {
    this.messages = < Subject < Message >> wsService
      .connect(CHAT_URL).pipe(
        map((response: MessageEvent): Message => {
          console.log(response);
          const data = JSON.parse(response.data);
          return data;
      }), share());
  }
</code>```

I deleted imports and paths from the code so it is shorter but they are correct. Also no errors in browser console were found.

答:
In the end, I found out the solution myself. I didn't even need this.counter for this. I modified what happens after receiving the message:

```<code>this.client.messages.subscribe(msg =>
{
  switch (msg.SUBJECT)
  {
    case 'TT_UPDATE':
    {
      this.ResetTimer(msg.COUNTER);    // THIS IS NEW !!!
    }
    break;
    default:
    break;
  }
});
</code>```

}

Then I created a new method that resets the countdown timer to value received from the message:

```<code>ResetTimer(updatedValue: number)
  {
    this.counter$.next({ count: updatedValue, interval: this.interval });
  }
</code>```

As I don't change the interval I let it be the same. Sometimes I wonder how things are easy.

Body:
I used a countdown timer solution from this example: Stackblitz --- It is from accepted answer of this question.

The difference is I don't use html input to reset my timer but Websocket message like this (the switch is the difference):

turn-timer.directive.ts:

@Directive({
  selector: '[counter]'
})
export class CounterDirective implements OnChanges, OnDestroy {

  private counter$ = new Subject<any>();
  private countSub$: SubscriptionLike;

  @Input() counter: number;
  @Input() interval: number;
  @Output() value = new EventEmitter<number>();

  constructor(private client: ClientService)
  {

    this.countSub$ = this.counter$.pipe(
      switchMap((options: any) =>
        timer(0, options.interval).pipe(
          take(options.count),
          tap(() => this.value.emit(--options.count))
        )
      )
    ).subscribe();

    this.client.messages.subscribe(msg =>
    {
      switch (msg.SUBJECT)
      {
        case 'TT_UPDATE':
        {
          this.counter = msg.COUNTER;
        }
        break;
        default:
        break;
      }
    });
  }

  ngOnChanges() {
    this.counter$.next({ count: this.counter, interval: this.interval });
  }
  ngOnDestroy() {
    this.countSub$.unsubscribe();
  }
}

That did not reset timer at all so I tried sending the message to initial component but that reseted timer only the first time it was sent.

turn-timer.component.ts:

@Component({
  selector: 'app-turn-timer',
  templateUrl: './turn-timer.component.html',
  styleUrls: ['../../../../angry_styles.css']
})

export class TurnTimerComponent implements OnInit
{
    public counter : number = 60;
    interval = 1000;
    public current_player: string;

    constructor (private ll: LL, private client: ClientService, private players: PlayersInfo)
    {
        this.client.messages.subscribe(msg =>
        {
            switch (msg.SUBJECT)
            {
                case 'TT_UPDATE':
                {
                    this.counter = msg.COUNTER;
                    this.current_player = msg.PLAYER_ON_TURN;
                }
                break;
                default:
                break;
            }
        });
    }
    ngOnInit(): void {}
}

There is the html:

<ng-container [counter]="counter" [interval]="interval" (value)="value = $event">
    {{ value }}
</ng-container>

The original author of the answer had

<input type="number" [(ngModel)]="counter"/>

in his html and every time value of this

<input>

changed, the countdown timer was reseted to that value. However in my app it should be reseted by C# server that sends Websocket messages.

So what result I expect: On every "TT_UPDATE" message I expect the {{ value }} in HTML to change to the value of msg.COUNTER. The this.counter$.pipe then decrements {{value}}. That is working fine. Just the reseting part does not work.

Btw. Every message was received successfully, I checked the names of the fields. Here is definition of messages:

export interface Message {
  SUBJECT: string;
  COUNTER?: number;       // This is the problematic field.
  PLAYER_ON_TURN?: string;
}

@Injectable()
export class ClientService
{
  public messages: Subject < Message > ;

  constructor(wsService: WebsocketService) {
    this.messages = < Subject < Message >> wsService
      .connect(CHAT_URL).pipe(
        map((response: MessageEvent): Message => {
          console.log(response);
          const data = JSON.parse(response.data);
          return data;
      }), share());
  }

I deleted imports and paths from the code so it is shorter but they are correct. Also no errors in browser console were found.

Body:
In the end, I found out the solution myself. I didn't even need this.counter for this. I modified what happens after receiving the message:

this.client.messages.subscribe(msg =>
{
  switch (msg.SUBJECT)
  {
    case 'TT_UPDATE':
    {
      this.ResetTimer(msg.COUNTER);    // THIS IS NEW !!!
    }
    break;
    default:
    break;
  }
});

}

Then I created a new method that resets the countdown timer to value received from the message:

ResetTimer(updatedValue: number)
  {
    this.counter$.next({ count: updatedValue, interval: this.interval });
  }

As I don't change the interval I let it be the same. Sometimes I wonder how things are easy.


问:
How to find the same values next to each other in multidimensional array?
I tried to write a function that would find in a multidimensional array (with values from 3 to 7) repeating values for at least 3 times next to each other (vertical and horizontal). And if it finds that, change it for a different value. Let's say 1.

I tried to do this by loops but it doesn't seem to be a good way to solve that or I messed it up. Because for some array it works, for some it does not.

Here's my code:

function searching(array) {
  for (i = 0; i < array.length; i++) {
    let horizontal = array[i][0];
    let howMany = 1;

    for (j = 1; j < array[i].length; j++) {
      if (horizontal === array[i][j]) {
        howMany += 1;
        horizontal = array[i][j];
        if (howMany >= 3) {
          for (d = j; d > j - howMany; d--) {
            array[i][d] = 0;
          }
        }
      } else {
        horizontal = array[i][j];
        howMany = 1;
      }

    }

  }

  for (v = 0; v < array.length; v++) {
    let vertical = array[0][v];
    let howMany = 1;
    for (x = 1; x < array.length; x++) {
      if (vertical === array[x][v]) {
        howMany++;
        vertical = array[x][v];
        if (howMany >= 3) {
          for (d = x; d > x - howMany; d--) {
            array[d][v] = 0;
          }
        }
      } else {
        vertical = array[x][v];
        howMany = 1;
      }
    }
  }
}```
</div>
</div>
</p>

<p>The idea is to for example give array:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let array = [
    [3, 4, 5, 6, 7],
    [3, 4, 5, 6, 7],
    [3, 4, 5, 5, 5],
    [3, 5, 6, 7, 4]
  ]</code>```

And the result should be:

let result = [
    [1, 1, 1, 6, 7],
    [1, 1, 1, 6, 7],
    [1, 1, 1, 1, 1],
    [1, 5, 6, 7, 4]
  ]```

Thanks in advance for any ideas how to solve it :) Greetings!

答:
The problems with your current code are

(1) You're only checking individual rows and columns, when you need to be checking them both (eg, with [[2, 2], [2, 5]], when at the starting position [0][0], you need to look at both [0][1] (and its neighbors, if matching) as well as [1][0] (and its neighbors, if matching).

(2) You're not actually checking for adjacency at the moment, you're just counting up the total number of matching elements in a particular row or column.

Iterate over all indicies of the array. If an index has already been checked, return early. Recursively search for neighbors to that index, and if at least 3 matching in total are found, set them all to 1. Put all matching neighbors in the checked set to avoid checking them again (even if there were less than 2 adjacent matches found total).

setAllAdjacentToOne([
  [3, 4, 5, 6, 7],
  [3, 4, 5, 6, 7],
  [3, 4, 5, 5, 5],
  [3, 5, 6, 7, 4]
]);
// all 9s stay, the rest get set to 1:
setAllAdjacentToOne([
  [2, 2, 9, 7, 7],
  [2, 9, 9, 9, 7],
  [3, 4, 4, 5, 5],
  [9, 4, 5, 5, 9]
]);

function setAllAdjacentToOne(input) {
  const output = input.map(subarr => subarr.slice());
  const checked = new Set();
  const getKey = (x, y) => `${x}_${y}`;

  const width = input[0].length;
  const height = input.length;
  const getAllAdjacent = (x, y, numToFind, matches = []) => {
    if (x >= width || x < 0 || y >= height || y < 0) {
      return matches;
    }
    const key = getKey(x, y);
    if (!checked.has(key) && input[y][x] === numToFind) {
      checked.add(key);
      matches.push({ x, y });
      getAllAdjacent(x + 1, y, numToFind, matches);
      getAllAdjacent(x - 1, y, numToFind, matches);
      getAllAdjacent(x, y + 1, numToFind, matches);
      getAllAdjacent(x, y - 1, numToFind, matches);
    }
    return matches;
  };

  output.forEach((innerRowArr, y) => {
    innerRowArr.forEach((num, x) => {
      const allAdjacent = getAllAdjacent(x, y, num);
      if (allAdjacent.length <= 2) {
        return;
      }
      allAdjacent.forEach(({ x, y }) => {
        output[y][x] = 1;
      });
    });
  });
  console.log(JSON.stringify(output));
}```

Body:
I tried to write a function that would find in a multidimensional array (with values from 3 to 7) repeating values for at least 3 times next to each other (vertical and horizontal). And if it finds that, change it for a different value. Let's say 1.

I tried to do this by loops but it doesn't seem to be a good way to solve that or I messed it up. Because for some array it works, for some it does not.

Here's my code:

function searching(array) {
  for (i = 0; i < array.length; i++) {
    let horizontal = array[i][0];
    let howMany = 1;

    for (j = 1; j < array[i].length; j++) {
      if (horizontal === array[i][j]) {
        howMany += 1;
        horizontal = array[i][j];
        if (howMany >= 3) {
          for (d = j; d > j - howMany; d--) {
            array[i][d] = 0;
          }
        }
      } else {
        horizontal = array[i][j];
        howMany = 1;
      }

    }

  }

  for (v = 0; v < array.length; v++) {
    let vertical = array[0][v];
    let howMany = 1;
    for (x = 1; x < array.length; x++) {
      if (vertical === array[x][v]) {
        howMany++;
        vertical = array[x][v];
        if (howMany >= 3) {
          for (d = x; d > x - howMany; d--) {
            array[d][v] = 0;
          }
        }
      } else {
        vertical = array[x][v];
        howMany = 1;
      }
    }
  }
}

The idea is to for example give array:

let array = [
    [3, 4, 5, 6, 7],
    [3, 4, 5, 6, 7],
    [3, 4, 5, 5, 5],
    [3, 5, 6, 7, 4]
  ]

And the result should be:

let result = [
    [1, 1, 1, 6, 7],
    [1, 1, 1, 6, 7],
    [1, 1, 1, 1, 1],
    [1, 5, 6, 7, 4]
  ]

Thanks in advance for any ideas how to solve it :) Greetings!


问:
Site loads normally, but PageSpeed thinks it takes minutes to do so
I am working on the site www.hatsfromoz.com.au
It appears to load OK (not very fast site, but loads in 5-6s at the moment).

However, Google PageSpeed thinks it takes 80-90s to get first data!
Generating of the PageSpeed report takes about 20s, so how is it possible PageSpeed thinks it takes 80-90s?

I tried to load sites from different locations/countries and can not see huge delays.

Any ideas?

Thanks,
Rudolf

答:
Google measures various criteria, including "render-blocking resources"
which take in your case about 74.98s according to the measurement:
https://developers.google.com/speed/pagespeed/insights/?hl=en&url=www.hatsfromoz.com.au

The site is hosted near Sydney (response times from Europe and US are over >160ms), maybe a service like CloudFlare or an CDN would be an option for you.

Test from Sydney, Australia:
https://www.webpagetest.org/result/190601_28_ecb3147f22d762972b4cecb5cb7d6219/

Test from: Zurich, Switzerland:
https://www.webpagetest.org/result/190601_YW_4f90dd07fd8c8a6229055b8167cf1850/

(I can't reach your site from Switzerland at the moment and have to use a VPN)


问:
Thin + Nginx Production ready combination for RubyOnRails Application
I have recently installed Nginx + Thin on my deployment server, but i am not sure how this will perform in last requests & responses situation. lets say 1000/req per sec.

so the speed on thin is good with 10-100 req /per sec

I wanted to know on higher volumes of data being processed on the request/response cluster.

Guide me on this :-)

答:
If you have a single server I think that the main key is, apart from everything already mentioned, is don't skimp on the specs of it. Trying to get too much to run on too little is just a recipe for disaster.

It is also a good idea to get monit or God monitoring your thin instances, I started out with God, but it leaked memory pretty bad on Ruby 1.8.6 so I stop using it in favour of monit. Monit is written in C I believe and has a tiny memory footprint so I'd recommend that one.

If all that seems like a bit much to keep nginx and thin playing nicely you may want to look into an all in one solution like Passenger or LiteSpeed. I have very little experience with these so can offer no substancial advice for them.

OwnerDisplayName: Raghavendra

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dylanfm

OwnerDisplayName: railsninja


答:
I agree with M. Kanarkowski that your examples seem fine, but you probably are missing something. Since you have the 2017 version, run this to check what's wrong:</p>

```<code>select END_DATE
from SourceTable1
where END_DATE is not null and try_convert(date,END_DATE) is null
</code>```

Title: Unable to change varchar column to date type

Body:
I agree with M. Kanarkowski that your examples seem fine, but you probably are missing something. Since you have the 2017 version, run this to check what's wrong:

select END_DATE
from SourceTable1
where END_DATE is not null and try_convert(date,END_DATE) is null


问:
Using heap for big disk sorts
On the official Python docs here, it is mentioned that:

Heaps are also very useful in big disk sorts.   You most probably all
  know that a big sort implies producing “runs” (which are pre-sorted
  sequences, whose size is usually related to the amount of CPU memory),
  followed by a merging passes for these runs, which merging is often
  very cleverly organised.

  It is very important that the initial
  sort produces the longest runs possible.   Tournaments are a good way
  to achieve that.   If, using all the memory available to hold a
  tournament, you replace and percolate items that happen to fit the
  current run, you’ll produce runs which are twice the size of the
  memory for random input, and much better for input fuzzily ordered.

Moreover, if you output the 0’th item on disk and get an input which
  may not fit in the current tournament (because the value “wins” over
  the last output value), it cannot fit in the heap, so the size of the
  heap decreases.   The freed memory could be cleverly reused
  immediately for progressively building a second heap, which grows at
  exactly the same rate the first heap is melting.

  When the first heap
  completely vanishes, you switch heaps and start a new run. Clever and
  quite effective!

I am aware of an algorithm called External sorting in which we:

Break down the input into smaller chunks.

Sort all the chunks individually and write them back to disk one-by-one.

Create a heap and do a k-way merge among all the sorted chunks.

I completely understood external sorting as described on Wikipedia, but am not able to understand the author when they say:

If, using all the memory available to hold a tournament, you replace
  and percolate items that happen to fit the current run, you’ll produce
  runs which are twice the size of the memory for random input, and much
  better for input fuzzily ordered.

and:

Moreover, if you output the 0’th item on disk and get an input which
  may not fit in the current tournament (because the value “wins” over
  the last output value), it cannot fit in the heap, so the size of the
  heap decreases.

What is this heap melting?

答:
Heap melting is not a thing.  It's just the word the author uses for the heap getting smaller as to pull out the smallest items.

The idea he's talking about is a clever replacement for "divide the input into chunks and sort the chunks" part of the external sort.  It produces larger sorted chunks.

The idea is that you first read the biggest chunk you can into memory and arrange it into a heap, then you start writing out the smallest elements from the heap as you read new elements in.

When you read in an element that is smaller than an element you have already written out, it can't go in the current chunk (it would ruin the sort), so you remember it for the next chunk.  Elements that are not smaller than the last one you wrote out can be inserted into the heap.  They will make it out into the current chunk, making the current chunk larger.

Eventually your heap will be empty.  At that point you're done with the current chunk -- heapify all the elements you remembered and start writing out the next chunk.

Title: Using heap for big disk sorts


问:
ClassCastException with CoordinatorLayout in AndroidX project
My project uses AndroidX, and has a CoordinatorLayout, AppbarLayout... I have the dependencies listed in the gradle file but the layout editor is throwing error and keeps saying classes couldn't be found. This causing a render problem but the project compiles and the app is working well.

Gradle (app):

```<code>    dependencies {
//...
//...
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.core:core:1.2.0-alpha01'
    implementation 'androidx.media:media:1.1.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0-alpha01'
    implementation group: 'androidx.coordinatorlayout', name: 'coordinatorlayout', version: '1.0.0'
}
</code>```

XML layout file:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBackgroundGrey"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarlayout"
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                ads:contentScrim="?attr/colorPrimary"
                ads:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    ads:layout_collapseMode="parallax">

                    <com.balysv.materialripple.MaterialRippleLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        ads:mrl_rippleAlpha="0.2"
                        ads:mrl_rippleColor="@color/colorRipple"
                        ads:mrl_rippleHover="true"
                        ads:mrl_rippleOverlay="true">

                        <ImageView
                            android:id="@+id/imv_image"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:contentDescription="@string/text_image_view_descrip"
                            android:scaleType="centerCrop"
                            ads:layout_collapseMode="none"
                            ads:srcCompat="@drawable/ic_launcher_foreground" />

                    </com.balysv.materialripple.MaterialRippleLayout>

                </RelativeLayout>

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/demo_dark_transparent"
                    ads:layout_collapseMode="pin"
                    ads:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

            </com.google.android.material.appbar.CollapsingToolbarLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:foreground="?android:attr/selectableItemBackground"
            ads:behavior_overlapTop="64dp"
            ads:cardCornerRadius="3dp"
            ads:cardElevation="3sp"
            ads:cardPreventCornerOverlap="false"
            ads:cardUseCompatPadding="true"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/nestedScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <include
                        android:id="@+id/lyt_main_content"
                        layout="@layout/include_news_content"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:visibility="visible" />

                    <ViewFlipper
                        android:id="@+id/view_flipper2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:background="#F44336">

                    </ViewFlipper>

                </RelativeLayout>

            </androidx.core.widget.NestedScrollView>

        </androidx.cardview.widget.CardView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Tried almost everything I could without success.

EDIT:

Java class (import):

```<code>import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.widget.NestedScrollView;
</code>```

答:
Convert all the layouts into corresponding androix support layouts.
https://developer.android.com/jetpack/androidx/migrate</p>

Body:
My project uses AndroidX, and has a CoordinatorLayout, AppbarLayout... I have the dependencies listed in the gradle file but the layout editor is throwing error and keeps saying classes couldn't be found. This causing a render problem but the project compiles and the app is working well.

Gradle (app):

    dependencies {
//...
//...
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.core:core:1.2.0-alpha01'
    implementation 'androidx.media:media:1.1.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0-alpha01'
    implementation group: 'androidx.coordinatorlayout', name: 'coordinatorlayout', version: '1.0.0'
}

XML layout file:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBackgroundGrey"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarlayout"
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                ads:contentScrim="?attr/colorPrimary"
                ads:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    ads:layout_collapseMode="parallax">

                    <com.balysv.materialripple.MaterialRippleLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        ads:mrl_rippleAlpha="0.2"
                        ads:mrl_rippleColor="@color/colorRipple"
                        ads:mrl_rippleHover="true"
                        ads:mrl_rippleOverlay="true">

                        <ImageView
                            android:id="@+id/imv_image"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:contentDescription="@string/text_image_view_descrip"
                            android:scaleType="centerCrop"
                            ads:layout_collapseMode="none"
                            ads:srcCompat="@drawable/ic_launcher_foreground" />

                    </com.balysv.materialripple.MaterialRippleLayout>

                </RelativeLayout>

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/demo_dark_transparent"
                    ads:layout_collapseMode="pin"
                    ads:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

            </com.google.android.material.appbar.CollapsingToolbarLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:foreground="?android:attr/selectableItemBackground"
            ads:behavior_overlapTop="64dp"
            ads:cardCornerRadius="3dp"
            ads:cardElevation="3sp"
            ads:cardPreventCornerOverlap="false"
            ads:cardUseCompatPadding="true"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/nestedScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <include
                        android:id="@+id/lyt_main_content"
                        layout="@layout/include_news_content"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:visibility="visible" />

                    <ViewFlipper
                        android:id="@+id/view_flipper2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:background="#F44336">

                    </ViewFlipper>

                </RelativeLayout>

            </androidx.core.widget.NestedScrollView>

        </androidx.cardview.widget.CardView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Tried almost everything I could without success.

EDIT:

Java class (import):

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.widget.NestedScrollView;


问:
How to convert Map to Java.util.Properties?
Is there a way to convert from Map to java.util.Properties?

For example, the following Map I would like to convert into java.util.Properties:

```<code>Map("x" -> 24, "y" -> 25, "z" -> 26)
</code>```

答:
You could use putAll from Properties, but it expects Java's map, so you'd also need to do the conversion:

```<code>import scala.collection.JavaConverters._

val m = Map("x" -> 24, "y" -> 25, "z" -> 26)
val properties = new Properties()
properties.putAll(m.mapValues(_.toString).asJava)
</code>```

As MarioGalic noticed in comment all values stored in properties should be Strings (even though you could theoretically store any object). From docs:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a "compromised" Properties object that contains a non-String key.

Because of that, you'd probably need to call mapValues(_.toString):

```<code>properties.putAll(m.mapValues(_.toString).asJava)
</code>```

Body:
Is there a way to convert from Map to java.util.Properties?

For example, the following Map I would like to convert into java.util.Properties:

Map("x" -> 24, "y" -> 25, "z" -> 26)

Body:
You could use putAll from Properties, but it expects Java's map, so you'd also need to do the conversion:

import scala.collection.JavaConverters._

val m = Map("x" -> 24, "y" -> 25, "z" -> 26)
val properties = new Properties()
properties.putAll(m.mapValues(_.toString).asJava)

As MarioGalic noticed in comment all values stored in properties should be Strings (even though you could theoretically store any object). From docs:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a "compromised" Properties object that contains a non-String key.

Because of that, you'd probably need to call mapValues(_.toString):

properties.putAll(m.mapValues(_.toString).asJava)


问:
EPP For Domain Registration connection fails when using a certificate
I am using EPP (Extensible Provisioning Protocol) to perform domain registration operations.

Everything works fine but when I use a certificate, the login request fails.

Let us say I have certificate in C:\Folder\epp.crt and using the following code:

```<code>var tcpTransport = new TcpTransport(url, port, new X509Certificate("C:\Folder\epp.crt"), true);
var service = new Service(tcpTransport);
service.Connect();
</code>```

This code executes just fine and service is connected. That means connection to URL is established using certificate. Now, I try to login with:

```<code>service.Execute(logingCmd);
</code>```

But this gives me "Server requires Client certificate validation, no client certificate provided".

Why? Should there be any flag for certificate in login command?

答:
Per RFC5734, EPP uses TLS, not TCP. This RFC also mandates use of client certificates.

Your question lacks details about the content of epp.crt (where is the associated key?) or the language you use. The TLS negotiation, including validation of client certificate happens before the EPP login, but the exact moment may be hidden by the library you use to connect.

So to answer your "Should there be any flag for certificate in Login Command?", no there should not as the certificate handling is part of the transport setup, not the EPP commands. Your problem is probably more around your use of TcpTransport.

You can use a network sniffer to see exactly what happens. Registries are probably not offering TLS1.3 for now so you should still be able to see the TLS exchanges, including your client providing a certificate.

Also the registry you connect to should be able to help you.

Body:
I am using EPP (Extensible Provisioning Protocol) to perform domain registration operations.

Everything works fine but when I use a certificate, the login request fails.

Let us say I have certificate in C:\Folder\epp.crt and using the following code:

var tcpTransport = new TcpTransport(url, port, new X509Certificate("C:\Folder\epp.crt"), true);
var service = new Service(tcpTransport);
service.Connect();

This code executes just fine and service is connected. That means connection to URL is established using certificate. Now, I try to login with:

service.Execute(logingCmd);

But this gives me "Server requires Client certificate validation, no client certificate provided".

Why? Should there be any flag for certificate in login command?


问:
Why only last character of the string in Angular async pipe binding is shown?
component.html:

```<code><div *ngIf="!isWaiting">
  <h2>LOGIN</h2>
  <p>{{ message | async }}</p>
  <div *ngIf="!(isLoggedIn | async)">
    <button (click)="login()">{{'StrLogin' | translate}}</button>
  </div>
  <div *ngIf="(isLoggedIn | async)">
    <button (click)="logout()">{{'StrLogout' | translate}}</button>
  </div>
</div>
<div *ngIf="isWaiting">
  <p>initializing</p>
</div>
</code>```

component.ts

```<code>  message: Observable<string>;

  login(name : string, password : string): void {
    this.message = this.tokenService.login(name, password)
    .pipe(
      map((token) => {
        console.debug('login succeeded: %s', JSON.stringify(token));
        return 'success';
      }),
      catchError(err => {
        console.debug('login failed: %s', JSON.stringify(err));
        return 'failed';
      })
    );
  }
</code>```

When this fails only the letter 'd' (of the 'failed') is displayed. If I change it to:

```<code>      catchError(err => {
        console.debug('login failed: %s', JSON.stringify(err));
        return '123';
      })
</code>```

it displays 3.

答:
The catchError() operator expects the callback function to return an observable. I'm not sure why it renders 3 but most likely the string was converted into an observable array that emits each character in sequence.

https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catchError.ts#L90

```<code>      catchError(err => {
        console.debug('login failed: %s', JSON.stringify(err));
        return of('failed');
      })
</code>```

https://www.learnrxjs.io/operators/error_handling/catch.html

When using the async pipe in templates. Keep in mind that it will call subscribe if the DOM is mutated by a *ngIf higher up. So if the observable is sourced from an HTTP request, then add a shareReplay(1) operator and only use the same object reference in the template.

Body:
component.html:

LOGIN

{{ message | async }}

    <button (click)="login()">{{'StrLogin' | translate}}</button>

    <button (click)="logout()">{{'StrLogout' | translate}}</button>

initializing

component.ts

  message: Observable<string>;

  login(name : string, password : string): void {
    this.message = this.tokenService.login(name, password)
    .pipe(
      map((token) => {
        console.debug('login succeeded: %s', JSON.stringify(token));
        return 'success';
      }),
      catchError(err => {
        console.debug('login failed: %s', JSON.stringify(err));
        return 'failed';
      })
    );
  }

When this fails only the letter 'd' (of the 'failed') is displayed. If I change it to:

      catchError(err => {
        console.debug('login failed: %s', JSON.stringify(err));
        return '123';
      })

it displays 3.

Body:
The catchError() operator expects the callback function to return an observable. I'm not sure why it renders 3 but most likely the string was converted into an observable array that emits each character in sequence.

https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catchError.ts#L90

      catchError(err => {
        console.debug('login failed: %s', JSON.stringify(err));
        return of('failed');
      })

https://www.learnrxjs.io/operators/error_handling/catch.html

When using the async pipe in templates. Keep in mind that it will call subscribe if the DOM is mutated by a *ngIf higher up. So if the observable is sourced from an HTTP request, then add a shareReplay(1) operator and only use the same object reference in the template.


问:
Programming: Principles and Practice Using C++ chapter 4 drill step 6 : General question about numeric range
I want to prompt the user for some double, then store the smallest and largest value and then prints a text. This is the code I have so far:

```<code>#include <iostream>
#include <string>
#include <cmath>
#include <vector>

using namespace std;

int main()
{
    double min = 1000000000; // Here is my issue !
    double max = -100000000; // Here is my issue !
    for (double input; cin >> input;)
    {
        if (input == '|')
            return 0;
        else if (input < min)
        {
            min = input;
            cout << "The smallest so far\n";
        }
        else if (input > max)
        {
            max = input;
            cout << "The largest so far\n";
        }
        else
            cout << "\n";
    }
}
</code>```

So my code is working fine and doing what I want, but I have a question about the way to handle the double min and max.
I must give them a value to get my program working, but giving them a value inpact the user. If I don't set them high or low enough the user might input value that don't trigger the program.
So I set them up at arbitrary high/low number.
But I wonder if there is a better solution for this.

答:
I came too late to answer the question, however I wanted to draw your attention on that in your case you must use lowest() and not min()

```<code>double min = std::numeric_limits<double>::max();
double max = std::numeric_limits<double>::lowest();  // <-- Attention, not min
</code>```

using min() instead of lowest() is a common error (yes the name is misleading)

From cppreference:

lowest() [static] (C++11) returns the lowest finite value of the given
  type  (public static member function)

min() [static] returns the smallest finite value of the given type
  (public static member function)

```<code>std::cout << std::numeric_limits<double>::min();
std::cout << std::numeric_limits<double>::lowest();
</code>```

prints:

```<code>2.22507e-308    <-- min    : smallest value
-1.79769e+308   <-- lowest : is what you need in your case
</code>```

Body:
I want to prompt the user for some double, then store the smallest and largest value and then prints a text. This is the code I have so far:

#include <iostream>
#include <string>
#include <cmath>
#include <vector>

using namespace std;

int main()
{
    double min = 1000000000; // Here is my issue !
    double max = -100000000; // Here is my issue !
    for (double input; cin >> input;)
    {
        if (input == '|')
            return 0;
        else if (input < min)
        {
            min = input;
            cout << "The smallest so far\n";
        }
        else if (input > max)
        {
            max = input;
            cout << "The largest so far\n";
        }
        else
            cout << "\n";
    }
}

So my code is working fine and doing what I want, but I have a question about the way to handle the double min and max.
I must give them a value to get my program working, but giving them a value inpact the user. If I don't set them high or low enough the user might input value that don't trigger the program.
So I set them up at arbitrary high/low number.
But I wonder if there is a better solution for this.

Body:
I came too late to answer the question, however I wanted to draw your attention on that in your case you must use lowest() and not min()

double min = std::numeric_limits<double>::max();
double max = std::numeric_limits<double>::lowest();  // <-- Attention, not min

using min() instead of lowest() is a common error (yes the name is misleading)

From cppreference:

lowest() [static] (C++11) returns the lowest finite value of the given
  type  (public static member function)

min() [static] returns the smallest finite value of the given type
  (public static member function)

std::cout << std::numeric_limits<double>::min();
std::cout << std::numeric_limits<double>::lowest();

prints:

2.22507e-308    <-- min    : smallest value
-1.79769e+308   <-- lowest : is what you need in your case


问:
Get values in array of objects Laravel
I have an array of objects in the telescope as follows. I need to get only the number and each number is placed in a numerical variable

```<code>"[[{"num":333}],[{"num":433}],[{"num":3033}],[{"num":533}],[{"num":514}],[{"num":1440}]]"
</code>```

Ex

```<code>$var1 = 333
$var2 = 433
</code>```

In the telescope appears exactly like this

```<code>"[[{"num":333}],[{"num":433}],[{"num":3033}],[{"num":533}],[{"num":514}],[{"num":1440}]]"
</code>```

答:
This is one of the ways you could do it.

```<code>$decoded = json_decode("[[{"num":333}],[{"num":433}],[{"num":3033}],[{"num":533}],[{"num":514}],[{"num":1440}]]");

$vars = [];
foreach ($decoded as $i => $v) {
    $vars["var{$i + 1}"] = $v[0]["num"];
}

extract($vars);
</code>```

The result will be:

```<code>$var1 = 333;
$var2 = 433;
...
</code>```

The extract function extracts the keys of the associative array and registers them as variables in the variable table while assigning the corresponding value to them.

Title: Get values in array of objects Laravel

Body:
I have an array of objects in the telescope as follows. I need to get only the number and each number is placed in a numerical variable

"[[{"num":333}],[{"num":433}],[{"num":3033}],[{"num":533}],[{"num":514}],[{"num":1440}]]"

Ex

$var1 = 333
$var2 = 433

In the telescope appears exactly like this

"[[{"num":333}],[{"num":433}],[{"num":3033}],[{"num":533}],[{"num":514}],[{"num":1440}]]"

Body:
This is one of the ways you could do it.

$decoded = json_decode("[[{"num":333}],[{"num":433}],[{"num":3033}],[{"num":533}],[{"num":514}],[{"num":1440}]]");

$vars = [];
foreach ($decoded as $i => $v) {
    $vars["var{$i + 1}"] = $v[0]["num"];
}

extract($vars);

The result will be:

$var1 = 333;
$var2 = 433;
...

The extract function extracts the keys of the associative array and registers them as variables in the variable table while assigning the corresponding value to them.


问:
Relate/combine 2 different xpath Java Selenium
This url will show the search result of a product in Amazon site.

https://www.amazon.com/s?k=yellow+puma+shoes&s=price-asc-rank&qid=1559364287&ref=sr_st_price-asc-rank

Using this xpath I can get product name

```<code>//span[@class='a-size-base-plus a-color-base a-text-normal']
</code>```

Using this xpath I can get price

```<code>//span[@class='a-offscreen']
</code>```

Is there a way to combine these 2 so that I can relate product name with price. 1 Way I can think of is:

//span[@class='a-size-base-plus a-color-base a-text-normal']

```<code>List<WebElements> allProductNames**** Save them in a list. Then run a for loop

for()
{
text = getText
//span[text()='PUMA Mens Basket Classic']/../../../../../..//span[@class='a-offscreen']
}
</code>```

If you have an idea for easier solution kindly suggest. Thanks in advance.

答:
I would rather get all the items and then iterate through each of them with in a loop as shown below.</p>

```<code>    // get all products
    List<WebElement> products = driver.findElements(By.xpath("//span[@data-component-type='s-search-results']//div[@class='sg-row'][2]"));
    // create a map (consider it as dictionary that  to hold key value pair) to hold product and price
    Map<String, String> map = new HashMap<String, String>();
    for (WebElement product : products) {
        String item = "";
        String price = "";
        // get product name
        item = product.findElement(By.xpath(".//span[@class='a-size-base-plus a-color-base a-text-normal']")).getText();
        // get product price (some products have range so we have to get the prices and display)
        List<WebElement> prices = product.findElements(By.xpath(".//span[@class='a-offscreen']"));
        for (WebElement pPrice : prices) {
            if (price !=""){
                price = price + "-" + pPrice.getAttribute("textContent");
            }else {
                price = pPrice.getAttribute("textContent");
            }
        }
        // push the product and price to the map
        map.put(item, price);

    }
    System.out.println(map);
</code>```

Body:
This url will show the search result of a product in Amazon site.

https://www.amazon.com/s?k=yellow+puma+shoes&s=price-asc-rank&qid=1559364287&ref=sr_st_price-asc-rank

Using this xpath I can get product name

//span[@class='a-size-base-plus a-color-base a-text-normal']

Using this xpath I can get price

//span[@class='a-offscreen']

Is there a way to combine these 2 so that I can relate product name with price. 1 Way I can think of is:

//span[@class='a-size-base-plus a-color-base a-text-normal']

List<WebElements> allProductNames**** Save them in a list. Then run a for loop

for()
{
text = getText
//span[text()='PUMA Mens Basket Classic']/../../../../../..//span[@class='a-offscreen']
}

If you have an idea for easier solution kindly suggest. Thanks in advance.

Body:
I would rather get all the items and then iterate through each of them with in a loop as shown below.

    // get all products
    List<WebElement> products = driver.findElements(By.xpath("//span[@data-component-type='s-search-results']//div[@class='sg-row'][2]"));
    // create a map (consider it as dictionary that  to hold key value pair) to hold product and price
    Map<String, String> map = new HashMap<String, String>();
    for (WebElement product : products) {
        String item = "";
        String price = "";
        // get product name
        item = product.findElement(By.xpath(".//span[@class='a-size-base-plus a-color-base a-text-normal']")).getText();
        // get product price (some products have range so we have to get the prices and display)
        List<WebElement> prices = product.findElements(By.xpath(".//span[@class='a-offscreen']"));
        for (WebElement pPrice : prices) {
            if (price !=""){
                price = price + "-" + pPrice.getAttribute("textContent");
            }else {
                price = pPrice.getAttribute("textContent");
            }
        }
        // push the product and price to the map
        map.put(item, price);

    }
    System.out.println(map);