问:
Spring, thread and warnings at app termination time
I'm building a web app with j2ee, hibernate and Spring. At a certain point the app has to send a number of emails, so I thought of putting this task in a separate thread. Details:

There is syncronization on a number of status variables the thread and the controller share

There is NOT synchronization on the service bean that is shared with the controller (should it be?).

Anyway, when I shut down the app, I receive the following worrying message:

```<code>...
INFO: Closing Hibernate SessionFactory
25-mar-2011 10.02.14 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
GRAVE: The web application [/Tomcat6Locale] registered the JDBC driver [org.hsqldb.jdbc.JDBCDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
25-mar-2011 10.02.14 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
GRAVE: The web application [/Tomcat6Locale] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
25-mar-2011 10.02.14 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
GRAVE: The web application [/Tomcat6Locale] appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak.
25-mar-2011 10.02.15 org.apache.coyote.http11.Http11Protocol destroy
INFO: Stopping Coyote HTTP/1.1 on http-8080
</code>```

That I was not getting before the thread trick... In the end when one of these threads completes, they just return. I don't do anything special. Should I do more?

答:
I disagree with Nilesh's assessment.  The container is supposed to manage the database connection pool when it is specified as a Resource.  Assuming you close all the connections you get, you should be fine ... in theory.

I have heard that the fault is with Apache's DBCP library.  I've also heard that it has been fixed in newer versions of DBCP, although it seems like a version of Tomcat should have shipped by now.  Anyway, manually upgrading DBCP to the latest version is something to try.

NOTE: My answer applies to the JDBC driver related parts of the message.  The message that says "appears to have started a thread named ..." may or may not be fixed by fixing the JDBC driver problems.

Body:
I'm building a web app with j2ee, hibernate and Spring. At a certain point the app has to send a number of emails, so I thought of putting this task in a separate thread. Details:

There is syncronization on a number of status variables the thread and the controller share

There is NOT synchronization on the service bean that is shared with the controller (should it be?).

Anyway, when I shut down the app, I receive the following worrying message:

...
INFO: Closing Hibernate SessionFactory
25-mar-2011 10.02.14 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
GRAVE: The web application [/Tomcat6Locale] registered the JDBC driver [org.hsqldb.jdbc.JDBCDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
25-mar-2011 10.02.14 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
GRAVE: The web application [/Tomcat6Locale] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
25-mar-2011 10.02.14 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
GRAVE: The web application [/Tomcat6Locale] appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak.
25-mar-2011 10.02.15 org.apache.coyote.http11.Http11Protocol destroy
INFO: Stopping Coyote HTTP/1.1 on http-8080

That I was not getting before the thread trick... In the end when one of these threads completes, they just return. I don't do anything special. Should I do more?


来源: stackexchange

问:
How to make a nullable field in a struct
I'm struggling to do table driven test, and I want do this:

```<code>testCases := []struct {
    name          string
    testUserID    uint
    expected      User // <- maybe nil
    expectedError error
}
</code>```

Because the return values of tested function is *User, error.

User is like this, it is defined as DB scheme.

```<code>type User struct {
  ID uint
  CreatedAt time.Time
  UpdatedAt time.Time
  ...
}
</code>```

But in this case, I cannot make expected nil.

How can I do this?

Or my approach to do table driven test is wrong?

答:
You can also use special sql type:</p>

```<code>type structName struct {
    id sql.NullInt64
    name sql.NullString
    field sql.NullBool
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm struggling to do table driven test, and I want do this:

testCases := []struct {
    name          string
    testUserID    uint
    expected      User // <- maybe nil
    expectedError error
}

Because the return values of tested function is *User, error.

User is like this, it is defined as DB scheme.

type User struct {
  ID uint
  CreatedAt time.Time
  UpdatedAt time.Time
  ...
}

But in this case, I cannot make expected nil.

How can I do this?

Or my approach to do table driven test is wrong?

Body:
You can also use special sql type:

type structName struct {
    id sql.NullInt64
    name sql.NullString
    field sql.NullBool
}


问:
I need better understanding on for loops
can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!

```<code>1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;

5 int main(){
6     int n, a , b , ma=0,mb=1000000001;
7     cin >> n ;
8     cin >> a;
9     for( n--; n ; --n ){
10         cin >> b;
11         if(abs(a-b) < abs(ma-mb))
12             ma=a , mb=b;
13         else
14             if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15                 ma=a , mb=b;
16         a = b;
17     }
18     cout << ma << " " << mb;
19     return 0;
20 }
</code>```

答:
A for loop works the following way:

It runs for a certain number of times. We signify this with a condition. It has a start and an increment:

```<code>for (start ; condition ; increment )
{
// loop body
}
</code>```

For loops and all loops are very useful when you want to perform repetitive tasks.

Lets say that you want to make a game and this game will have 3 rounds. Each one of those rounds can be implemented as an iteration of a for loop. It will look like this:

```<code>for(int round = 0; round < 3; ++round) {
// game round logic
}
</code>```

In the above loop we start at 0. Once we reach 3, we would have already executed the for-loop 3 times. After each iteration of the for loop ++round gets executed, this increments the variable round by 1. We can increment it by a different value by doing: round+=2 or round*=2 etc.

Body:
can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;

5 int main(){
6     int n, a , b , ma=0,mb=1000000001;
7     cin >> n ;
8     cin >> a;
9     for( n--; n ; --n ){
10         cin >> b;
11         if(abs(a-b) < abs(ma-mb))
12             ma=a , mb=b;
13         else
14             if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15                 ma=a , mb=b;
16         a = b;
17     }
18     cout << ma << " " << mb;
19     return 0;
20 }

Body:
A for loop works the following way:

It runs for a certain number of times. We signify this with a condition. It has a start and an increment:

for (start ; condition ; increment )
{
// loop body
}

For loops and all loops are very useful when you want to perform repetitive tasks.

Lets say that you want to make a game and this game will have 3 rounds. Each one of those rounds can be implemented as an iteration of a for loop. It will look like this:

for(int round = 0; round < 3; ++round) {
// game round logic
}

In the above loop we start at 0. Once we reach 3, we would have already executed the for-loop 3 times. After each iteration of the for loop ++round gets executed, this increments the variable round by 1. We can increment it by a different value by doing: round+=2 or round*=2 etc.


问:
mutate date to create a column for all time less than a timestamp
I have some data which looks something like this:

```<code># A tibble: 754 x 2
   time                 v1
   <dttm>              <dbl>
 1 2020-04-16 09:45:00  175.
 2 2020-04-16 10:00:00  174.
 3 2020-04-16 10:15:00  174.
 4 2020-04-16 10:30:00  173.
 5 2020-04-16 10:45:00  174.
</code>```

I want to group_by a variable day from the lubridate package and apply an ifelse statement.

```<code>df %>%
  mutate(
    day = day(time)
    ) %>%
  group_by(day) %>%
  mutate(
    lessThanTenThirty = ifelse(time < "10:30", 1, 0)
  )
</code>```

So the expected output would have a 1 for all time (across all days) when the data is less than 10:30 and a 0 for all time after.

Data:

```<code>    df <- structure(list(time = structure(c(1587030300, 1587031200, 1587032100,
1587033000, 1587033900, 1587116700, 1587117600, 1587118500, 1587119400,
1587120300), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    v1 = c(174.52, 174.25, 173.69, 173.07, 174.015, 179.578,
    178.41, 178.42, 178.98, 178.6)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

答:
An option with as.ITime

```<code>library(data.table)
library(dplyr)
df %>%
   mutate(lessThanTenThirty = +(as.ITime(time) < as.ITime("10:30:00")))
</code>```

Body:
I have some data which looks something like this:

# A tibble: 754 x 2
   time                 v1
   <dttm>              <dbl>
 1 2020-04-16 09:45:00  175.
 2 2020-04-16 10:00:00  174.
 3 2020-04-16 10:15:00  174.
 4 2020-04-16 10:30:00  173.
 5 2020-04-16 10:45:00  174.

I want to group_by a variable day from the lubridate package and apply an ifelse statement.

df %>%
  mutate(
    day = day(time)
    ) %>%
  group_by(day) %>%
  mutate(
    lessThanTenThirty = ifelse(time < "10:30", 1, 0)
  )

So the expected output would have a 1 for all time (across all days) when the data is less than 10:30 and a 0 for all time after.

Data:

    df <- structure(list(time = structure(c(1587030300, 1587031200, 1587032100,
1587033000, 1587033900, 1587116700, 1587117600, 1587118500, 1587119400,
1587120300), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    v1 = c(174.52, 174.25, 173.69, 173.07, 174.015, 179.578,
    178.41, 178.42, 178.98, 178.6)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))

Body:
An option with as.ITime

library(data.table)
library(dplyr)
df %>%
   mutate(lessThanTenThirty = +(as.ITime(time) < as.ITime("10:30:00")))


问:
Acquiring OAuth2 access tokens for Exchange Management Shell cmdlets
In our python application, we use the Exchange Management Shell cmdlets to perform some tasks.
(In fact, the python application runs .Net application, which calls the Exchange Management Shell cmdlets.)
Currently we use basic authentication with the New-PSSession cmdlet.
On the other hand, we are already acquiring OAuth2 access tokens for different APIs and resources.
Now we would like to use OAuth2 authentication with the Exchange Management Shell cmdlets.

We had a look at this article[1].

However we have a few questions:

Is there a way to get access tokens without using ADAL and MSAL?

Is there a way to get a new access token using a refresh token?

It seems there is no chance to use an external(system) browser, isn't there?
Thank you in advance.

[1] https://developermessaging.azurewebsites.net/2018/09/07/acquiring-oauth2-access-tokens-for-automating-exchange-management-shell-cmdlets/?unapproved=96&moderation-hash=9250fbdda0e11fd8af9bafd4c3576139#review-96

答:
MSAL and ADAL are libraries which are designed for authenticating through OAuth and Yes you can get token without using MSAL or ADAL by directly using OAuth.you can directly use Oauth and OpenID Connect. It is very easy to code by managing Get and Post requests from URLs.

Refresh tokens are used to get a new access token when your current access token expires. For more information, see the document.

Using of a Browser depends on auth flow you are using. For example Device code flow does not require browser.


问:
State list for PreferenceScreen?
I've added a widget layout to my preference screens showing an arrow icon, to indicate to users that there are more preferences behind a given PreferenceScreen.

However, I notice when a PreferenceScreen is not enabled it is darkened. Is there a way I could also change the widget layout being used, or make it stateful, so that I could use a faded icon when my PreferenceScreen is disabled? Similar to how a state list drawable can be applied as a button's background?

tl;dr: How can I change the icon displayed when an instance of PreferenceLayout is disabled?

答:
Nice method

The best way I can see to tackle this problem is to create your own class which extends a Preference/PreferenceScreen. The layout resource you want is called in the initialisation of the class:

```<code> setWidgetLayoutResource(R.layout.preference_color);
</code>```

Which creates the view to be displayed in the widget area, which I don't think get grayed out when the preference is disabled.

Hacky/Ugly Method

Afraid I've only come up with a hack around this issue, I don't believe the widgets support states.

Just change the widget programatically:

```<code>   Preference BGColor = findPreference("Setting_BG_Color");
   BGColor.setWidgetLayoutResource(R.layout.ic_custom);
</code>```

Then change the widget layout when each time a dependency is called (kinda messy).

```<code>pref1 = (Preference) findPreference("Setting_Pref1");
pref1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // Check what object returned (assume checkbox pref)
            if ((boolean)newValue){
                BGColor.setWidgetLayoutResource(R.layout.ic_custom2);
                }
            return true;
        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Title: State list for PreferenceScreen?

Body:
Nice method

The best way I can see to tackle this problem is to create your own class which extends a Preference/PreferenceScreen. The layout resource you want is called in the initialisation of the class:

 setWidgetLayoutResource(R.layout.preference_color);

Which creates the view to be displayed in the widget area, which I don't think get grayed out when the preference is disabled.

Hacky/Ugly Method

Afraid I've only come up with a hack around this issue, I don't believe the widgets support states.

Just change the widget programatically:

   Preference BGColor = findPreference("Setting_BG_Color");
   BGColor.setWidgetLayoutResource(R.layout.ic_custom);

Then change the widget layout when each time a dependency is called (kinda messy).

pref1 = (Preference) findPreference("Setting_Pref1");
pref1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // Check what object returned (assume checkbox pref)
            if ((boolean)newValue){
                BGColor.setWidgetLayoutResource(R.layout.ic_custom2);
                }
            return true;
        }
    });


问:
Splitting items in a list - R
I have some items in my list that have / built in to them.
I want to split and duplucate them, e.g
a/b/c z -> becomes
a z
b z
c z

This is an example of my data but i don't have a clue on how to start. Any thoughts?

```<code>structure(list(keyword = c("deltoid muscle", "teres major/minor muscle",
"latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
"levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
"thoracolumbar fascia.", "Bone â\200“", "Clavicle:")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

e.g The output of

```<code>"rhomboid major/minor muscle"
</code>```

should be

```<code>"rhomboid major  muscle"
</code>```

and

```<code> "rhomboid minor muscle"
</code>```

Thanks!

答:
this works for all cases when only one \ is present

```<code>sub("(.*) (\\w+)/(\\w+) (.*)", "\\1 \\2 \\4; \\1 \\3 \\4", keyword[,1])

 [1] "deltoid muscle"
 [2] "teres major muscle; teres minor muscle"
 [3] "latissimus dorsi muscle"
 [4] "serratus anterior/posterior superior muscle; serratus anterior muscle; serratus anterior/posterior superior muscle; serratus posterior inferior muscle"
 [5] "levator scapulae"
 [6] "rhomboid major muscle; rhomboid minor muscle"
 [7] "erector spinae muscle"
 [8] "thoracolumbar fascia."
 [9] "Bone â€“"
[10] "Clavicle:"
</code>```

we can use this awkward stack to get the case when 2 \ are present

```<code>output <- sub("(.*) (\\w+)/(\\w+) (.*)", "\\1 \\2 \\4;\\1 \\3 \\4", keyword[,1])
output <- sub("(.*) (\\w+)/(\\w+) (.*)", "\\1 \\2 \\4;\\1 \\3 \\4", unlist(strsplit(output,";")))
output <- unlist(strsplit(output,";"))

    > output
 [1] "deltoid muscle"                     "teres major muscle"
 [3] "teres minor muscle"                 "latissimus dorsi muscle"
 [5] "serratus anterior superior muscle"  "serratus posterior superior muscle"
 [7] "serratus anterior inferior muscle"  "serratus posterior inferior muscle"
 [9] "levator scapulae"                   "rhomboid major muscle"
[11] "rhomboid minor muscle"              "erector spinae muscle"
[13] "thoracolumbar fascia."              "Bone â€“"
[15] "Clavicle:"
</code>```

Title: Splitting items in a list - R

Body:
I have some items in my list that have / built in to them.
I want to split and duplucate them, e.g
a/b/c z -> becomes
a z
b z
c z

This is an example of my data but i don't have a clue on how to start. Any thoughts?

structure(list(keyword = c("deltoid muscle", "teres major/minor muscle",
"latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
"levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
"thoracolumbar fascia.", "Bone â\200“", "Clavicle:")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

e.g The output of

"rhomboid major/minor muscle"

should be

"rhomboid major  muscle"

and

 "rhomboid minor muscle"

Thanks!

Body:
this works for all cases when only one \ is present

sub("(.*) (\\w+)/(\\w+) (.*)", "\\1 \\2 \\4; \\1 \\3 \\4", keyword[,1])

 [1] "deltoid muscle"
 [2] "teres major muscle; teres minor muscle"
 [3] "latissimus dorsi muscle"
 [4] "serratus anterior/posterior superior muscle; serratus anterior muscle; serratus anterior/posterior superior muscle; serratus posterior inferior muscle"
 [5] "levator scapulae"
 [6] "rhomboid major muscle; rhomboid minor muscle"
 [7] "erector spinae muscle"
 [8] "thoracolumbar fascia."
 [9] "Bone â€“"
[10] "Clavicle:"

we can use this awkward stack to get the case when 2 \ are present

output <- sub("(.*) (\\w+)/(\\w+) (.*)", "\\1 \\2 \\4;\\1 \\3 \\4", keyword[,1])
output <- sub("(.*) (\\w+)/(\\w+) (.*)", "\\1 \\2 \\4;\\1 \\3 \\4", unlist(strsplit(output,";")))
output <- unlist(strsplit(output,";"))

    > output
 [1] "deltoid muscle"                     "teres major muscle"
 [3] "teres minor muscle"                 "latissimus dorsi muscle"
 [5] "serratus anterior superior muscle"  "serratus posterior superior muscle"
 [7] "serratus anterior inferior muscle"  "serratus posterior inferior muscle"
 [9] "levator scapulae"                   "rhomboid major muscle"
[11] "rhomboid minor muscle"              "erector spinae muscle"
[13] "thoracolumbar fascia."              "Bone â€“"
[15] "Clavicle:"


问:
Issues using sqlsrv_rows_affected, it keeps returning false even when its true
I have a query that changes a users password, and I want to check the users knows their current password before being able to change it. So it is working, I need to enter the current password before changes will be made, but my outputs are still always false, here is the code I have:

```<code>$passwordnew=$_POST['passwordnew'];
$password=$_POST['password'];

$password_hash = md5($passwordnew);

$sql = "UPDATE cryptuser  SET password='" . $password_hash."'  WHERE  password = '".md5($password)."' AND userID ='" . $userid ."' ";

//Check SQL Query
$stmt = sqlsrv_query( $conn, $sql,array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
    var_dump(sqlsrv_rows_affected($stmt));

    $rows_affected = sqlsrv_rows_affected( $stmt);

    if( $rows_affected === false) {
         die('password incorrect');
    }

    else{
        echo $rows_affected." the password was updated.<br />";
    }

if(!$stmt)
{
    die('An error has occured with your registration. If this is an indeliberate occurance,
         please report this to us through the contact us page with details of the error.');
}
</code>```

Can anyone see this won't output "the password was updated" even when it is? It always returns password incorrect (false)

答:
Astax is right...

This if a full example query of getting sqlsrv_rows_affected() working. The key is setting the sqlsrv_query() $options to array('Scrollable' => SQLSRV_CURSOR_FORWARD) in the query. If you don't have any parms just put array() in t

```<code>    $sql = "UPDATE TOP (1) MyTable SET name=? WHERE id=$id";
    $params = array($name);
    $options =  array('Scrollable' => SQLSRV_CURSOR_FORWARD);
    $stmt = db_mssql_query($db, $sql, $params, $options);

    $updated_rows = sqlsrv_rows_affected($stmt);

    if($updated_rows === false) {
        die(print_r(sqlsrv_errors(), true));
    } elseif($updated_rows == -1) {
        print "No Info available<br>";
    } else {
        print "Updated: $updated_rows rows<br>";
    }
</code>```

Body:
I have a query that changes a users password, and I want to check the users knows their current password before being able to change it. So it is working, I need to enter the current password before changes will be made, but my outputs are still always false, here is the code I have:

$passwordnew=$_POST['passwordnew'];
$password=$_POST['password'];

$password_hash = md5($passwordnew);

$sql = "UPDATE cryptuser  SET password='" . $password_hash."'  WHERE  password = '".md5($password)."' AND userID ='" . $userid ."' ";

//Check SQL Query
$stmt = sqlsrv_query( $conn, $sql,array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
    var_dump(sqlsrv_rows_affected($stmt));

    $rows_affected = sqlsrv_rows_affected( $stmt);

    if( $rows_affected === false) {
         die('password incorrect');
    }

    else{
        echo $rows_affected." the password was updated.
";
    }

if(!$stmt)
{
    die('An error has occured with your registration. If this is an indeliberate occurance,
         please report this to us through the contact us page with details of the error.');
}

Can anyone see this won't output "the password was updated" even when it is? It always returns password incorrect (false)

Body:
Astax is right...

This if a full example query of getting sqlsrv_rows_affected() working. The key is setting the sqlsrv_query() $options to array('Scrollable' => SQLSRV_CURSOR_FORWARD) in the query. If you don't have any parms just put array() in t

    $sql = "UPDATE TOP (1) MyTable SET name=? WHERE id=$id";
    $params = array($name);
    $options =  array('Scrollable' => SQLSRV_CURSOR_FORWARD);
    $stmt = db_mssql_query($db, $sql, $params, $options);

    $updated_rows = sqlsrv_rows_affected($stmt);

    if($updated_rows === false) {
        die(print_r(sqlsrv_errors(), true));
    } elseif($updated_rows == -1) {
        print "No Info available<br>";
    } else {
        print "Updated: $updated_rows rows<br>";
    }


问:
need assistance with css layout

  I am having css layout issues.  I am attempting to align the Required! message to the right of the input elements

Keeping the flow:

Species:

input element    error-message

Breed:

input element    error-message

I tried various nested divs with-out success.

Link:

http://jsfiddle.net/d0773d/BpqyT/

答:
This has got nothing to do with css, you have a
 tag between the inputs and the error messages, you will have to remove these first.

Title: need assistance with css layout

Body: This has got nothing to do with css, you have a <br /> tag between the inputs and the error messages, you will have to remove these first.


问:
Spring Boot 2 Authorization Server for public clients (PKCE)
is possible create authorization server for PKCE authentication in current version of spring security?

I did research and I found out this authorization server project https://github.com/spring-projects-experimental/spring-authorization-server but there is no usable sample for that project.

I also find out that spring recommends Keycloak as authorization server, but it is not fit for my case.
We need be able fetch and verify user against remote service, and then use authorization server only for generating and verifying jwt tokens. In my knowledge Keycloak should holds also users right? So the best solution would be custom spring standalone authorization server. Is it possible in some way? Thank you!

答:
As far as I know, Spring framework has one more implementation of the authorization server.  It is a part of spring-security-oauth project. But this project was moved into maintenance mode.

According to this migration guide, the new authorization server project (that you have already found) will be created to change the legacy solution.

From my point of view now there are several possible options:

Using old legacy spring-security-oauth. More examples with old auth server

Using external services like Keycloak, Auth0, Okta and etc


问:
space-separated string of all positive numbers that are divisible by 2.For example, even_numbers(6) returns “2 4 6”
```<code>def even_numbers(maximum):
    return_string = ""
    for x in ___:
        return_string += str(x) + " "
    return return_string.strip()
print(even_numbers(1))  # No numbers displayed
</code>```

答:
You can use this</p>

```<code>def even_numbers(maximum):
    return_string = ""
    for x in range(2, maximum + 1, 2):
        return_string += str(x) + " "
    return return_string.strip()

print(even_numbers(6))  # prints 2, 4, 6
</code>```

Body:
You can use this

def even_numbers(maximum):
    return_string = ""
    for x in range(2, maximum + 1, 2):
        return_string += str(x) + " "
    return return_string.strip()

print(even_numbers(6))  # prints 2, 4, 6


问:
how to know if range slider change is made by client or by modifying its value with javascript?
Is there any way to know if range slider change is made by client or by modifying its value with javascript?

var caller = "by the client";

document.getElementById('mySlider').oninput = function() {
console.log("Changed "+caller+" to "+this.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="mySlider" type="range" value="50" min="0" max="100"></code>```

答:
You can try using the Event.isTrusted which specifies whether an event was created by user interaction (true) or via something like JavaScript manipulation (false):

```<code>var caller = "by the client";

document.getElementById('mySlider').oninput = function(event) {
  if (event.isTrusted) {
    /* The event is trusted, generated by a user action */
  } else {
    /* The event is not trusted, generated or modified by a script or dispatched via EventTarget.dispatchEvent()  */
  }
}
</code>```

var inputEl = document.getElementById('foo');

inputEl.onchange = function (event) {
  console.log(event.isTrusted);
}

document.getElementById('bar').onclick = function() {
  inputEl.value = Math.floor(Math.random() * 100);
  inputEl.dispatchEvent(new Event('change'));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="range" id="foo" name="foo" />

<button type="button" id="bar">change value</button></code>```

Hopefully that helps!

Body:
Is there any way to know if range slider change is made by client or by modifying its value with javascript?

var caller = "by the client";

document.getElementById('mySlider').oninput = function() {
console.log("Changed "+caller+" to "+this.value);
}

<input id="mySlider" type="range" value="50" min="0" max="100">

Body:
You can try using the Event.isTrusted which specifies whether an event was created by user interaction (true) or via something like JavaScript manipulation (false):

var caller = "by the client";

document.getElementById('mySlider').oninput = function(event) {
  if (event.isTrusted) {
    /* The event is trusted, generated by a user action */
  } else {
    /* The event is not trusted, generated or modified by a script or dispatched via EventTarget.dispatchEvent()  */
  }
}

var inputEl = document.getElementById('foo');

inputEl.onchange = function (event) {
  console.log(event.isTrusted);
}

document.getElementById('bar').onclick = function() {
  inputEl.value = Math.floor(Math.random() * 100);
  inputEl.dispatchEvent(new Event('change'));
}

<input type="range" id="foo" name="foo" />

<button type="button" id="bar">change value</button>

Hopefully that helps!


问:
JAVA. JTABLE - How to count currently selected row(s)
I need to count selected row for removing multiple rows. Please help with the steps.

Example in the picture I want to delete/remove those selected rows at the same time.

Body: table.getSelectedRows().length


问:
How to import csv file into mongoDB using python
i'm new to Python.
I want to insert specific columns of a csv file into a collection in my mongodb, i know how to do it with the shell but i want to do it with python, as i'm learning Python.

This is what i have so far:

```<code>import csv
import json
import pandas as pd
import sys, getopt, pprint
from pymongo import MongoClient
#CSV to JSON Conversion
with open('netflix_titles.csv','rt', encoding="utf8") as file:
data = file.read()
mongo_client=MongoClient()
db=mongo_client.Netflix
db.segment.drop()
header= [ "show_id", "director"]

for each in data:
    row={}
    for field in header:
        row[field]=each[field]

    db.segment.insert(row)
</code>```

In only throws me an indented error in this line:

```<code>data = file.read()
</code>```

答: You have to put tab before date = file.read() , because with increase indentation level.

Body:
i'm new to Python.
I want to insert specific columns of a csv file into a collection in my mongodb, i know how to do it with the shell but i want to do it with python, as i'm learning Python.

This is what i have so far:

import csv
import json
import pandas as pd
import sys, getopt, pprint
from pymongo import MongoClient
#CSV to JSON Conversion
with open('netflix_titles.csv','rt', encoding="utf8") as file:
data = file.read()
mongo_client=MongoClient()
db=mongo_client.Netflix
db.segment.drop()
header= [ "show_id", "director"]

for each in data:
    row={}
    for field in header:
        row[field]=each[field]

    db.segment.insert(row)

In only throws me an indented error in this line:

data = file.read()


问:
TextWatcher -related code works well only with one EditView
I have the following issue.I'm having an activity,part of an animal shelter app, where an user has to enter or edit pet-related data like weight,name and breed.What I want to achieve is to  show a dialog asking if the user wants to keep editing or leave the activity,depending on whether he actually changed any of the text in the EditText views.
To do so I have created a boolean variable ,which should turn to true if the text was edited /trigger the dialog/ or remain false/do nothing/ if the user didn't edit anything.
I have attached TextWatcher to my EditText fields and tried to change the variable to true by doing that in onTextChangedor in beforeTextChanged.I tried comparing the hash or string values  of the EditText fields to the CharSequence charSequence in the onTextChanged method but it only works for one of the EditText fields/meaning it triggers the dialog when the user changed the text/.Whenever I try to apply similar logic to the rest of the EditText fields as well the functionality breaks and the boolean variable stays "true" no matter what/meaning user sees dialog no matter if they changed the text or not/.
I tried various comparisson,if-logic,switch statement in an inner class and nothing seems to work.Kindly see code below.Thank you.

```<code>/**
 * Allows user to create a new pet or edit an existing one.
 */
public class EditorActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>, TextWatcher {

    /**
     * EditText field to enter the pet's name
     */
    private EditText mNameEditText;

    /**
     * EditText field to enter the pet's breed
     */
    private EditText mBreedEditText;

    /**
     * EditText field to enter the pet's weight
     */
    private EditText mWeightEditText;

    /**
     * EditText field to enter the pet's gender
     */
    private Spinner mGenderSpinner;

    /**
     * Gender of the pet. The possible values are:
     * 0 for unknown gender, 1 for male, 2 for female.
     */
    public static int mGender;

    public static String mPetName;

    public static String mPetBreed;

    public static String mPetWeight;

    private static ArrayAdapter mGenderSpinnerAdapter;

    private static Uri mSinglePetUri;

    private static ContentValues mContentValues;
    // we will show warning dialog to the user,if the below variable is true
    private boolean mPetHasChanged;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);
        // checks if we are about to edit the information about an existing pet or add
        // a new pet record , adjusts the activity title accordingly and initializes/
        // activates Loader only if we are updating an existing pet
        mSinglePetUri = getIntent().getData();
        if (mSinglePetUri != null) {
            setTitle(R.string.edit_pet_activity_title);
            getSupportLoaderManager().initLoader(0, null, this);
        } else {
            setTitle(getString(R.string.add_a_pet_activity_title));

        }
        // Find all relevant views that we will need to read user input from
        mNameEditText = findViewById(R.id.edit_pet_name);
        mBreedEditText = findViewById(R.id.edit_pet_breed);
        mWeightEditText = findViewById(R.id.edit_pet_weight);
        mGenderSpinner = findViewById(R.id.spinner_gender);
        setupSpinner();
        // watch for text changes
        mNameEditText.addTextChangedListener(this);
        mBreedEditText.addTextChangedListener(this);
        mWeightEditText.addTextChangedListener(this);

}

@Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

  @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        int nameTextHashCode = mNameEditText.getText().hashCode();
        int breedTextHashCode = mBreedEditText.getText().hashCode();
        int weightTextHashCode = mWeightEditText.getText().hashCode();
        boolean nameChanged = nameTextHashCode == charSequence.hashCode();
        boolean breedChanged = breedTextHashCode == charSequence.hashCode();
        boolean weightChanged = weightTextHashCode == charSequence.hashCode();
        //this works-mPetHasChanged properly changes value
        mPetHasChanged = nameChanged ;
        //this doesn't work - the value is always true even when user didn't change a thing
        mPetHasChanged = nameChanged||breedChanged||weightChanged;
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}
</code>```

Then in another method the boolean value is tested in order to show or not the dialog

```<code>if (!mPetHasChanged) {
                    NavUtils.navigateUpFromSameTask(EditorActivity.this);
                    return true;
                }

                // Otherwise if there are unsaved changes, setup a dialog to warn the user.
                // Create a click listener to handle the user confirming that
                // changes should be discarded.
                DialogInterface.OnClickListener discardButtonClickListener =
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                // User clicked "Discard" button, navigate to parent activity.
                                NavUtils.navigateUpFromSameTask(EditorActivity.this);
                            }
                        };

                // Show a dialog that notifies the user they have unsaved changes
                showUnsavedChangesDialog(discardButtonClickListener);

                return true;
</code>```

XML of the layout:

```<code><?xml version="1.0" encoding="utf-8"?>

<!-- Copyright (C) 2016 The Android Open Source Project
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<!-- Layout for the editor -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/activity_margin"
    tools:context=".EditorActivity">

    <!-- Overview category -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <!-- Label -->
        <TextView
            android:text="@string/category_overview"
            style="@style/CategoryStyle" />

        <!-- Input fields -->
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:paddingLeft="4dp"
            android:orientation="vertical">

            <!-- Name field -->
            <EditText
                android:id="@+id/edit_pet_name"
                android:hint="@string/hint_pet_name"
                android:inputType="textCapWords"
                style="@style/EditorFieldStyle" />

            <!-- Breed field -->
            <EditText
                android:id="@+id/edit_pet_breed"
                android:hint="@string/hint_pet_breed"
                android:inputType="textCapWords"
                style="@style/EditorFieldStyle" />
        </LinearLayout>
    </LinearLayout>

    <!-- Gender category -->
    <LinearLayout
        android:id="@+id/container_gender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <!-- Label -->
        <TextView
            android:text="@string/category_gender"
            style="@style/CategoryStyle" />

        <!-- Input field -->
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:orientation="vertical">

            <!-- Gender drop-down spinner -->
            <Spinner
                android:id="@+id/spinner_gender"
                android:layout_height="48dp"
                android:layout_width="wrap_content"
                android:paddingRight="16dp"
                android:spinnerMode="dropdown"/>
        </LinearLayout>
    </LinearLayout>

    <!-- Measurement category -->
    <LinearLayout
        android:id="@+id/container_measurement"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <!-- Label -->
        <TextView
            android:text="@string/category_measurement"
            style="@style/CategoryStyle" />

        <!-- Input fields -->
        <RelativeLayout
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:paddingLeft="4dp">

            <!-- Weight field -->
            <EditText
                android:id="@+id/edit_pet_weight"
                android:hint="@string/hint_pet_weight"
                android:inputType="number"
                style="@style/EditorFieldStyle" />

            <!-- Units for weight (kg) -->
            <TextView
                android:id="@+id/label_weight_units"
                android:text="@string/unit_pet_weight"
                style="@style/EditorUnitsStyle"/>
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>
</code>```

答:
When all that you need is mPetChanged, why are you even matching the HashCodes?

See this:

```<code>@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    mPetHasChanged = !mNameEditText.getText().toString().trim().equals("") || !mBreedEditText.getText().toString().trim().equals("") || !mWeightEditText.getText().toString().trim().equals("");
}
</code>```

You can use If for each EditText to check if they're empty but this seems easy. You can also use isBlank() but that comes in StringUtils() with Apache library, you can use String.isEmpty() which is available in Java but it returns true if it the EditText contains only spaces.

Update: you can compare start and before in onTextChanged(CharSequence charSequence, int start, int before, int count), if the values of start and before are not same that means text has changed. As provided below:

```<code>@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int i2) {
    mPetHasChanged = start!= before;
}
</code>```

Body:
I have the following issue.I'm having an activity,part of an animal shelter app, where an user has to enter or edit pet-related data like weight,name and breed.What I want to achieve is to  show a dialog asking if the user wants to keep editing or leave the activity,depending on whether he actually changed any of the text in the EditText views.
To do so I have created a boolean variable ,which should turn to true if the text was edited /trigger the dialog/ or remain false/do nothing/ if the user didn't edit anything.
I have attached TextWatcher to my EditText fields and tried to change the variable to true by doing that in onTextChangedor in beforeTextChanged.I tried comparing the hash or string values  of the EditText fields to the CharSequence charSequence in the onTextChanged method but it only works for one of the EditText fields/meaning it triggers the dialog when the user changed the text/.Whenever I try to apply similar logic to the rest of the EditText fields as well the functionality breaks and the boolean variable stays "true" no matter what/meaning user sees dialog no matter if they changed the text or not/.
I tried various comparisson,if-logic,switch statement in an inner class and nothing seems to work.Kindly see code below.Thank you.

/**
 * Allows user to create a new pet or edit an existing one.
 */
public class EditorActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>, TextWatcher {

    /**
     * EditText field to enter the pet's name
     */
    private EditText mNameEditText;

    /**
     * EditText field to enter the pet's breed
     */
    private EditText mBreedEditText;

    /**
     * EditText field to enter the pet's weight
     */
    private EditText mWeightEditText;

    /**
     * EditText field to enter the pet's gender
     */
    private Spinner mGenderSpinner;

    /**
     * Gender of the pet. The possible values are:
     * 0 for unknown gender, 1 for male, 2 for female.
     */
    public static int mGender;

    public static String mPetName;

    public static String mPetBreed;

    public static String mPetWeight;

    private static ArrayAdapter mGenderSpinnerAdapter;

    private static Uri mSinglePetUri;

    private static ContentValues mContentValues;
    // we will show warning dialog to the user,if the below variable is true
    private boolean mPetHasChanged;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);
        // checks if we are about to edit the information about an existing pet or add
        // a new pet record , adjusts the activity title accordingly and initializes/
        // activates Loader only if we are updating an existing pet
        mSinglePetUri = getIntent().getData();
        if (mSinglePetUri != null) {
            setTitle(R.string.edit_pet_activity_title);
            getSupportLoaderManager().initLoader(0, null, this);
        } else {
            setTitle(getString(R.string.add_a_pet_activity_title));

        }
        // Find all relevant views that we will need to read user input from
        mNameEditText = findViewById(R.id.edit_pet_name);
        mBreedEditText = findViewById(R.id.edit_pet_breed);
        mWeightEditText = findViewById(R.id.edit_pet_weight);
        mGenderSpinner = findViewById(R.id.spinner_gender);
        setupSpinner();
        // watch for text changes
        mNameEditText.addTextChangedListener(this);
        mBreedEditText.addTextChangedListener(this);
        mWeightEditText.addTextChangedListener(this);

}

@Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

  @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        int nameTextHashCode = mNameEditText.getText().hashCode();
        int breedTextHashCode = mBreedEditText.getText().hashCode();
        int weightTextHashCode = mWeightEditText.getText().hashCode();
        boolean nameChanged = nameTextHashCode == charSequence.hashCode();
        boolean breedChanged = breedTextHashCode == charSequence.hashCode();
        boolean weightChanged = weightTextHashCode == charSequence.hashCode();
        //this works-mPetHasChanged properly changes value
        mPetHasChanged = nameChanged ;
        //this doesn't work - the value is always true even when user didn't change a thing
        mPetHasChanged = nameChanged||breedChanged||weightChanged;
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}

Then in another method the boolean value is tested in order to show or not the dialog

if (!mPetHasChanged) {
                    NavUtils.navigateUpFromSameTask(EditorActivity.this);
                    return true;
                }

                // Otherwise if there are unsaved changes, setup a dialog to warn the user.
                // Create a click listener to handle the user confirming that
                // changes should be discarded.
                DialogInterface.OnClickListener discardButtonClickListener =
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                // User clicked "Discard" button, navigate to parent activity.
                                NavUtils.navigateUpFromSameTask(EditorActivity.this);
                            }
                        };

                // Show a dialog that notifies the user they have unsaved changes
                showUnsavedChangesDialog(discardButtonClickListener);

                return true;

XML of the layout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/activity_margin"
    tools:context=".EditorActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:text="@string/category_overview"
            style="@style/CategoryStyle" />

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:paddingLeft="4dp"
            android:orientation="vertical">

            <EditText
                android:id="@+id/edit_pet_name"
                android:hint="@string/hint_pet_name"
                android:inputType="textCapWords"
                style="@style/EditorFieldStyle" />

            <EditText
                android:id="@+id/edit_pet_breed"
                android:hint="@string/hint_pet_breed"
                android:inputType="textCapWords"
                style="@style/EditorFieldStyle" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/container_gender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:text="@string/category_gender"
            style="@style/CategoryStyle" />

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:orientation="vertical">

            <Spinner
                android:id="@+id/spinner_gender"
                android:layout_height="48dp"
                android:layout_width="wrap_content"
                android:paddingRight="16dp"
                android:spinnerMode="dropdown"/>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/container_measurement"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:text="@string/category_measurement"
            style="@style/CategoryStyle" />

        <RelativeLayout
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:paddingLeft="4dp">

            <EditText
                android:id="@+id/edit_pet_weight"
                android:hint="@string/hint_pet_weight"
                android:inputType="number"
                style="@style/EditorFieldStyle" />

            <TextView
                android:id="@+id/label_weight_units"
                android:text="@string/unit_pet_weight"
                style="@style/EditorUnitsStyle"/>
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

Body:
When all that you need is mPetChanged, why are you even matching the HashCodes?

See this:

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    mPetHasChanged = !mNameEditText.getText().toString().trim().equals("") || !mBreedEditText.getText().toString().trim().equals("") || !mWeightEditText.getText().toString().trim().equals("");
}

You can use If for each EditText to check if they're empty but this seems easy. You can also use isBlank() but that comes in StringUtils() with Apache library, you can use String.isEmpty() which is available in Java but it returns true if it the EditText contains only spaces.

Update: you can compare start and before in onTextChanged(CharSequence charSequence, int start, int before, int count), if the values of start and before are not same that means text has changed. As provided below:

@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int i2) {
    mPetHasChanged = start!= before;
}


问:
string to array in php or javascript
I have string below in PHP/Javascript which is encoded. How to make that string to array in PHP or javascript?

```<code>data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201
</code>```

I tried to decode string first. Then I tried to split("&") but That I result is different than I am looking.
Javascript:

console.log(decodeURIComponent(data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201));

// Result: data[0][Name]=Car&data[0][Price]=101&data[1][Name]=Laptop&data[1][Price]=201&data[2][Name]=Laptop&data[2][Price]=201
```

<p>So I think split by "&" was not better Idea or Need to do more steps to make array.</p>

<p>In <strong>PHP</strong>, I tried to explod by "&" first and then tried to explode by "=" again but it gives me different result.</p>

```$mydata = "data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201";
                foreach ($mydata as $chunk) {
                    $param = explode("=", $chunk);
                    print("```".print_r($param,true)."```"); //prints first element

                    if ($param) {
                        printf("Value for parameter \"%s\" is \"%s\"
\n", urldecode($param[0]),
                        urldecode($param[1]));

                       //First round:
                        Array
                        (
                         [0] => data%5B0%5D%5BName%5D
                         [1] => Car
                        )
                        //Second round:
                        Array
                        (
                        [0] => data%5B0%5D%5BPrice%5D
                        [1] => 101
                        )
                       $What_Should_Var_Name??  = urldecode($param[1]);
                      //confuse to put variable name because [1] will be
                      'Car' which represents "Name", but in second loop, same
                      [1] will be '101' which will represent 'Price'. So I
                      don't know how to store that here to make array.

                    }
                }
```

答:
I taste two questions here. Correct me if I am wrong.

How to decode the data to a usable array

How to use the array

1. How to decode the data to a usable array

I think you are looking for urldecode() and parse_str().

```<code>$decodedString = urldecode('data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201');

// The above code will give you the following string in $decodedString:
data[0][Name]=Car&data[0][Price]=101&data[1][Name]=Laptop&data[1][Price]=20

parse_str($decodedString, $array);

// The above code will give you the following array in $array:
array(1) {
  ["data"]=>
  array(2) {
    [0]=>
    array(2) {
      ["Name"]=>
      string(3) "Car"
      ["Price"]=>
      string(3) "101"
    }
    [1]=>
    array(2) {
      ["Name"]=>
      string(6) "Laptop"
      ["Price"]=>
      string(2) "20"
    }
  }
}
</code>```

2. How to use the array

If you would iterate over the array like this

```<code>foreach ($array['data'] as $data) {
    // So you can use $data['Name'] and $data['Price']

    // ITERATION 1:
    // $data will be ['name' => 'Car', 'Price' => '101']

    // ITERATION 2:
    // $data will be ['name' => 'Laptop', 'Price' => '20']
}
</code>```

Title: string to array in php or javascript

Body:
I have string below in PHP/Javascript which is encoded. How to make that string to array in PHP or javascript?

data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201

I tried to decode string first. Then I tried to split("&") but That I result is different than I am looking.
Javascript:

console.log(decodeURIComponent(data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201));

// Result: data[0][Name]=Car&data[0][Price]=101&data[1][Name]=Laptop&data[1][Price]=201&data[2][Name]=Laptop&data[2][Price]=201

So I think split by "&" was not better Idea or Need to do more steps to make array.

In PHP, I tried to explod by "&" first and then tried to explode by "=" again but it gives me different result.

$mydata = "data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201";
                foreach ($mydata as $chunk) {
                    $param = explode("=", $chunk);
                    print("
".print_r($param,true)."
"); //prints first element

                    if ($param) {
                        printf("Value for parameter \"%s\" is \"%s\"
\n", urldecode($param[0]),
                        urldecode($param[1]));

                       //First round:
                        Array
                        (
                         [0] => data%5B0%5D%5BName%5D
                         [1] => Car
                        )
                        //Second round:
                        Array
                        (
                        [0] => data%5B0%5D%5BPrice%5D
                        [1] => 101
                        )
                       $What_Should_Var_Name??  = urldecode($param[1]);
                      //confuse to put variable name because [1] will be
                      'Car' which represents "Name", but in second loop, same
                      [1] will be '101' which will represent 'Price'. So I
                      don't know how to store that here to make array.

                    }
                }

Body:
I taste two questions here. Correct me if I am wrong.

How to decode the data to a usable array

How to use the array

1. How to decode the data to a usable array

I think you are looking for urldecode() and parse_str().

$decodedString = urldecode('data%5B0%5D%5BName%5D=Car&data%5B0%5D%5BPrice%5D=101&data%5B1%5D%5BName%5D=Laptop&data%5B1%5D%5BPrice%5D=201');

// The above code will give you the following string in $decodedString:
data[0][Name]=Car&data[0][Price]=101&data[1][Name]=Laptop&data[1][Price]=20

parse_str($decodedString, $array);

// The above code will give you the following array in $array:
array(1) {
  ["data"]=>
  array(2) {
    [0]=>
    array(2) {
      ["Name"]=>
      string(3) "Car"
      ["Price"]=>
      string(3) "101"
    }
    [1]=>
    array(2) {
      ["Name"]=>
      string(6) "Laptop"
      ["Price"]=>
      string(2) "20"
    }
  }
}

2. How to use the array

If you would iterate over the array like this

foreach ($array['data'] as $data) {
    // So you can use $data['Name'] and $data['Price']

    // ITERATION 1:
    // $data will be ['name' => 'Car', 'Price' => '101']

    // ITERATION 2:
    // $data will be ['name' => 'Laptop', 'Price' => '20']
}


问:
How to properly handle client "Connection: close" request on HTTP file server?
How do I handle properly a client Connection: close request field? As of now if I get this particular field I close the socket and wait for a following request from the client than reply again and start serving the data.

I don't know why my client/server communication is not working as the Apache Server I tested with.

Thanks for any clarifications...

Client/Server comunication:

```<code>CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

231489172304981723409817234981234acvass123412323
21312hjdfaoi8w34yorhadl4hi8rali45mhalo3i,wmotw
345fqw354aoicu43yocq2i3hr
</code>```

Client/ApacheServer Comunication:

```<code>CLIENT:
GET /test.mp3 HTTP/1.0
Host: 192.168.1.120
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.1 200 OK
Date: Wed, 01 Jun 2011 19:15:11 GMT
Server: Apache/2.2.16 (Win32)
Last-Modified: Thu, 29 Apr 2010 21:06:34 GMT
ETag: "14000000047049-4f75c8-4856680636a80"
Accept-Ranges: bytes
Content-Length: 5207496
Connection: close
Content-Type: audio/mpeg

...d.....<).0.. ..........<.@.. ( .h.$.J...1...i....A. ......c....a.9..!g.N...A. ........ ....>......|.......8....a......|..|N.............'>........?...C.....@..TJt.n .e...r.iL..#..IH...pR|.
</code>```

答:
Yes closing the socket is the right action to take.  If the client is using this header properly, they are closing the socket on their end once they receive your response.

What I'm noticing here is that your server is not returning a Content-Length header.  Even though the client is issuing a HEAD request, based on the W3C proposal (sec. 9.4):

The metainformation contained in the HTTP
  headers in response to a HEAD request
  SHOULD be identical to the information
  sent in response to a GET request.
  This method can be used for obtaining
  metainformation about the entity
  implied by the request without
  transferring the entity-body itself.
  This method is often used for testing
  hypertext links for validity,
  accessibility, and recent
  modification.

The response to a HEAD request MAY be
  cacheable in the sense that the
  information contained in the response
  MAY be used to update a previously
  cached entity from that resource. If
  the new field values indicate that the
  cached entity differs from the current
  entity (as would be indicated by a
  change in Content-Length, Content-MD5,
  ETag or Last-Modified), then the cache
  MUST treat the cache entry as stale.

The key here is to make sure you're telling the client the size of the response without actually sending the data.

Body:
How do I handle properly a client Connection: close request field? As of now if I get this particular field I close the socket and wait for a following request from the client than reply again and start serving the data.

I don't know why my client/server communication is not working as the Apache Server I tested with.

Thanks for any clarifications...

Client/Server comunication:

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

231489172304981723409817234981234acvass123412323
21312hjdfaoi8w34yorhadl4hi8rali45mhalo3i,wmotw
345fqw354aoicu43yocq2i3hr

Client/ApacheServer Comunication:

CLIENT:
GET /test.mp3 HTTP/1.0
Host: 192.168.1.120
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.1 200 OK
Date: Wed, 01 Jun 2011 19:15:11 GMT
Server: Apache/2.2.16 (Win32)
Last-Modified: Thu, 29 Apr 2010 21:06:34 GMT
ETag: "14000000047049-4f75c8-4856680636a80"
Accept-Ranges: bytes
Content-Length: 5207496
Connection: close
Content-Type: audio/mpeg

...d.....<).0.. ..........<.@.. ( .h.$.J...1...i....A. ......c....a.9..!g.N...A. ........ ....>......|.......8....a......|..|N.............'>........?...C.....@..TJt.n .e...r.iL..#..IH...pR|.


问:
Split an array of booleans into smaller repeatable chunks of arrays in javascript
I'm reaching out to see if there are anyone that could point me to the right direction. I have a program that produces an array of booleans that consist of either false(0) og true(1). Like this: [0,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,1,1,1,0,0,1,0].
This array is usually between 50 and 400 long. Instead of showing the whole array to the end user I want to make it more "readable". One of the things I have to do is to split in into smaller repeatable chunks of arrays that shows how many times it should repeated (1 to n times). I'll give som examples:

Example number 1 simple:

```<code>Before: [1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1]
After: [1,0,1]*7 time,
</code>```

Example number 1 more complex:

```<code>Before: [1,1,1,0,1,1,0,1,1,0,1,1,0,1,0,0,1,0,1,1,0,1]
After: [1,1]*1 time, [1,0,1]*4 times, [0,0] *1 time, [1,0,1]*2 times
</code>```

As you can see from the examples both before and after is actually the same but only different way of printing it.

Remember that in my program I can have bigger arrays (size up to 400). And often it is much easier to print out (to the user) [1,0,1,1]* 55 than [1,0,1,1,...< long array>...,1,0,1,1]

Edit:
The main goal is to make the array easier to read, since it will be read 1 by 1 (by a human).

So '01'*22 rather than '01010101010101010101010101010101010101010101'

And also I would prefer a higher multiplication number rather than a low one.

'01'*22 is better than '0101'*11 which is better than '010101'*7 + '01'*1

答:
You yould iterate the array/string from the end and store for each step the optimal solution. At last take the first item of the array.

This works with lage data as well.

function getChunks(data) {

    function same(position, size) {
        for (let i = 0; i < size; i++) {
            const right = offset + i + position * size;
            if (right >= data.length || data[offset + i] !== data[right]) return false;
        }
        return true;
    }

    function add(offset, patternSize, count) {
        let result = chunks[offset],
            temp = data.slice(offset, offset + patternSize) + '<' + count,
            product = patternSize * count,
            score = patternSize * ((count - 1) || 0.5),
            size = patternSize;

        if (offset + product < data.length) {
            let chunk = chunks[offset + product];
            score += chunk.score;
            temp += '|' + chunk.result;
            size += chunk.size;
        }

        if (!result) {
            chunks[offset] = { result: temp, score: 0.5, size };
            return;
        }
        if (result.score < score || result.score === score && size < result.size) {
            chunks[offset] = { result: temp, score, size };
        }
    }

    var chunks = [],
        offset = data.length;

    while (offset--) {
        let patternSize = data.length - offset + 1;

        while (--patternSize) {
            let count = 0;
            while (same(++count, patternSize)) add(offset, patternSize, count);
            add(offset, patternSize, count);
        }
    }
    return chunks[0].result;
}

console.log(getChunks('11101110111101111000010011110001100'));
console.log(getChunks('101101101101101101101'));
console.log(getChunks('1110110110110100101101'));```

Body:
I'm reaching out to see if there are anyone that could point me to the right direction. I have a program that produces an array of booleans that consist of either false(0) og true(1). Like this: [0,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,1,1,1,0,0,1,0].
This array is usually between 50 and 400 long. Instead of showing the whole array to the end user I want to make it more "readable". One of the things I have to do is to split in into smaller repeatable chunks of arrays that shows how many times it should repeated (1 to n times). I'll give som examples:

Example number 1 simple:

Before: [1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1]
After: [1,0,1]*7 time,

Example number 1 more complex:

Before: [1,1,1,0,1,1,0,1,1,0,1,1,0,1,0,0,1,0,1,1,0,1]
After: [1,1]*1 time, [1,0,1]*4 times, [0,0] *1 time, [1,0,1]*2 times

As you can see from the examples both before and after is actually the same but only different way of printing it.

Remember that in my program I can have bigger arrays (size up to 400). And often it is much easier to print out (to the user) [1,0,1,1]* 55 than [1,0,1,1,...< long array>...,1,0,1,1]

Edit:
The main goal is to make the array easier to read, since it will be read 1 by 1 (by a human).

So '01'*22 rather than '01010101010101010101010101010101010101010101'

And also I would prefer a higher multiplication number rather than a low one.

'01'*22 is better than '0101'*11 which is better than '010101'*7 + '01'*1


问:
Find element that appears odd number of times
I'm trying to solve this exercise of finding the number that appears an odd number of times in an array. I have this so far but the output ends up being an integer that appears an even number of times. For example, the number 2 appears 3 times and the number 4 appears 6 times, but the output is 4 because it counts it as appearing 5 times. How can it be that it returns the first set that it finds as odd? Any help is appreciated!</p>

```<code>         function oddInt(array) {
         var count = 0;
         var element = 0;
         for(var i = 0; i < array.length; i++) {
           var tempInt = array[i];
           var tempCount = 0;
             for(var j = 0; j <array.length; j++) {
                if(array[j]===tempInt) {
                tempCount++;
                  if(tempCount % 2 !== 0 && tempCount > count) {
                  count = tempCount;
                  element = array[j];
                }
               }
              }
             }
           return element;
           }
           oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
</code>```

答:
function oddInt(array) {
    let result = 0;
    for (let element of array) {
        result ^= element
    }
    return result
}
```

Body:
I'm trying to solve this exercise of finding the number that appears an odd number of times in an array. I have this so far but the output ends up being an integer that appears an even number of times. For example, the number 2 appears 3 times and the number 4 appears 6 times, but the output is 4 because it counts it as appearing 5 times. How can it be that it returns the first set that it finds as odd? Any help is appreciated!

         function oddInt(array) {
         var count = 0;
         var element = 0;
         for(var i = 0; i < array.length; i++) {
           var tempInt = array[i];
           var tempCount = 0;
             for(var j = 0; j <array.length; j++) {
                if(array[j]===tempInt) {
                tempCount++;
                  if(tempCount % 2 !== 0 && tempCount > count) {
                  count = tempCount;
                  element = array[j];
                }
               }
              }
             }
           return element;
           }
           oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);


问:
How to create dynamic PyMongo query handling ISODate?
I am developing a Flask REST API which will have three query parameters (HomeDevice, Key, UpdateDate), all passed as string. Now, I have to PyMongo query on Mongodb using these three inputs as filters.

```<code>typeof db.getCollection('collection_name').findOne().updatedate
>> Object
</code>```

```<code>import json
from pymongo import MongoClient
import pandas as pd

client = MongoClient(<ServerAddress>,27017)
db = client.db_name
col = db.collection_name

updatedate="2020-01-13 06:43:47.500Z"
print(updatedate)

var = '{ "$and" : [{"homeDevice" : "Loader"} , {"key" : "OP2561NX" },{"updatedate" : ISODate("2020-01-13 06:43:47.500Z")}]}'
data = json.loads(var)
docs = pd.DataFrame(list(col.find(data)))
print(docs)
</code>```

ISODate(updateDate) is causing JSONDecodeError, and after removing ISODate casting, query fetches empty frame.

```<code>JSONDecodeError                           Traceback (most recent call last)
<ipython-input-12-95360c676df4> in <module>
     11
     12 var = '{ "$and" : [{"homeDevice" : "Loader"} , {"keyed" : "OP2561NX" },{"updatedate" : ISODate("2020-01-13 06:43:47.500Z")}]}'
---> 13 data = json.loads(var)
     14 docs = pd.DataFrame(list(col.find(data)))
     15 print(docs)

E:\Analytics\Installations\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

E:\Analytics\Installations\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
    335
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

E:\Analytics\Installations\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 81 (char 80)
</code>```

Running this query directly in monogodb (Robo3T) returns data. I need a way to create query dynamically and apply ISODate on updatedate key.

How to create dynamic PyMongo query to handle ISODate?

答:
Construct var like a dictionary:

var = { "$and" : [{"homeDevice" : "Loader"} , {"key" : "OP2561NX" },{"updatedate" : ISO("2020-01-13 06:43:47.500Z")}]}
```

<p>and use it like:</p>

<pre class="lang-py prettyprint-override"><code>col.find(var)
</code>```

You don't need to convert it to string/JSON.

Try the above and let me know.

Body:
I am developing a Flask REST API which will have three query parameters (HomeDevice, Key, UpdateDate), all passed as string. Now, I have to PyMongo query on Mongodb using these three inputs as filters.

typeof db.getCollection('collection_name').findOne().updatedate
>> Object

import json
from pymongo import MongoClient
import pandas as pd

client = MongoClient(<ServerAddress>,27017)
db = client.db_name
col = db.collection_name

updatedate="2020-01-13 06:43:47.500Z"
print(updatedate)

var = '{ "$and" : [{"homeDevice" : "Loader"} , {"key" : "OP2561NX" },{"updatedate" : ISODate("2020-01-13 06:43:47.500Z")}]}'
data = json.loads(var)
docs = pd.DataFrame(list(col.find(data)))
print(docs)

ISODate(updateDate) is causing JSONDecodeError, and after removing ISODate casting, query fetches empty frame.

JSONDecodeError                           Traceback (most recent call last)
<ipython-input-12-95360c676df4> in <module>
     11
     12 var = '{ "$and" : [{"homeDevice" : "Loader"} , {"keyed" : "OP2561NX" },{"updatedate" : ISODate("2020-01-13 06:43:47.500Z")}]}'
---> 13 data = json.loads(var)
     14 docs = pd.DataFrame(list(col.find(data)))
     15 print(docs)

E:\Analytics\Installations\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

E:\Analytics\Installations\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
    335
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

E:\Analytics\Installations\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 81 (char 80)

Running this query directly in monogodb (Robo3T) returns data. I need a way to create query dynamically and apply ISODate on updatedate key.

How to create dynamic PyMongo query to handle ISODate?

Body:
Construct var like a dictionary:

var = { "$and" : [{"homeDevice" : "Loader"} , {"key" : "OP2561NX" },{"updatedate" : ISO("2020-01-13 06:43:47.500Z")}]}

and use it like:

col.find(var)

You don't need to convert it to string/JSON.

Try the above and let me know.


问:
[Snowflake-jdbc]It hangs when get info from resetset object of connection.getMetadata().getColumns(...)
I try to test the jdbc connection of snowflake with codes below

```<code>                Connection conn = .......
                .......
                ResultSet rs = conn.getMetaData().getColumns(**null**, "PUBLIC", "TAB1", null); // 1. set parameters to get metadata of table TAB1

                while (rs.next()) {   // 2. It hangs here if the first parameter is null in above liune; otherwise(set the corrent db name), it works fine
                    System.out.println( "precision:" + rs.getInt(7)
                                       + ",col type name:" + rs.getString(6)
                                       + ",col type:" + rs.getInt(5)
                                       + ",col name:" + rs.getString(4)
                                       + ",CHAR_OCTET_LENGTH:" + rs.getInt(16)
                                       + ",buf LENGTH:" + rs.getString(8)
                                       + ",SCALE:" + rs.getInt(9));
                }
                .......
</code>```

I debug the codes above in Intellij IDEA, and find that the debugger can't get the details of the object, it always shows "Evaluating..."

The JDBC driver I used is snowflake-jdbc-3.12.5.jar

Is it a bug?

答:
There is no issue with the 3.12.5 jar.I just tested the same version in Eclipse, I can inspect all the objects . Could be an issue with your IDE.

```<code>ResultSet columns = metaData.getColumns(null, null, "TESTTABLE123",null);

            while (columns.next()){
                 System.out.print("Column name and size: "+columns.getString("COLUMN_NAME"));
                 System.out.print("("+columns.getInt("COLUMN_SIZE")+")");
                 System.out.println(" ");
                 System.out.println("COLUMN_DEF : "+columns.getString("COLUMN_DEF"));
                 System.out.println("Ordinal position: "+columns.getInt("ORDINAL_POSITION"));
                 System.out.println("Catalog: "+columns.getString("TABLE_CAT"));
                 System.out.println("Data type (integer value): "+columns.getInt("DATA_TYPE"));
                 System.out.println("Data type name: "+columns.getString("TYPE_NAME"));
                 System.out.println(" ");
              }
</code>```

Body:
I try to test the jdbc connection of snowflake with codes below

                Connection conn = .......
                .......
                ResultSet rs = conn.getMetaData().getColumns(**null**, "PUBLIC", "TAB1", null); // 1. set parameters to get metadata of table TAB1

                while (rs.next()) {   // 2. It hangs here if the first parameter is null in above liune; otherwise(set the corrent db name), it works fine
                    System.out.println( "precision:" + rs.getInt(7)
                                       + ",col type name:" + rs.getString(6)
                                       + ",col type:" + rs.getInt(5)
                                       + ",col name:" + rs.getString(4)
                                       + ",CHAR_OCTET_LENGTH:" + rs.getInt(16)
                                       + ",buf LENGTH:" + rs.getString(8)
                                       + ",SCALE:" + rs.getInt(9));
                }
                .......

I debug the codes above in Intellij IDEA, and find that the debugger can't get the details of the object, it always shows "Evaluating..."

The JDBC driver I used is snowflake-jdbc-3.12.5.jar

Is it a bug?

Body:
There is no issue with the 3.12.5 jar.I just tested the same version in Eclipse, I can inspect all the objects . Could be an issue with your IDE.

ResultSet columns = metaData.getColumns(null, null, "TESTTABLE123",null);

            while (columns.next()){
                 System.out.print("Column name and size: "+columns.getString("COLUMN_NAME"));
                 System.out.print("("+columns.getInt("COLUMN_SIZE")+")");
                 System.out.println(" ");
                 System.out.println("COLUMN_DEF : "+columns.getString("COLUMN_DEF"));
                 System.out.println("Ordinal position: "+columns.getInt("ORDINAL_POSITION"));
                 System.out.println("Catalog: "+columns.getString("TABLE_CAT"));
                 System.out.println("Data type (integer value): "+columns.getInt("DATA_TYPE"));
                 System.out.println("Data type name: "+columns.getString("TYPE_NAME"));
                 System.out.println(" ");
              }


问:
How do you force Perl to re-compile a regex compiled with "/o" on demand?
Technical question:

Given a regex:

```<code>my $regEx = qr{whatever$myVar}oxi; # Notice /o for "compile-once"
</code>```

What is the most effective way to force it to recompile on demand? (e.g. when I know from the program logic that $myVar value changed) without dropping /o and depending on Perl's internal smarts to auto-recompile?

NOTE: The regex is used in a substitution, which may affect re-compilation rules sans /o:

```<code>$string2 =~ s/$regEx//;
</code>```

The context is:

I have a regular expression that is built by slurping in a fairly long (>1k long) string from a config file.

That file is re-read once every 60 minutes.

If the string read from the file changes (as defined by changing file timestamp), I want to re-compile the regex using the re-slurped string value in $myVar.

The regex is used repeatedly and frequently in the Perl module running under mod_perl.

This means that (coupled with the string being >1-2k long) I must use "/o" modifier to force compile-once on the regex, to avoid performance hit of Perl repeatedly checking if the variable value changed (this heuristic is from perlop qr//, since the regex is used as part  of s/// as shown above and not by itself as a match).

That in turn means that, when I know that the variable changed after re-slurping it in 1 hour, I need to force the regex to re-compile despite the /o modifier.

UPDATE: Here's an illustration of why I need /o - without it, the regex is recompiled (and thus necessarily checked) every loop iteration; with it it is NOT:

```<code>$ perl -e '{for (my $i=0; $i<3; $i++) {
                 my $re = qr{$i}oix; $s="123"; $s =~ s/$re//;
                 print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=123
i=2; s=123

$ perl -e '{ for (my $i=0; $i<3; $i++) {
                  my $re = qr{$i}ix; $s="123"; $s =~ s/$re//;
                  print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=23
i=2; s=13
</code>```

答:
when I know from the program logic that $myVar value changed

m//, s/// and qr// only compile if the pattern doesn't change. All you have to do to get the behaviour you requested is to remove the /o.

```<code>$ perl -Mre=debug -e'
    qr/$_/ for qw( abc abc def def abc abc );
' 2>&1 | grep Compiling
Compiling REx "abc"
Compiling REx "def"
Compiling REx "abc"
</code>```

Therefore,

If the string read from the file changes (as defined by changing file timestamp), I want to re-compile the regex using the re-slurped string value in $myVar.

```<code>my $new_myVar = ...;
if ($myVar ne $new_myVar) {
   $re = qr/$new_myVar/;
   $myVar = $new_myVar;
}
...
s/$re/.../
</code>```

or just

```<code>$myVar = ...;
...
s/$myVar/.../
</code>```

Body:
Technical question:

Given a regex:

my $regEx = qr{whatever$myVar}oxi; # Notice /o for "compile-once"

What is the most effective way to force it to recompile on demand? (e.g. when I know from the program logic that $myVar value changed) without dropping /o and depending on Perl's internal smarts to auto-recompile?

NOTE: The regex is used in a substitution, which may affect re-compilation rules sans /o:

$string2 =~ s/$regEx//;

The context is:

I have a regular expression that is built by slurping in a fairly long (>1k long) string from a config file.

That file is re-read once every 60 minutes.

If the string read from the file changes (as defined by changing file timestamp), I want to re-compile the regex using the re-slurped string value in $myVar.

The regex is used repeatedly and frequently in the Perl module running under mod_perl.

This means that (coupled with the string being >1-2k long) I must use "/o" modifier to force compile-once on the regex, to avoid performance hit of Perl repeatedly checking if the variable value changed (this heuristic is from perlop qr//, since the regex is used as part  of s/// as shown above and not by itself as a match).

That in turn means that, when I know that the variable changed after re-slurping it in 1 hour, I need to force the regex to re-compile despite the /o modifier.

UPDATE: Here's an illustration of why I need /o - without it, the regex is recompiled (and thus necessarily checked) every loop iteration; with it it is NOT:

$ perl -e '{for (my $i=0; $i<3; $i++) {
                 my $re = qr{$i}oix; $s="123"; $s =~ s/$re//;
                 print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=123
i=2; s=123

$ perl -e '{ for (my $i=0; $i<3; $i++) {
                  my $re = qr{$i}ix; $s="123"; $s =~ s/$re//;
                  print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=23
i=2; s=13

Body:
when I know from the program logic that $myVar value changed

m//, s/// and qr// only compile if the pattern doesn't change. All you have to do to get the behaviour you requested is to remove the /o.

$ perl -Mre=debug -e'
    qr/$_/ for qw( abc abc def def abc abc );
' 2>&1 | grep Compiling
Compiling REx "abc"
Compiling REx "def"
Compiling REx "abc"

Therefore,

If the string read from the file changes (as defined by changing file timestamp), I want to re-compile the regex using the re-slurped string value in $myVar.

my $new_myVar = ...;
if ($myVar ne $new_myVar) {
   $re = qr/$new_myVar/;
   $myVar = $new_myVar;
}
...
s/$re/.../

or just

$myVar = ...;
...
s/$myVar/.../


问:
How to use a variable inside a carbon datetime?
Good morning guys, i need to have a custom date that always has the current date but a certain time to be able to compare two dates and get the remaining time. At the moment something like this occurred to me:

```<code> $day=date("d");
            $dayy= now();
            $datelim= Carbon::createFromFormat('Y-m-d H:i:s', '2020-05-',$day, '22:00:02');
return view('fen.index', [

        'works' => Period::select('paperiod.descriptionp','pamatrixinfoperio.description', 'pamatrixinfoperio.codpar')
                ->join('pamatrixinfoperio', 'pamatrixinfoperio.cod_paperiod', '=', 'paperiod.cod')
                ->where('pamatrixinfoperio.read_at', '=', 0, 'AND')
                ->where('pamatrixinfoperio.cod_paperiod', '=', 1)
                ->get(),
        'Periodres' => $fechalim

        ]);
</code>```

but I don't know how to concatenate that variable day in the carbon '2020-05-',$day, '22:00:02' , How could I use it because my objective is that the variable always has the current day, Monday, Tuesday, Wednesday, but that the time is always the same.

On the other hand, I don't know if they could help me. How can I compare dayy and datelim? So in the view I can have for example: "The work is about to end in 3 days, 3 hours and 20 seconds" I hope you can help me, because I find more complex examples in carbon but not basic and I don't know how to do this :(

my view is this:

```<code> @extends('layouts.app')

    @section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">WorksF</div>

                    <div class="card-body">
                        @if (session('status'))
                            <div class="alert alert-success" role="alert">
                                {{ session('status') }}
                            </div>
                        @endif

                        Welcome {{Auth::user()->name}}, Lasis informs you that the following files are about to end in:
@foreach($works as $work)
            <li class="list-group-item">
            {{$work->description}}
            you have the next time to deliver the report:
            <b>{{$Periodres}}</b>
   </li>
@endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endsection
</code>```

As you can see the view is not finished but I am looking for something similar, Thanks in advance for the help.

答:
Concatenation in PHP use . not , and you need a space between $day and the hour.

```<code>Carbon::createFromFormat('Y-m-d H:i:s', '2020-05-' . $day . ' 22:00:02');
</code>```

Of course Carbon::create() as suggested by Nacho is appropriate, but still Carbon::createFromFormat() works also fine if the given input is given as 1 single string and matches the format.

Body:
Good morning guys, i need to have a custom date that always has the current date but a certain time to be able to compare two dates and get the remaining time. At the moment something like this occurred to me:

 $day=date("d");
            $dayy= now();
            $datelim= Carbon::createFromFormat('Y-m-d H:i:s', '2020-05-',$day, '22:00:02');
return view('fen.index', [

        'works' => Period::select('paperiod.descriptionp','pamatrixinfoperio.description', 'pamatrixinfoperio.codpar')
                ->join('pamatrixinfoperio', 'pamatrixinfoperio.cod_paperiod', '=', 'paperiod.cod')
                ->where('pamatrixinfoperio.read_at', '=', 0, 'AND')
                ->where('pamatrixinfoperio.cod_paperiod', '=', 1)
                ->get(),
        'Periodres' => $fechalim

        ]);

but I don't know how to concatenate that variable day in the carbon '2020-05-',$day, '22:00:02' , How could I use it because my objective is that the variable always has the current day, Monday, Tuesday, Wednesday, but that the time is always the same.

On the other hand, I don't know if they could help me. How can I compare dayy and datelim? So in the view I can have for example: "The work is about to end in 3 days, 3 hours and 20 seconds" I hope you can help me, because I find more complex examples in carbon but not basic and I don't know how to do this :(

my view is this:

 @extends('layouts.app')

    @section('content')

WorksF

                        @if (session('status'))

                                {{ session('status') }}

                        @endif

                        Welcome {{Auth::user()->name}}, Lasis informs you that the following files are about to end in:
@foreach($works as $work)

            {{$work->description}}
            you have the next time to deliver the report:
            {{$Periodres}}

@endforeach

    @endsection

As you can see the view is not finished but I am looking for something similar, Thanks in advance for the help.

Body:
Concatenation in PHP use . not , and you need a space between $day and the hour.

Carbon::createFromFormat('Y-m-d H:i:s', '2020-05-' . $day . ' 22:00:02');

Of course Carbon::create() as suggested by Nacho is appropriate, but still Carbon::createFromFormat() works also fine if the given input is given as 1 single string and matches the format.


问:
Dynamically hooking up a class having different possible constructors
Let's say I have two classes that look like this:

```<code>public class ByteFilter
{
    private Func <int, byte[]> readBytes;
    private Action<byte[]> writeBytes;

    public ByteFilter(Func <int, byte[]> readBytes, Action<byte[]> writeBytes)
    {
        this.readBytes = readBytes;
        this.writeBytes = writeBytes;
    }
}

public class PacketFilter
{
    private Func<Packet> readPacket;
    private Action<Packet> writePacket;

    Public PacketFilter(Func<Packet> readPacket, Action<Packet> writePacket)
    {
        this.readBytes = readPacket;
        this.writeBytes = writePacket;
    }
}
</code>```

Either class may be instantiated at runtime (via Activator.CreateInstance) to perform a filtering function.  The read and write methods will be hooked up at runtime to methods from other classes that will provide and accept byte arrays or packets.

Within each filter is additional code that performs the filtering function:

```<code>public void Process()
{
    while (!done)
    {
        byte[] data = ReadBytes();      // or ReadPacket()
        // perform filtering on data
        WriteBytes(data);               // or WritePacket()
    }
}
</code>```

If only one of the above constructor signatures will be present in each filter, how do I determine (using Reflection) which constructor signature is present, so that I can hook up the appropriate methods at runtime?

Note: If I'm daffy and doing this the wrong way, I'd like to know that too.

答: You can enumerate the constructors (to get the one constructor) and then enumerate the parameters of the constructor.  Since the parameters are expected to be generic types, you then need to enumerate the generic type parameters for each generic constructor parameter.  Note that all of this is very hacky and I would recommend finding a better solution.  Reflection is a powerful tool and using it introduces complexity; if there is a less complex solution (such as a factory pattern, perhaps), that would be preferable.  It's also possible that your need to solve this particular problem reflects excessive complication in your existing design.  If you simplify the original design, you may find that the technical problem goes away.</p>

Body:
Let's say I have two classes that look like this:

public class ByteFilter
{
    private Func <int, byte[]> readBytes;
    private Action<byte[]> writeBytes;

    public ByteFilter(Func <int, byte[]> readBytes, Action<byte[]> writeBytes)
    {
        this.readBytes = readBytes;
        this.writeBytes = writeBytes;
    }
}

public class PacketFilter
{
    private Func<Packet> readPacket;
    private Action<Packet> writePacket;

    Public PacketFilter(Func<Packet> readPacket, Action<Packet> writePacket)
    {
        this.readBytes = readPacket;
        this.writeBytes = writePacket;
    }
}

Either class may be instantiated at runtime (via Activator.CreateInstance) to perform a filtering function.  The read and write methods will be hooked up at runtime to methods from other classes that will provide and accept byte arrays or packets.

Within each filter is additional code that performs the filtering function:

public void Process()
{
    while (!done)
    {
        byte[] data = ReadBytes();      // or ReadPacket()
        // perform filtering on data
        WriteBytes(data);               // or WritePacket()
    }
}

If only one of the above constructor signatures will be present in each filter, how do I determine (using Reflection) which constructor signature is present, so that I can hook up the appropriate methods at runtime?

Note: If I'm daffy and doing this the wrong way, I'd like to know that too.


问:
R: find and set to zero each element in a vector that does not appear in another vector
I have two numeric vectors:

```<code>a <- c(1,2,3,4,5,6,7,8)
b <- c(4,2,2,3,9,10,7,7,10,14)
</code>```

I want to set any number in b that does not appear in a to zero.
 My desired result is:

```<code>c <- c(4,2,2,3,0,0,7,7,0,0)
</code>```

who can I do this in an elegant way?

(I was thinking to use left_join but I think there must be some more elegant approach)

答:
We can use replace

```<code>replace(b, !b  %in% a, 0)
</code>```

Body:
I have two numeric vectors:

a <- c(1,2,3,4,5,6,7,8)
b <- c(4,2,2,3,9,10,7,7,10,14)

I want to set any number in b that does not appear in a to zero.
 My desired result is:

c <- c(4,2,2,3,0,0,7,7,0,0)

who can I do this in an elegant way?

(I was thinking to use left_join but I think there must be some more elegant approach)

Body:
We can use replace

replace(b, !b  %in% a, 0)


问:
Mocha for node js app in Visual Studio 2019 is not showing Tests in Test Explorer when reference or require another file
I am using node js in VS 2019.  I want to try Mocha as the test platform so I have gone through and installed that and got it working in a basic sense.  I have a simple calculator node js file (calc.js).

I have another file that has basic hello world tests (basictest.js).  If I do NOT put in the "require" line for Calc.js, then these tests (Test 1 and Test 2) are discovered by VS 2019 test explorer and are listed.

However, I need the require line to access the calculator app, so when I put the require line var mycalc = require('./Scripts/Calc.js'); in there, the tests are NOT discovered.  The same thing happens if I try a reference path=.. to it. I am new to node js so I could be missing something seemingly obvious as well when referencing functions in another js file.

basictest.js:

```<code>'use strict';

var assert = require('assert');
var mycalc = require('./Scripts/Calc.js');

describe('Test Suite 1', function () {
it('Test 1', function () {
    assert.ok(true, "This shouldn't fail");
});

it('Test 2', function () {
    assert.ok(1 === 1, "This shouldn't fail");
    assert.ok(false, "This should fail");
});
});
</code>```

答:
Ok ... I figured it out after hours of searching online and had no success.

This line here wasn't completely correct:
   var mycalc = require('./Scripts/Calc.js');

For some reason js finds the calc.js file and test file.  However, the test explorer wasn't able to discover the tests.  The reason is a simple "."  My guess is that ./Scripts/ puts current working directory in the Scripts directory and VS is unable to find the tests.  Just adding a second "." moves it back a directory so the Tests can be found.

Correct code:
   var mycalc = require('../Scripts/Calc.js');

Body:
I am using node js in VS 2019.  I want to try Mocha as the test platform so I have gone through and installed that and got it working in a basic sense.  I have a simple calculator node js file (calc.js).

I have another file that has basic hello world tests (basictest.js).  If I do NOT put in the "require" line for Calc.js, then these tests (Test 1 and Test 2) are discovered by VS 2019 test explorer and are listed.

However, I need the require line to access the calculator app, so when I put the require line var mycalc = require('./Scripts/Calc.js'); in there, the tests are NOT discovered.  The same thing happens if I try a reference path=.. to it. I am new to node js so I could be missing something seemingly obvious as well when referencing functions in another js file.

basictest.js:

'use strict';

var assert = require('assert');
var mycalc = require('./Scripts/Calc.js');

describe('Test Suite 1', function () {
it('Test 1', function () {
    assert.ok(true, "This shouldn't fail");
});

it('Test 2', function () {
    assert.ok(1 === 1, "This shouldn't fail");
    assert.ok(false, "This should fail");
});
});