问:
perl help troubleshooting error msg using perl module
I am testing perl script using this example found on the forum. I took the sample data and put it in a separate file and using an open to try it this way.

I don't understand why I would be getting undef. I am getting the msg:

Use of uninitialized value in join or string at ./h.pl line 15,  line 4.

```<code>#!/usr/local/bin/perl

use warnings;
use strict;
use Data::Dumper;
use Text::CSV_XS;

    open my $fh, '<', 't.out' or die "Unable to open: $!";
    my $csv = Text::CSV_XS->new( { sep_char => "\t" } );
    my @list;
    $csv->column_names ($csv->getline ($fh));
    while ( my $hr = $csv->getline_hr($fh) ) {
        push @list, $hr->{'Ball'};
    }

    print "@list\n";
    print Dumper(\@list);
</code>```

Test file (t.out)

```<code>Camera Make Camera Model    Text    Ball    Swing
a   b   c   d   e
f   g   h   i   j
k   l   m   n   o

$ od -cx t.out
0000000   C   a   m   e   r   a       M   a   k   e  \t   C   a   m   e
        6143 656d 6172 4d20 6b61 0965 6143 656d
0000020   r   a       M   o   d   e   l  \t   T   e   x   t  \t   B   a
        6172 4d20 646f 6c65 5409 7865 0974 6142
0000040   l   l  \t   S   w   i   n   g  \n   a  \t   b  \t   c  \t   d
        6c6c 5309 6977 676e 610a 6209 6309 6409
0000060  \t   e  \n   f  \t   g  \t   h  \t   i  \t   j  \n   k  \t   l
        6509 660a 6709 6809 6909 6a09 6b0a 6c09
0000100  \t   m  \t   n  \t   o  \n  \0
        6d09 6e09 6f09 000a
0000107
</code>```

Results:

```<code>$VAR1 = [
          undef,
          undef,
          undef
        ];
</code>```

答:
If $csv->getline_hr($fh) returns an undefined value, you will get the warning "Use of uninitialized value in join or string at ..." if you try to print the list @list.

You can test this explicitly with a simple program:

```<code>use strict;
use warnings;
my @list;
my $x = undef; # This is similar to what may happen in your program on the `push @list, @hr->{'Name'}` line
push @list, $x;
print "@list\n";
</code>```

Also, you may want to use Data::Dumper and then print Dumper(\@list) instead if you are just doing debugging, since you won't get any warnings, and you will get a clearer picture of what is stored in your data structure.

Body:
I am testing perl script using this example found on the forum. I took the sample data and put it in a separate file and using an open to try it this way.

I don't understand why I would be getting undef. I am getting the msg:

Use of uninitialized value in join or string at ./h.pl line 15,  line 4.

#!/usr/local/bin/perl

use warnings;
use strict;
use Data::Dumper;
use Text::CSV_XS;

    open my $fh, '<', 't.out' or die "Unable to open: $!";
    my $csv = Text::CSV_XS->new( { sep_char => "\t" } );
    my @list;
    $csv->column_names ($csv->getline ($fh));
    while ( my $hr = $csv->getline_hr($fh) ) {
        push @list, $hr->{'Ball'};
    }

    print "@list\n";
    print Dumper(\@list);

Test file (t.out)

Camera Make Camera Model    Text    Ball    Swing
a   b   c   d   e
f   g   h   i   j
k   l   m   n   o

$ od -cx t.out
0000000   C   a   m   e   r   a       M   a   k   e  \t   C   a   m   e
        6143 656d 6172 4d20 6b61 0965 6143 656d
0000020   r   a       M   o   d   e   l  \t   T   e   x   t  \t   B   a
        6172 4d20 646f 6c65 5409 7865 0974 6142
0000040   l   l  \t   S   w   i   n   g  \n   a  \t   b  \t   c  \t   d
        6c6c 5309 6977 676e 610a 6209 6309 6409
0000060  \t   e  \n   f  \t   g  \t   h  \t   i  \t   j  \n   k  \t   l
        6509 660a 6709 6809 6909 6a09 6b0a 6c09
0000100  \t   m  \t   n  \t   o  \n  \0
        6d09 6e09 6f09 000a
0000107

Results:

$VAR1 = [
          undef,
          undef,
          undef
        ];

Body:
If $csv->getline_hr($fh) returns an undefined value, you will get the warning "Use of uninitialized value in join or string at ..." if you try to print the list @list.

You can test this explicitly with a simple program:

use strict;
use warnings;
my @list;
my $x = undef; # This is similar to what may happen in your program on the `push @list, @hr->{'Name'}` line
push @list, $x;
print "@list\n";

Also, you may want to use Data::Dumper and then print Dumper(\@list) instead if you are just doing debugging, since you won't get any warnings, and you will get a clearer picture of what is stored in your data structure.


来源: stackexchange

问:
Is there any difference between bag= bag + n - i +1 and bag += n - i + 1
Is there any difference between bag= bag + n - i +1  and bag += n - i + 1 bcs is shows differnt while running a program below:

var n = 5
for (i = 1; i <= n; i++) {
  var bag = ""

  for (j = 1; j <= n - i + 1; j++) {
    bag += n - j + 1
  }
  console.log(bag)
}
// 2nd way
var n = 5; //
for (let i = 1; i <= n; i++) {
  var string = "";
  for (let j = 1; j <= n - i + 1; j++) {
    string = string + n - j + 1;
  }
  console.log(string);
}```

Replit link

答:
Yes, there is a difference. The difference is to do with the order that your operators are evaluated:

```<code>bag += n - i + 1
</code>```

is the same as:

```<code>bag = bag + (n - i + 1) // string concatenation as `bag` is a string and we're using `+`
</code>```

Notice that n - i + 1 is grouped (( )) because it is on the right-hand side of the +=, so it is evaluated/calculated first before being concatenated with the string bag. Both of the above lines of code are different from your other alternative of:

bag = bag + n - i +1
```
<p>Here there is no grouping, so the order in which the operators are evaluated is different (see operator precedence). The above is equivalent to:</p>
<pre class="lang-js prettyprint-override"><code>bag = (bag + n) - (i + 1) // (string) - (number)
</code>```

... which you can hopefully see will give different results from the first two lines above, as you are now subtracting different quantities. Moreover, as you're using subtraction, your results will now be numbers.

ContentLicense: CC BY-SA 4.0

Body:
Is there any difference between bag= bag + n - i +1  and bag += n - i + 1 bcs is shows differnt while running a program below:

var n = 5
for (i = 1; i <= n; i++) {
  var bag = ""

  for (j = 1; j <= n - i + 1; j++) {
    bag += n - j + 1
  }
  console.log(bag)
}
// 2nd way
var n = 5; //
for (let i = 1; i <= n; i++) {
  var string = "";
  for (let j = 1; j <= n - i + 1; j++) {
    string = string + n - j + 1;
  }
  console.log(string);
}

Replit link

Body:
Yes, there is a difference. The difference is to do with the order that your operators are evaluated:

bag += n - i + 1

is the same as:

bag = bag + (n - i + 1) // string concatenation as `bag` is a string and we're using `+`

Notice that n - i + 1 is grouped (( )) because it is on the right-hand side of the +=, so it is evaluated/calculated first before being concatenated with the string bag. Both of the above lines of code are different from your other alternative of:

bag = bag + n - i +1

Here there is no grouping, so the order in which the operators are evaluated is different (see operator precedence). The above is equivalent to:

bag = (bag + n) - (i + 1) // (string) - (number)

... which you can hopefully see will give different results from the first two lines above, as you are now subtracting different quantities. Moreover, as you're using subtraction, your results will now be numbers.


问:
Multiple ssh key for the same gitlab host
I'm having two gitlab.com accounts and since GitLab does not allow me to use the same ssh key, I have to generate two ssh keys.

I'm trying to config the ssh, here is my config:

```<code>Host company
    HostName gitlab.com
    User vunh
    IdentityFile ~/.ssh/id_rsa
Host private
    Hostname gitlab.com
    User hoangvu271297
    IdentityFile ~/.ssh/private
</code>```

Both accounts are logged in to the same domain gitlab.com.

Previously, I did not config anything because I only use the id_rsa.
Until now the id_rsa still works fine but I can not find a way out to clone the project using the private one.
I tried many configs on the Internet but no one works.

Is there any way to deal with this situation? I knew it is configurable if there are two different hosts such as gitlab.com and work.gitlab.com

Many thanks.

答:
The documentation covers this scenario.

You should setup your ssh config using two different Host configurations for each user. Say, user_1.gitlab.com and user_2.gitlab.com. You can use whatever value you want here, these are just examples.

```<code># User1 Account Identity
Host user_1.gitlab.com
  Hostname gitlab.com
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/example_ssh_key1

# User2 Account Identity
Host user_2.gitlab.com
  Hostname gitlab.com
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/example_ssh_key2
</code>```

You then use these Host keys when setting up your git repos.

For example, to clone using user_1 account:

```<code>git clone git@user_1.gitlab.com:gitlab-org/gitlab.git
</code>```

Note that you should NOT provide your username as the User configuration in your SSH config. The username you use to connect to GitLab over SSH is always git. The identity file (ssh key), not ssh user, determines the GitLab user account.

Body:
I'm having two gitlab.com accounts and since GitLab does not allow me to use the same ssh key, I have to generate two ssh keys.

I'm trying to config the ssh, here is my config:

Host company
    HostName gitlab.com
    User vunh
    IdentityFile ~/.ssh/id_rsa
Host private
    Hostname gitlab.com
    User hoangvu271297
    IdentityFile ~/.ssh/private

Both accounts are logged in to the same domain gitlab.com.

Previously, I did not config anything because I only use the id_rsa.
Until now the id_rsa still works fine but I can not find a way out to clone the project using the private one.
I tried many configs on the Internet but no one works.

Is there any way to deal with this situation? I knew it is configurable if there are two different hosts such as gitlab.com and work.gitlab.com

Many thanks.

Body:
The documentation covers this scenario.

You should setup your ssh config using two different Host configurations for each user. Say, user_1.gitlab.com and user_2.gitlab.com. You can use whatever value you want here, these are just examples.

# User1 Account Identity
Host user_1.gitlab.com
  Hostname gitlab.com
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/example_ssh_key1

# User2 Account Identity
Host user_2.gitlab.com
  Hostname gitlab.com
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/example_ssh_key2

You then use these Host keys when setting up your git repos.

For example, to clone using user_1 account:

git clone git@user_1.gitlab.com:gitlab-org/gitlab.git

Note that you should NOT provide your username as the User configuration in your SSH config. The username you use to connect to GitLab over SSH is always git. The identity file (ssh key), not ssh user, determines the GitLab user account.


答:
It seems like your @list array is undefined. Try checking it:

```<code>if (scalar @list) {
    print "@list\n";
}
</code>```

If your while loop has never been executed, scalar @list will return 0, because the array is empty.

ContentLicense: CC BY-SA 3.0

Title: perl help troubleshooting error msg using perl module

Body:
It seems like your @list array is undefined. Try checking it:

if (scalar @list) {
    print "@list\n";
}

If your while loop has never been executed, scalar @list will return 0, because the array is empty.


问:
Not able to find spark-warehouse directory
I am a beginner in Spark Programming.
I was practicing the below program:

```<code>package practice.spark.examples

import org.apache.log4j.Logger
import org.apache.spark.sql.{SaveMode, SparkSession}

object SparkSQLTableDemo extends Serializable {
  @transient lazy val logger: Logger = Logger.getLogger(getClass.getName)

  def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder()
      .appName("SparkSQLTableDemo")
      .master("local[3]")
      .enableHiveSupport()  // to allow the connectivity to a persistent Hive Metastore.
      .getOrCreate()

    val flightTimeParquetDF = spark.read
      .format("parquet")
      .option("path", "data/flight*.parquet")
      .load()

    spark.sql("CREATE DATABASE IF NOT EXISTS AIRLINE_DB")
    spark.catalog.setCurrentDatabase("AIRLINE_DB")

    flightTimeParquetDF.write
      .mode(SaveMode.Overwrite)
      .partitionBy("ORIGIN", "OP_CARRIER")
      .saveAsTable("flight_data_tbl")

    spark.catalog.listTables("AIRLINE_DB").show()
    //spark.sql("Select * from flight_data_tbl limit 5").show()

    logger.info("Finished.")
    spark.stop()
  }

}
</code>```

After running this code we must get 2 directories created right?
1:metastore_db 2:spark-warehouse

But in the current directory, only metastore_db was created.
My spark-warehouse folder was created in the Desktop/ location.
Attaching the pics below:
enter image description here
enter image description here

I tried googling about how to set the spark-warehouse directory but was very confused.
Also every time I run the code I get the below warnings. I thought this has something to do with the error.

```<code>    22/02/12 21:30:22 WARN HiveConf: HiveConf of name hive.stats.jdbc.timeout does not exist
22/02/12 21:30:22 WARN HiveConf: HiveConf of name hive.stats.retries.wait does not exist
22/02/12 21:30:31 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped
22/02/12 21:30:33 WARN ObjectStore: Version information not found in metastore. hive.metastore.schema.verification is not enabled so recording the schema version 2.3.0
22/02/12 21:30:33 WARN ObjectStore: setMetaStoreSchemaVersion called but recording version is disabled: version = 2.3.0, comment = Set by MetaStore UNKNOWN@192.168.56.1
22/02/12 21:30:33 WARN ObjectStore: Failed to get database global_temp, returning NoSuchObjectException
22/02/12 21:31:02 WARN SessionState: METASTORE_FILTER_HOOK will be ignored, since hive.security.authorization.manager is set to instance of HiveAuthorizerFactory.
22/02/12 21:31:02 WARN HiveConf: HiveConf of name hive.internal.ss.authz.settings.applied.marker does not exist
22/02/12 21:31:02 WARN HiveConf: HiveConf of name hive.stats.jdbc.timeout does not exist
22/02/12 21:31:02 WARN HiveConf: HiveConf of name hive.stats.retries.wait does not exist
</code>```

Can someone please guide me in any way such that I can set the warehouse path to my current practice directory i.e., under metastore_db as shown in Image1 ?

Thank You in Advance :)

答:
You can use below example to specify metastore location.

```<code>import java.io.File

import org.apache.spark.sql.{Row, SaveMode, SparkSession}

case class Record(key: Int, value: String)

// warehouseLocation points to the default location for managed databases and tables
val warehouseLocation = new File("spark-warehouse").getAbsolutePath

val spark = SparkSession
  .builder()
  .appName("Spark Hive Example")
  .config("spark.sql.warehouse.dir", warehouseLocation)
  .enableHiveSupport()
  .getOrCreate()
</code>```

Details please refer https://spark.apache.org/docs/latest/sql-data-sources-hive-tables.html

Body:
I am a beginner in Spark Programming.
I was practicing the below program:

package practice.spark.examples

import org.apache.log4j.Logger
import org.apache.spark.sql.{SaveMode, SparkSession}

object SparkSQLTableDemo extends Serializable {
  @transient lazy val logger: Logger = Logger.getLogger(getClass.getName)

  def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder()
      .appName("SparkSQLTableDemo")
      .master("local[3]")
      .enableHiveSupport()  // to allow the connectivity to a persistent Hive Metastore.
      .getOrCreate()

    val flightTimeParquetDF = spark.read
      .format("parquet")
      .option("path", "data/flight*.parquet")
      .load()

    spark.sql("CREATE DATABASE IF NOT EXISTS AIRLINE_DB")
    spark.catalog.setCurrentDatabase("AIRLINE_DB")

    flightTimeParquetDF.write
      .mode(SaveMode.Overwrite)
      .partitionBy("ORIGIN", "OP_CARRIER")
      .saveAsTable("flight_data_tbl")

    spark.catalog.listTables("AIRLINE_DB").show()
    //spark.sql("Select * from flight_data_tbl limit 5").show()

    logger.info("Finished.")
    spark.stop()
  }

}

After running this code we must get 2 directories created right?
1:metastore_db 2:spark-warehouse

But in the current directory, only metastore_db was created.
My spark-warehouse folder was created in the Desktop/ location.
Attaching the pics below:
enter image description here
enter image description here

I tried googling about how to set the spark-warehouse directory but was very confused.
Also every time I run the code I get the below warnings. I thought this has something to do with the error.

    22/02/12 21:30:22 WARN HiveConf: HiveConf of name hive.stats.jdbc.timeout does not exist
22/02/12 21:30:22 WARN HiveConf: HiveConf of name hive.stats.retries.wait does not exist
22/02/12 21:30:31 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped
22/02/12 21:30:33 WARN ObjectStore: Version information not found in metastore. hive.metastore.schema.verification is not enabled so recording the schema version 2.3.0
22/02/12 21:30:33 WARN ObjectStore: setMetaStoreSchemaVersion called but recording version is disabled: version = 2.3.0, comment = Set by MetaStore UNKNOWN@192.168.56.1
22/02/12 21:30:33 WARN ObjectStore: Failed to get database global_temp, returning NoSuchObjectException
22/02/12 21:31:02 WARN SessionState: METASTORE_FILTER_HOOK will be ignored, since hive.security.authorization.manager is set to instance of HiveAuthorizerFactory.
22/02/12 21:31:02 WARN HiveConf: HiveConf of name hive.internal.ss.authz.settings.applied.marker does not exist
22/02/12 21:31:02 WARN HiveConf: HiveConf of name hive.stats.jdbc.timeout does not exist
22/02/12 21:31:02 WARN HiveConf: HiveConf of name hive.stats.retries.wait does not exist

Can someone please guide me in any way such that I can set the warehouse path to my current practice directory i.e., under metastore_db as shown in Image1 ?

Thank You in Advance :)

Body:
You can use below example to specify metastore location.

import java.io.File

import org.apache.spark.sql.{Row, SaveMode, SparkSession}

case class Record(key: Int, value: String)

// warehouseLocation points to the default location for managed databases and tables
val warehouseLocation = new File("spark-warehouse").getAbsolutePath

val spark = SparkSession
  .builder()
  .appName("Spark Hive Example")
  .config("spark.sql.warehouse.dir", warehouseLocation)
  .enableHiveSupport()
  .getOrCreate()

Details please refer https://spark.apache.org/docs/latest/sql-data-sources-hive-tables.html


答:
Why?

There is a difference because you are using the "+" operator for concatenation and using a "-" in the same line, so JS is implicitly casting between strings and numbers for you.

In the example of bag += n - j + 1, JS evaluates everything on the right side from left-to-right. Then that number is concatenated onto the end of the string named bag.

In the example of bag = bag + n - j + 1, JS again evaluates everything on the right side from left-to-right, but now we have a mixture of strings and numbers on the right, so you're seeing strange behavior resulting from the anti-pattern.

See here:

```<code>bag += n - j + 1       // => bag += 5 - 1 + 1     => bag += 5          => bag = "5"
bag = bag + n - j + 1  // => bag = "" + 5 - 1 + 1 => bag = "5" - 1 + 1 => bag = 5
</code>```

On the next loop, with the second syntax, you'll be adding to a number instead of concatenating to a string, which is what is causing your problem.

Solution

To fix this, you can technically just keep the first syntax, or you can wrap the numbers in parentheses, like so: bag = bag + (n - j + 1), but I would recommend considering making your casts explicit, like bag += String(n - j + 1) or bag = bag.concat(n - j + 1) and prevent mixing data types to ensure bugs like these don't come up again.

Title: Is there any difference between bag= bag + n - i +1 and bag += n - i + 1

Body:
Why?

There is a difference because you are using the "+" operator for concatenation and using a "-" in the same line, so JS is implicitly casting between strings and numbers for you.

In the example of bag += n - j + 1, JS evaluates everything on the right side from left-to-right. Then that number is concatenated onto the end of the string named bag.

In the example of bag = bag + n - j + 1, JS again evaluates everything on the right side from left-to-right, but now we have a mixture of strings and numbers on the right, so you're seeing strange behavior resulting from the anti-pattern.

See here:

bag += n - j + 1       // => bag += 5 - 1 + 1     => bag += 5          => bag = "5"
bag = bag + n - j + 1  // => bag = "" + 5 - 1 + 1 => bag = "5" - 1 + 1 => bag = 5

On the next loop, with the second syntax, you'll be adding to a number instead of concatenating to a string, which is what is causing your problem.

Solution

To fix this, you can technically just keep the first syntax, or you can wrap the numbers in parentheses, like so: bag = bag + (n - j + 1), but I would recommend considering making your casts explicit, like bag += String(n - j + 1) or bag = bag.concat(n - j + 1) and prevent mixing data types to ensure bugs like these don't come up again.


问:
How to customize the background image of an Ionic 5 app?
I'm trying to set an image takken from media manager in appery in my Ionic App, using Ionic 5... but the image doesn't show. I'm using following code in the SCSS section:

```<code>ion-content

{
--background: no-repeat center/cover url('/files/images/background.png');
}
</code>```

my implementation

Please help.

答:
There are a few issues with your SCSS code. So your code should be the following:

```<code>ion-content{
    --background:
url('../assets/images/a_2020_in_front_of_the_orchestra.jpg') no-repeat
center/cover;
}

ion-content.ion-color-secondary{
        --ion-color-base: none !important;
}
</code>```

Please correct the URL to the image.

Add the selector "ion-content.ion-color-secondary" with the property "--ion-color-base".

Body:
I'm trying to set an image takken from media manager in appery in my Ionic App, using Ionic 5... but the image doesn't show. I'm using following code in the SCSS section:

ion-content

{
--background: no-repeat center/cover url('/files/images/background.png');
}

my implementation

Please help.

Body:
There are a few issues with your SCSS code. So your code should be the following:

ion-content{
    --background:
url('../assets/images/a_2020_in_front_of_the_orchestra.jpg') no-repeat
center/cover;
}

ion-content.ion-color-secondary{
        --ion-color-base: none !important;
}

Please correct the URL to the image.

Add the selector "ion-content.ion-color-secondary" with the property "--ion-color-base".


问:
"Thousands" and " skip_blank_lines" arguments of pandas.read_csv would not work properly. Why?
This my code:

```<code>in[0]
      import pandas as pd
      df = pd.read_csv('datefile6.csv',thousands=',', skip_blank_lines=True)
      df

out[1]      month   day     year    salary   age
       0    8.0     15.0    2012.0  1400.0   25.0
       1    NaN     NaN     NaN     NaN      NaN
       2    9.0     4.0     2020.0  2500.0   26.0
</code>```

As we see the thousands did not work. Also, line[1] which is blank has not been skipped by the commands.

I expected ',' from the "thousands" command and removed line[1] from the "skip_blan_lines" command.

答:
thousands parameter is a property of the input file. It tells pandas that numbers in your csv file contain thousands character (typically comma or dot). Parameter thousands does not impact the output.

Consider this code:

```<code>import pandas as pd
df = pd.read_csv('datafile6.csv', sep=';', thousands=',', skip_blank_lines=True)
print(df)
</code>```

where datafile6.csv is:

```<code>month;day;year;salary;age
8;15;2,012;1,400;25
9;4;2,020;2,500;26
</code>```

I get the output as:

```<code>   month   day    year  salary   age
0    8.0  15.0  2012.0  1400.0  25.0
1    9.0   4.0  2020.0  2500.0  26.0
</code>```

and you can see that 1,400 has been correctly parsed as 1400 etc.

Regarding your question about skip_blank_lines. I suspect that instead of a completely blank line, your csv contains field separators.

Consider now this as the content from datafile6.csv:

```<code>month;day;year;salary;age
8;15;2,012;1,400;25
;;;;
9;4;2,020;2,500;26

9;3;2,021;3,200;33
</code>```

I get dataframe output as:

```<code>   month   day    year  salary   age
0    8.0  15.0  2012.0  1400.0  25.0
1    NaN   NaN     NaN     NaN   NaN
2    9.0   4.0  2020.0  2500.0  26.0
3    9.0   3.0  2021.0  3200.0  33.0
</code>```

NaN results from line #3 of datafile6.csv which is not really blank but has 4 field separators. Where as line #5 which is completely blank is skipped. This is the behaviour of parameter skip_blank_lines

Hope this clears.

Body:
This my code:

in[0]
      import pandas as pd
      df = pd.read_csv('datefile6.csv',thousands=',', skip_blank_lines=True)
      df

out[1]      month   day     year    salary   age
       0    8.0     15.0    2012.0  1400.0   25.0
       1    NaN     NaN     NaN     NaN      NaN
       2    9.0     4.0     2020.0  2500.0   26.0

As we see the thousands did not work. Also, line[1] which is blank has not been skipped by the commands.

I expected ',' from the "thousands" command and removed line[1] from the "skip_blan_lines" command.

Body:
thousands parameter is a property of the input file. It tells pandas that numbers in your csv file contain thousands character (typically comma or dot). Parameter thousands does not impact the output.

Consider this code:

import pandas as pd
df = pd.read_csv('datafile6.csv', sep=';', thousands=',', skip_blank_lines=True)
print(df)

where datafile6.csv is:

month;day;year;salary;age
8;15;2,012;1,400;25
9;4;2,020;2,500;26

I get the output as:

   month   day    year  salary   age
0    8.0  15.0  2012.0  1400.0  25.0
1    9.0   4.0  2020.0  2500.0  26.0

and you can see that 1,400 has been correctly parsed as 1400 etc.

Regarding your question about skip_blank_lines. I suspect that instead of a completely blank line, your csv contains field separators.

Consider now this as the content from datafile6.csv:

month;day;year;salary;age
8;15;2,012;1,400;25
;;;;
9;4;2,020;2,500;26

9;3;2,021;3,200;33

I get dataframe output as:

   month   day    year  salary   age
0    8.0  15.0  2012.0  1400.0  25.0
1    NaN   NaN     NaN     NaN   NaN
2    9.0   4.0  2020.0  2500.0  26.0
3    9.0   3.0  2021.0  3200.0  33.0

NaN results from line #3 of datafile6.csv which is not really blank but has 4 field separators. Where as line #5 which is completely blank is skipped. This is the behaviour of parameter skip_blank_lines

Hope this clears.


问:
Building a Kotlin + Java 9 project with Gradle
I'm fairly new to Gradle (and Java 9, to be honest), and I'm trying to use Gradle to build a simple library project that is a mix of Java 9 and Kotlin. More in detail, there is an interface in Java and an implementation in Kotlin; I'd do everything in Kotlin, but the modules-info.java is java anyway, so I decided to do things this way.

I'm building on IntelliJ Idea, with the 1.2.0 kotlin plugin and gradle 4.3.1 defined externally.

Filesystem schema is:

```<code>+ src
  + main
    + java
      + some.package
        - Roundabout.java [an interface]
      - module-info.java
    + kotlin
      + some.package.impl
        - RoundaboutImpl.kt [implementing the interface]
</code>```

module-info.java is:

```<code>module some.package {
  requires kotlin.stdlib;
  exports some.package;
}
</code>```

and build.gradle is:

```<code>buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'some.package'
version '1.0-PRE_ALPHA'

apply plugin: 'java-library'
apply plugin: 'kotlin'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

sourceCompatibility = 9

compileJava {
    dependsOn(':compileKotlin')
    doFirst {
        options.compilerArgs = [
                '--module-path', classpath.asPath,
        ]
        classpath = files()
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: "$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
</code>```

Notice that I had to specify a module path on the java compile task, or the compilation fails with:

error: module not found: kotlin.stdlib
  requires kotlin.stdlib;

Anyway, now this build fails with this error, and I can't figure out how to solve it:

error: package some.package.impl does not exist

import some.package.impl.RoundaboutImpl;

error: cannot find symbol

return new RoundaboutImpl<>(queueSize, parallelism, worker, threadPool);

I think that the Kotlin part of the compilation is going ok, then the java part fails because it doesn't "see" the kotlin side, so to speak.

I think I should tell it somehow to to load the already compiled kotlin classes in the classpath; but (first) how do I do this in gradle? and (second) is it even possible? I think you can't mix module path and class path in Java 9.

How can I solve this? I think it is a pretty common situation, as every java9-style module will be a mixed-language module (because of module-info.java), so I think I'm missing something really basic here.

Thanks in advance!

答:
On gradle 7.4 with kotlin DSL, I need to:

move the module-info.java to src/main/java

create any java file inside each package to export under src/main/java, at least empty package-info.java

In build.gradle.kts:

```<code>val compileKotlin: KotlinCompile by tasks
val compileJava: JavaCompile by tasks
compileKotlin.destinationDirectory.set(compileJava.destinationDirectory)
</code>```

Also discussed here:
https://github.com/gradle/gradle/issues/17271

Body:
I'm fairly new to Gradle (and Java 9, to be honest), and I'm trying to use Gradle to build a simple library project that is a mix of Java 9 and Kotlin. More in detail, there is an interface in Java and an implementation in Kotlin; I'd do everything in Kotlin, but the modules-info.java is java anyway, so I decided to do things this way.

I'm building on IntelliJ Idea, with the 1.2.0 kotlin plugin and gradle 4.3.1 defined externally.

Filesystem schema is:

+ src
  + main
    + java
      + some.package
        - Roundabout.java [an interface]
      - module-info.java
    + kotlin
      + some.package.impl
        - RoundaboutImpl.kt [implementing the interface]

module-info.java is:

module some.package {
  requires kotlin.stdlib;
  exports some.package;
}

and build.gradle is:

buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'some.package'
version '1.0-PRE_ALPHA'

apply plugin: 'java-library'
apply plugin: 'kotlin'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

sourceCompatibility = 9

compileJava {
    dependsOn(':compileKotlin')
    doFirst {
        options.compilerArgs = [
                '--module-path', classpath.asPath,
        ]
        classpath = files()
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: "$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Notice that I had to specify a module path on the java compile task, or the compilation fails with:

error: module not found: kotlin.stdlib
  requires kotlin.stdlib;

Anyway, now this build fails with this error, and I can't figure out how to solve it:

error: package some.package.impl does not exist

import some.package.impl.RoundaboutImpl;

error: cannot find symbol

return new RoundaboutImpl<>(queueSize, parallelism, worker, threadPool);

I think that the Kotlin part of the compilation is going ok, then the java part fails because it doesn't "see" the kotlin side, so to speak.

I think I should tell it somehow to to load the already compiled kotlin classes in the classpath; but (first) how do I do this in gradle? and (second) is it even possible? I think you can't mix module path and class path in Java 9.

How can I solve this? I think it is a pretty common situation, as every java9-style module will be a mixed-language module (because of module-info.java), so I think I'm missing something really basic here.

Thanks in advance!

Body:
On gradle 7.4 with kotlin DSL, I need to:

move the module-info.java to src/main/java

create any java file inside each package to export under src/main/java, at least empty package-info.java

In build.gradle.kts:

val compileKotlin: KotlinCompile by tasks
val compileJava: JavaCompile by tasks
compileKotlin.destinationDirectory.set(compileJava.destinationDirectory)

Also discussed here:
https://github.com/gradle/gradle/issues/17271


问:
How to convert this nested loop to numpy broadcast?
I want to rearrange my data (two even-length 1d arrays):

cs = [w x y z]
rs = [a b c d e f]
```
<p>to make a result like this:</p>
<pre class="lang-py prettyprint-override"><code>[[a b w x]
 [c d w x]
 [e f w x]
 [a b y z]
 [c d y z]
 [e f y z]]
</code>```

This is what I have tried (it works):

ls = []
for c in range(0,len(cs),2):
  for r in range(0,len(rs),2):
    item = [rs[r], rs[r+1], cs[c], cs[c+1]]
    ls.append(item)
```

But I want to get the same result using reshaping/broadcasting or other numpy functions.
What is the idiomatic way to do this task in numpy?

答:
An alternative to using tile/repeat, is to generate repeated row indices.

Make the two arrays - reshaped as they will be combined:

```<code>In [106]: rs=np.reshape(list('abcdef'),(3,2))
In [107]: cs=np.reshape(list('wxyz'),(2,2))
In [108]: rs
Out[108]:
array([['a', 'b'],
       ['c', 'd'],
       ['e', 'f']], dtype='<U1')
In [109]: cs
Out[109]:
array([['w', 'x'],
       ['y', 'z']], dtype='<U1')
</code>```

Make 'meshgrid' like indices (itertools.product could also be used)

```<code>In [110]: IJ = np.indices((3,2))
In [111]: IJ
Out[111]:
array([[[0, 0],
        [1, 1],
        [2, 2]],

       [[0, 1],
        [0, 1],
        [0, 1]]])
</code>```

reshape with order gives two 1d arrays:

```<code>In [112]: I,J=IJ.reshape(2,6,order='F')
In [113]: I,J
Out[113]: (array([0, 1, 2, 0, 1, 2]), array([0, 0, 0, 1, 1, 1]))
</code>```

Then just index the rs and cs and combine them with hstack:

```<code>In [114]: np.hstack((rs[I],cs[J]))
Out[114]:
array([['a', 'b', 'w', 'x'],
       ['c', 'd', 'w', 'x'],
       ['e', 'f', 'w', 'x'],
       ['a', 'b', 'y', 'z'],
       ['c', 'd', 'y', 'z'],
       ['e', 'f', 'y', 'z']], dtype='<U1')
</code>```

edit

Here's another way of looking this - a bit more advanced.  With sliding_window_view we can get a "block" view of that Out[114] result:

```<code>In [130]: np.lib.stride_tricks.sliding_window_view(_114,(3,2))[::3,::2,:,:]
Out[130]:
array([[[['a', 'b'],
         ['c', 'd'],
         ['e', 'f']],

        [['w', 'x'],
         ['w', 'x'],
         ['w', 'x']]],

       [[['a', 'b'],
         ['c', 'd'],
         ['e', 'f']],

        [['y', 'z'],
         ['y', 'z'],
         ['y', 'z']]]], dtype='<U1')
</code>```

With a bit more reverse engineering, I find I can create Out[114] with:

```<code>In [147]: res = np.zeros((6,4),'U1')
In [148]: res1 = np.lib.stride_tricks.sliding_window_view(res,(3,2),writeable=True)[::3,::2,:,:]
In [149]: res1[:,0,:,:] = rs
In [150]: res1[:,1,:,:] = cs[:,None,:]
In [151]: res
Out[151]:
array([['a', 'b', 'w', 'x'],
       ['c', 'd', 'w', 'x'],
       ['e', 'f', 'w', 'x'],
       ['a', 'b', 'y', 'z'],
       ['c', 'd', 'y', 'z'],
       ['e', 'f', 'y', 'z']], dtype='<U1')
</code>```

I can't say that either of these is superior, but they show there are various ways of "vectorizing" this kind of array layout.

Body:
I want to rearrange my data (two even-length 1d arrays):

cs = [w x y z]
rs = [a b c d e f]

to make a result like this:

[[a b w x]
 [c d w x]
 [e f w x]
 [a b y z]
 [c d y z]
 [e f y z]]

This is what I have tried (it works):

ls = []
for c in range(0,len(cs),2):
  for r in range(0,len(rs),2):
    item = [rs[r], rs[r+1], cs[c], cs[c+1]]
    ls.append(item)

But I want to get the same result using reshaping/broadcasting or other numpy functions.
What is the idiomatic way to do this task in numpy?

Body:
An alternative to using tile/repeat, is to generate repeated row indices.

Make the two arrays - reshaped as they will be combined:

In [106]: rs=np.reshape(list('abcdef'),(3,2))
In [107]: cs=np.reshape(list('wxyz'),(2,2))
In [108]: rs
Out[108]:
array([['a', 'b'],
       ['c', 'd'],
       ['e', 'f']], dtype='<U1')
In [109]: cs
Out[109]:
array([['w', 'x'],
       ['y', 'z']], dtype='<U1')

Make 'meshgrid' like indices (itertools.product could also be used)

In [110]: IJ = np.indices((3,2))
In [111]: IJ
Out[111]:
array([[[0, 0],
        [1, 1],
        [2, 2]],

       [[0, 1],
        [0, 1],
        [0, 1]]])

reshape with order gives two 1d arrays:

In [112]: I,J=IJ.reshape(2,6,order='F')
In [113]: I,J
Out[113]: (array([0, 1, 2, 0, 1, 2]), array([0, 0, 0, 1, 1, 1]))

Then just index the rs and cs and combine them with hstack:

In [114]: np.hstack((rs[I],cs[J]))
Out[114]:
array([['a', 'b', 'w', 'x'],
       ['c', 'd', 'w', 'x'],
       ['e', 'f', 'w', 'x'],
       ['a', 'b', 'y', 'z'],
       ['c', 'd', 'y', 'z'],
       ['e', 'f', 'y', 'z']], dtype='<U1')

edit

Here's another way of looking this - a bit more advanced.  With sliding_window_view we can get a "block" view of that Out[114] result:

In [130]: np.lib.stride_tricks.sliding_window_view(_114,(3,2))[::3,::2,:,:]
Out[130]:
array([[[['a', 'b'],
         ['c', 'd'],
         ['e', 'f']],

        [['w', 'x'],
         ['w', 'x'],
         ['w', 'x']]],

       [[['a', 'b'],
         ['c', 'd'],
         ['e', 'f']],

        [['y', 'z'],
         ['y', 'z'],
         ['y', 'z']]]], dtype='<U1')

With a bit more reverse engineering, I find I can create Out[114] with:

In [147]: res = np.zeros((6,4),'U1')
In [148]: res1 = np.lib.stride_tricks.sliding_window_view(res,(3,2),writeable=True)[::3,::2,:,:]
In [149]: res1[:,0,:,:] = rs
In [150]: res1[:,1,:,:] = cs[:,None,:]
In [151]: res
Out[151]:
array([['a', 'b', 'w', 'x'],
       ['c', 'd', 'w', 'x'],
       ['e', 'f', 'w', 'x'],
       ['a', 'b', 'y', 'z'],
       ['c', 'd', 'y', 'z'],
       ['e', 'f', 'y', 'z']], dtype='<U1')

I can't say that either of these is superior, but they show there are various ways of "vectorizing" this kind of array layout.


问:
Python: concat rows of two dataframes where not all columns are the same
I have two dataframes:

EDIT:

```<code>df1 = pd.DataFrame(index = [0,1,2], columns=['timestamp', 'order_id', 'account_id', 'USD', 'CAD'])
df1['timestamp']=['2022-01-01','2022-01-02','2022-01-03']
df1['account_id']=['usdcad','usdcad','usdcad']
df1['order_id']=['11233123','12313213','12341242']
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
    timestamp   account_id order_id  USD CAD
0   2022-01-01  usdcad     11233123  1   4
1   2022-01-02  usdcad     12313213  2   5
2   2022-01-03  usdcad     12341242  3   6

df2 = pd.DataFrame(index = [0,1], columns = ['timestamp','account_id', 'currency','balance'])
df2['timestamp']=['2021-12-21','2021-12-21']
df2['account_id']=['usdcad','usdcad']
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
    timestamp  account_id currency  balance
0   2021-12-21 usdcad     USD       2
1   2021-12-21 usdcad     CAD       3
</code>```

I would like to add a row to df1 at index 0, and fill that row with the balance of df2 based on currency. So the final df should look like this:

```<code>df:
    timestamp   account_id order_id  USD CAD
0   0           0          0         2   3
1   2022-01-01  usdcad     11233123  1   4
2   2022-01-02  usdcad     12313213  2   5
3   2022-01-03  usdcad     12341242  3   6
</code>```

How can I do this in a pythonic way? Thank you

答:
Set the index of df2 to currency then transpose the index to columns, then append this dataframe with df1

```<code>df_out = df2.set_index('currency').T.append(df1, ignore_index=True).fillna(0)
</code>```

```<code>print(df_out)

   USD  CAD  order_id
0    2    3         0
1    1    4  11233123
2    2    5  12313213
3    3    6  12341242
</code>```

Body:
I have two dataframes:

EDIT:

df1 = pd.DataFrame(index = [0,1,2], columns=['timestamp', 'order_id', 'account_id', 'USD', 'CAD'])
df1['timestamp']=['2022-01-01','2022-01-02','2022-01-03']
df1['account_id']=['usdcad','usdcad','usdcad']
df1['order_id']=['11233123','12313213','12341242']
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
    timestamp   account_id order_id  USD CAD
0   2022-01-01  usdcad     11233123  1   4
1   2022-01-02  usdcad     12313213  2   5
2   2022-01-03  usdcad     12341242  3   6

df2 = pd.DataFrame(index = [0,1], columns = ['timestamp','account_id', 'currency','balance'])
df2['timestamp']=['2021-12-21','2021-12-21']
df2['account_id']=['usdcad','usdcad']
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
    timestamp  account_id currency  balance
0   2021-12-21 usdcad     USD       2
1   2021-12-21 usdcad     CAD       3

I would like to add a row to df1 at index 0, and fill that row with the balance of df2 based on currency. So the final df should look like this:

df:
    timestamp   account_id order_id  USD CAD
0   0           0          0         2   3
1   2022-01-01  usdcad     11233123  1   4
2   2022-01-02  usdcad     12313213  2   5
3   2022-01-03  usdcad     12341242  3   6

How can I do this in a pythonic way? Thank you

Body:
Set the index of df2 to currency then transpose the index to columns, then append this dataframe with df1

df_out = df2.set_index('currency').T.append(df1, ignore_index=True).fillna(0)

print(df_out)

   USD  CAD  order_id
0    2    3         0
1    1    4  11233123
2    2    5  12313213
3    3    6  12341242


问:
How to concatenate more sql queries to get one table?
I have 4 tables that I have used following queries to get data,

```<code>query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 : select * from userdetails2.AmountTable;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,TotalInvested from userdetails2.TotalInvestmentsTable group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,TotalExpenses from userdetails2.TotalExpensesTable group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
</code>```

Now I need to get another table by combining all these queries as follows. How should I get that by concatenating all these queries?

```<code>UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0
</code>```

Here TotalBalance column need to get from TotalBalance=TotalAmount+Totalnvested -TotalExpenses.Is this possible to get using one query?

Update:

If the total expenses and total investments are more than one value we need to get sum of each user to the total investements. Then how we can get that one?

Example:

```<code>Username    Totalnvested
    John         45000
    Micheal      45000
    Ann          45000
    John         21000
    Micheal       5000

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
Ann            2345
John            5478
</code>```

答:
You can try to use JOIN and OUTER JOIN to get your expected result.

OUTER JOIN need to base on userdetails1.UserTable because some people might not have Investments or Expenses in those tables, then use COALESCE function to let NULL value be 0

Query #1

```<code>SELECT t2.UserID,
       t1.Username,
       t2.TotalAmountResetDate,
       t2.TotalAmount,
       COALESCE(Totalnvested,0) Totalnvested,
       COALESCE(TotalExpenses,0) TotalExpenses,
       t2.TotalAmount + COALESCE(Totalnvested,0) - COALESCE(TotalExpenses,0) TotalBalance
FROM userdetails1.UserTable t1
INNER JOIN userdetails2.AmountTable t2
ON t1.UserID = t2.UserID
LEFT JOIN userdetails2.TotalInvestmentsTable investment
ON t1.Username = investment.Username
LEFT JOIN userdetails2.TotalExpensesTable expenses
ON t1.Username = expenses.Username;
</code>```

UserID
TotalAmountResetDate
TotalAmount
Username
Totalnvested
TotalExpenses
TotalBalance

1
1/31/2022
-12
John
45000
2543
42445

2
1/31/2022
345
Micheal
45000
2345
43000

3
1/31/2022
213
Ann
45000
3290
41923

4
1/31/2022
0
Shasha
0
0
0

5
1/31/2022
0
mike
0
0
0

View on DB Fiddle

Body:
I have 4 tables that I have used following queries to get data,

query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 : select * from userdetails2.AmountTable;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,TotalInvested from userdetails2.TotalInvestmentsTable group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,TotalExpenses from userdetails2.TotalExpensesTable group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290

Now I need to get another table by combining all these queries as follows. How should I get that by concatenating all these queries?

UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0

Here TotalBalance column need to get from TotalBalance=TotalAmount+Totalnvested -TotalExpenses.Is this possible to get using one query?

Update:

If the total expenses and total investments are more than one value we need to get sum of each user to the total investements. Then how we can get that one?

Example:

Username    Totalnvested
    John         45000
    Micheal      45000
    Ann          45000
    John         21000
    Micheal       5000

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
Ann            2345
John            5478

Body:
You can try to use JOIN and OUTER JOIN to get your expected result.

OUTER JOIN need to base on userdetails1.UserTable because some people might not have Investments or Expenses in those tables, then use COALESCE function to let NULL value be 0

Query #1

SELECT t2.UserID,
       t1.Username,
       t2.TotalAmountResetDate,
       t2.TotalAmount,
       COALESCE(Totalnvested,0) Totalnvested,
       COALESCE(TotalExpenses,0) TotalExpenses,
       t2.TotalAmount + COALESCE(Totalnvested,0) - COALESCE(TotalExpenses,0) TotalBalance
FROM userdetails1.UserTable t1
INNER JOIN userdetails2.AmountTable t2
ON t1.UserID = t2.UserID
LEFT JOIN userdetails2.TotalInvestmentsTable investment
ON t1.Username = investment.Username
LEFT JOIN userdetails2.TotalExpensesTable expenses
ON t1.Username = expenses.Username;

UserID
TotalAmountResetDate
TotalAmount
Username
Totalnvested
TotalExpenses
TotalBalance

1
1/31/2022
-12
John
45000
2543
42445

2
1/31/2022
345
Micheal
45000
2345
43000

3
1/31/2022
213
Ann
45000
3290
41923

4
1/31/2022
0
Shasha
0
0
0

5
1/31/2022
0
mike
0
0
0

View on DB Fiddle


问:
Angular: Cyclic Dependency
Why is currentdate in this.currentdate.getTime() coming back as undefined?

```<code>newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      xyz: new FormControl()
    },[this.mainservice.getcurrenttime.bind(this)])
})
</code>```
```<code>@Injectable({providedIn: 'root'})
export class MainService {

  constructor(){}

  currentdate: Date = new Date();

  getcurrenttime(control: FormGroup){

    console.log(this.currentdate.getTime())  <~~ Generates Error!!!

    if(condition){
      return {date: true};
    }
    return null;
  }

}
</code>```

答:
set validate without .bind()

```<code>newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      XYZ: new FormControl()
    },[this.mainservice.getcurrenttime()])
})
</code>```

I think you can define that currentDate variable inside the method.

```<code> const currentdate: Date = new Date();
</code>```

and I think you should return something like this.

```<code>getCurrentTime(): ValidatorFn {
    return (formGroup: FormGroup): ValidationErrors | null => {
      const currentDate: Date = new Date();

      const year = formGroup.get('year').value;
      const month = formGroup.get('month').value;
      const day = formGroup.get('day').value;

      const selectedDate = new Date(year, month, day, 0, 0, 0, 0);

      if (selectedDate === currentDate) {
        formGroup.setErrors({ any_error: true }); // on your form group
        return null;
      } else return null;
    };
  }
</code>```

Title: Angular: Cyclic Dependency

Body:
Why is currentdate in this.currentdate.getTime() coming back as undefined?

newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      xyz: new FormControl()
    },[this.mainservice.getcurrenttime.bind(this)])
})

@Injectable({providedIn: 'root'})
export class MainService {

  constructor(){}

  currentdate: Date = new Date();

  getcurrenttime(control: FormGroup){

    console.log(this.currentdate.getTime())  <~~ Generates Error!!!

    if(condition){
      return {date: true};
    }
    return null;
  }

}

Body:
set validate without .bind()

newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      XYZ: new FormControl()
    },[this.mainservice.getcurrenttime()])
})

I think you can define that currentDate variable inside the method.

 const currentdate: Date = new Date();

and I think you should return something like this.

getCurrentTime(): ValidatorFn {
    return (formGroup: FormGroup): ValidationErrors | null => {
      const currentDate: Date = new Date();

      const year = formGroup.get('year').value;
      const month = formGroup.get('month').value;
      const day = formGroup.get('day').value;

      const selectedDate = new Date(year, month, day, 0, 0, 0, 0);

      if (selectedDate === currentDate) {
        formGroup.setErrors({ any_error: true }); // on your form group
        return null;
      } else return null;
    };
  }


问:
jQuery index on each function
I am curious why I need this index

```<code>$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });
</code>```

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

答:
with $(this) you are still in the jquery model where the correct way to get id is .attr("id")

writing $(this)[0] drops you back into the DOM model where its as you wrote.

Title: jQuery index on each function

Body:
I am curious why I need this index

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..


问:
Initialization of an ArrayList in one line
I wanted to create a list of options for testing purposes. At first, I did this:

```<code>ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
</code>```

Then, I refactored the code as follows:

```<code>ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
</code>```

Is there a better way to do this?

答:
Simplest way : you can use this approach to add multiple elements to any type of collection like ArrayList and HashSet</p>
```<code>ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");
</code>```

Body:
I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then, I refactored the code as follows:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?

Body:
Simplest way : you can use this approach to add multiple elements to any type of collection like ArrayList and HashSet

ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");


答:
Statement x = x + 1 and x += 1 are same.
But in JavaScript: String (type) + Integer (type) or  Integer (type) + String (type) will be a String.
i.e.

var a1 = 'b'  + 1; // a1 is 'b1' which is string concatenating
console.log(a1);
var a2 = 'b'  + 1 + 2; // a2 is 'b12' which is string concatenating
console.log(a2);
var a3 =  1 + 2 + 'b' ; // a3 is '3b', here string concatenating after summing 1 and 2
console.log(a3);```

Body:
Is there any difference between bag= bag + n - i +1  and bag += n - i + 1 bcs is shows differnt while running a program below:

var n = 5
for (i = 1; i <= n; i++) {
  var bag = ""

  for (j = 1; j <= n - i + 1; j++) {
    bag += n - j + 1
  }
  console.log(bag)
}
// 2nd way
var n = 5; //
for (let i = 1; i <= n; i++) {
  var string = "";
  for (let j = 1; j <= n - i + 1; j++) {
    string = string + n - j + 1;
  }
  console.log(string);
}

Replit link


问:
Fuzzy `==`, or "almost_equal_to" function for strings?
I want to search for duplicates in my database, but it could be things like

"The smallest thing, and nothing more"
"The Smallest Things, And Nothing More"
"The smallest thing, and nothing more."
"The smallest thing, and nothing"

Is there an easy way to design a fuzzy == function that gives a weight of matching, instead of a binary true/false result?

答:
Ruby ships with a library called did_you_mean it is used to make suggestions for code correction when you make a mistake like "abc".downcsae will ask you "Did you mean downcase?"

This library includes a module called DidYouMean::Levenshtein which has a method called distance. This distance is the number of transformations required for 2 strings to be equal
Example:

```<code>s = "The smallest thing, and nothing more"
x = "The Smallest Things, And Nothing More"

DidYouMean::Levenshtein.distance(s,x)
#=> 6
DidYouMean::Levenshtein.distance(s.downcase,x.downcase)
#=> 1
</code>```

This may be useful in your case although you would need to determine the threshold.

Implementation is also available via the Gem::Text module which you could include in a class if needed e.g.

```<code>class MyClass
  extend Gem::Text

  def self.fuzzy_equal?(x:, y:, threshold:3)
    levenshtein_distance(x,y) <= threshold
  end
end

MyClass.fuzzy_equal?(x: s,y: x)
#=> false
MyClass.fuzzy_equal?(x: s.downcase,y: x.downcase)
#=> true
MyClass.fuzzy_equal?(x: s,y: x, threshold: 10)
#=> true
</code>```

Body:
Ruby ships with a library called did_you_mean it is used to make suggestions for code correction when you make a mistake like "abc".downcsae will ask you "Did you mean downcase?"

This library includes a module called DidYouMean::Levenshtein which has a method called distance. This distance is the number of transformations required for 2 strings to be equal
Example:

s = "The smallest thing, and nothing more"
x = "The Smallest Things, And Nothing More"

DidYouMean::Levenshtein.distance(s,x)
#=> 6
DidYouMean::Levenshtein.distance(s.downcase,x.downcase)
#=> 1

This may be useful in your case although you would need to determine the threshold.

Implementation is also available via the Gem::Text module which you could include in a class if needed e.g.

class MyClass
  extend Gem::Text

  def self.fuzzy_equal?(x:, y:, threshold:3)
    levenshtein_distance(x,y) <= threshold
  end
end

MyClass.fuzzy_equal?(x: s,y: x)
#=> false
MyClass.fuzzy_equal?(x: s.downcase,y: x.downcase)
#=> true
MyClass.fuzzy_equal?(x: s,y: x, threshold: 10)
#=> true


问:
cpan problems with 02packages.details.txt.gz
I'm getting complaints about 02packages.details.txt.gz when I'm trying to install a package with cpan. The error is "Warning: Your /root/.cpan/sources/modules/02packages.details.txt.gz does not contain a Line-Count header.
"

Apparently, according to cpan, this is not a valid zip file, which it isn't. It's just a web page which I'll paste later. I do not use a proxy and I had five mirrors in my configuration. I've deleted one then the next off the list and I'm still getting the same data back. I have deleted the file and attempted to allow cpan to fetch it again. I have fetched the page with curl and I'm seeing a web page and not anything that looks like a gz file.

I have tried "install cpan" from the cpan command line in case I missed an update but that runs into the exact same problem.

Example fetch:

```<code>curl http://noodle.portalus.net/CPAN/modules/02packages.details.txt.gz
</code>```

Result (parts obsfucated)

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function getCookie(c_name) { // Local function for getting a cookie value
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
        c_start=c_start + c_name.length + 1;
        c_end=document.cookie.indexOf(";", c_start);

        if (c_end==-1)
            c_end = document.cookie.length;

        return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}
function setCookie(c_name, value, expiredays) { // Local function for setting a value of a cookie
    var exdate = new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
}
function getHostUri() {
    var loc = document.location;
    return loc.toString();
}
setCookie('XXXXXXXXXXXXXXXXXXXXiw_9289NNNNNNNNJAX666', 'MY.IP.ADDRESS.HERE', 10);
try {
    location.reload(true);
} catch (err1) {
    try {
        location.reload();
    } catch (err2) {
        location.href = getHostUri();
    }
}
</script>
</head>
<body>
<noscript>This site requires JavaScript and Cookies to be enabled. Please change your browser settings or upgrade your browser.</noscript>
</body>
</html>
</code>```

Note that this is the same as the contents as fetched by cpan.

答: It seems like indeed, one after another of my mirrors was stale. Currently using mirrors.namecheap.com and all looking good.</p>

Body:
I'm getting complaints about 02packages.details.txt.gz when I'm trying to install a package with cpan. The error is "Warning: Your /root/.cpan/sources/modules/02packages.details.txt.gz does not contain a Line-Count header.
"

Apparently, according to cpan, this is not a valid zip file, which it isn't. It's just a web page which I'll paste later. I do not use a proxy and I had five mirrors in my configuration. I've deleted one then the next off the list and I'm still getting the same data back. I have deleted the file and attempted to allow cpan to fetch it again. I have fetched the page with curl and I'm seeing a web page and not anything that looks like a gz file.

I have tried "install cpan" from the cpan command line in case I missed an update but that runs into the exact same problem.

Example fetch:

curl http://noodle.portalus.net/CPAN/modules/02packages.details.txt.gz

Result (parts obsfucated)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">

This site requires JavaScript and Cookies to be enabled. Please change your browser settings or upgrade your browser.

Note that this is the same as the contents as fetched by cpan.


问:
How to split with comma in numpy.ndarray without using for and while
I made a grade function that changes the values to P (Pass) and F (Fail), with the code as below:

```<code>def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    print(*grade_index_row,sep=', ')
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)
</code>```

Output :  ['P' 'F' 'P' 'F' 'P'], ['P' 'P' 'P' 'P' 'F'], ['P' 'P' 'F' 'F' 'P']

How if I wanna put a comma on each array contents to be like this [[P,F,P], [P,P,P], [F,P,F], [F,F,P]]

答:
Here's one way:

```<code>def grade(input_array):
    grade_index_rows = np.where(input_array>= 70, "P", "F")
    print(*[f"[{','.join(row)}]" for row in grade_index_rows], sep=', ')
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)
</code>```

Result:

```<code>[P,F,P,F,P], [P,P,P,P,F], [P,P,F,F,P]
</code>```

What you're getting from your example appears to be due to how Numpy chooses to represent a numpy.ndarray as a string.  I've never noticed that it produces that kinda strange formatting.  This new version of the code takes over the formatting of these arrays so that they can be formatted however you want.

Body:
I made a grade function that changes the values to P (Pass) and F (Fail), with the code as below:

def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    print(*grade_index_row,sep=', ')
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

Output :  ['P' 'F' 'P' 'F' 'P'], ['P' 'P' 'P' 'P' 'F'], ['P' 'P' 'F' 'F' 'P']

How if I wanna put a comma on each array contents to be like this [[P,F,P], [P,P,P], [F,P,F], [F,F,P]]

Body:
Here's one way:

def grade(input_array):
    grade_index_rows = np.where(input_array>= 70, "P", "F")
    print(*[f"[{','.join(row)}]" for row in grade_index_rows], sep=', ')
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

Result:

[P,F,P,F,P], [P,P,P,P,F], [P,P,F,F,P]

What you're getting from your example appears to be due to how Numpy chooses to represent a numpy.ndarray as a string.  I've never noticed that it produces that kinda strange formatting.  This new version of the code takes over the formatting of these arrays so that they can be formatted however you want.


答:
You should use np.array2string with a seperator in print.

-This below implementation will return output in string type.

```<code>def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    val = np.array2string(grade_index_row, separator=', ')
    print(type(val))
    print(val)
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)
</code>```

output:

<class 'str'>

[['P', 'F', 'P', 'F', 'P'],  ['P', 'P', 'P', 'P', 'F'], ['P', 'P',
'F', 'F', 'P']]

-If you want result in List format then use this:

```<code>def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    val = np.array2string(grade_index_row, separator=', ')
    val = eval(val)
    print(type(val))
    print(val)
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)
</code>```

Output:

<class 'list'>

[['P', 'F', 'P', 'F', 'P'], ['P', 'P', 'P', 'P', 'F'],['P', 'P', 'F', 'F', 'P']]

Title: How to split with comma in numpy.ndarray without using for and while

Body:
You should use np.array2string with a seperator in print.

-This below implementation will return output in string type.

def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    val = np.array2string(grade_index_row, separator=', ')
    print(type(val))
    print(val)
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

output:

<class 'str'>

[['P', 'F', 'P', 'F', 'P'],  ['P', 'P', 'P', 'P', 'F'], ['P', 'P',
'F', 'F', 'P']]

-If you want result in List format then use this:

def grade(input_array):
    grade_index_row = np.where(input_array>= 70,"P","F")
    val = np.array2string(grade_index_row, separator=', ')
    val = eval(val)
    print(type(val))
    print(val)
    return

input_array = np.array([[80,50,80,60,70],
                   [100,90,80,70,50],
                   [70,70,60,50,85]])
grade(input_array)

Output:

<class 'list'>

[['P', 'F', 'P', 'F', 'P'], ['P', 'P', 'P', 'P', 'F'],['P', 'P', 'F', 'F', 'P']]


问:
Macro definition conflict
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

```<code>test1.h
#define TEST 123
test2.h
#define TEST 456
</code>```

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

答:
You can use the #ifdef pre-processor directive to determine if TEST is defined already for your particular case. Or just #undef it first.

```<code>#undef TEST
#define TEST 123
</code>```

Put that in your header file where you want TEST to be 123 and not 456. Also, this needs to be before test1.h.

Title: Macro definition conflict

Body:
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

test1.h
#define TEST 123
test2.h
#define TEST 456

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

Body:
You can use the #ifdef pre-processor directive to determine if TEST is defined already for your particular case. Or just #undef it first.

#undef TEST
#define TEST 123

Put that in your header file where you want TEST to be 123 and not 456. Also, this needs to be before test1.h.


问:
[JavaScript]Add elements to a global array in a function and keep them

window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);```

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

答:
The code is right, you're getting an error because the browser is running func1() before the list array is rendered in. Just move it before window.onload() and you're good.

const list = [];

window.onload = function(){
    func1();
};

function func1(){
  for(let i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);```

Body:
window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?


问:
How to obtain the Stripe chargeID
So I am making a payment on the Stripe test environment through using their API, I use the below to create a payment.

```<code>const createPayment = await stripe.customers.create
</code>```

when printing createPayment object, there is no chargeID value.

I want to obtain this value so i can make a stripe transfer using the following:

```<code>const transfer = stripe.transfers.create({
                    amount: amountToPay,
                    currency: 'gbp',
                    source_transaction: {{chargeID}},
                    destination: stripeID,
                });
</code>```

I have looked through the Stripe docs and online and I can't seem to find how this is found.
Does anyone know how to find the chargeID anywhere ?

答:
stripe.customers.create is used to create a Customer.

To create a payment, you should create a PaymentIntent instead.

Example

```<code>const paymentIntent = await stripe.paymentIntents.create({
  amount: 2000,
  currency: 'usd',
  confirm: true,
  payment_method: 'pm_card_amex_threeDSecureNotSupported',
});
</code>```

Once the PaymentIntent's status='succeeded', you can use the charge id that can be found in charges.data.

Example

```<code>{
  "id": "pi_...",
  "object": "payment_intent",
  "amount": 2000,
  "currency": "usd",
  "last_payment_error": null,
  "livemode": false,
  "next_action": null,
  "payment_method": "pm_...",
  "status": "succeeded",
  ...
  "charges": {
    "object": "list",
    "data": [
      {
        "id": "ch_...",
        "object": "charge",
        "amount": 2000,
        ...
}
</code>```

Additional resources that may be useful :

https://stripe.com/docs/payments/intents

https://stripe.com/docs/testing

https://stripe.com/docs/payments/accept-a-payment

https://stripe.com/docs/connect/charges-transfers

Title: How to obtain the Stripe chargeID

Body:
So I am making a payment on the Stripe test environment through using their API, I use the below to create a payment.

const createPayment = await stripe.customers.create

when printing createPayment object, there is no chargeID value.

I want to obtain this value so i can make a stripe transfer using the following:

const transfer = stripe.transfers.create({
                    amount: amountToPay,
                    currency: 'gbp',
                    source_transaction: {{chargeID}},
                    destination: stripeID,
                });

I have looked through the Stripe docs and online and I can't seem to find how this is found.
Does anyone know how to find the chargeID anywhere ?

Body:
stripe.customers.create is used to create a Customer.

To create a payment, you should create a PaymentIntent instead.

Example

const paymentIntent = await stripe.paymentIntents.create({
  amount: 2000,
  currency: 'usd',
  confirm: true,
  payment_method: 'pm_card_amex_threeDSecureNotSupported',
});

Once the PaymentIntent's status='succeeded', you can use the charge id that can be found in charges.data.

Example

{
  "id": "pi_...",
  "object": "payment_intent",
  "amount": 2000,
  "currency": "usd",
  "last_payment_error": null,
  "livemode": false,
  "next_action": null,
  "payment_method": "pm_...",
  "status": "succeeded",
  ...
  "charges": {
    "object": "list",
    "data": [
      {
        "id": "ch_...",
        "object": "charge",
        "amount": 2000,
        ...
}

Additional resources that may be useful :

https://stripe.com/docs/payments/intents

https://stripe.com/docs/testing

https://stripe.com/docs/payments/accept-a-payment

https://stripe.com/docs/connect/charges-transfers


问:
Couldn't find Article with 'id'=show
I know this question may be simple and related to other problems but in my case those solutions are not working, so my question is how to deal with this problem?

While I try to show the article I am getting this error:

ActiveRecord::RecordNotFound in ArticlesController#show couldn't find
  article with 'id'=show

I am stucking here

```<code>@article = Article.find(params[:id])
</code>```

Here is my code snippets
My article_controller.rb look like this

```<code>class ArticlesController < ApplicationController
  def index
    @articles= Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article= current_user.articles.build
  end

  def create
    @article=current_user.articles.build(@article_params)
    if @article.save
      redirect_to articles_path
    else
      render 'new'
    end
  end

  def edit
    @article=Article.new(article_params)
  end
end
</code>```

my index.html.erb looks like this

```<code><h2>welcome index</h2>

<ul>
  <% @articles.each do |article| %>
    <%= article.titile %>
    <%= article.body %>
  <% end %>
</ul>
</code>```

my show.html.erb look like this

```<code><h2><%= @article.title %></h2>
<p><%= @article.body %></p>
</code>```

my Routes look like this

```<code>Rails.application.routes.draw do
  devise_for :users

  root 'articles#index'

  resources :articles

  get 'articles/show'
end
</code>```

答:
Rails.application.routes.draw do

root 'articles#index'

get 'articles/show/:id', to: 'articles#show'

end

Title: Couldn't find Article with 'id'=show

Body:
I know this question may be simple and related to other problems but in my case those solutions are not working, so my question is how to deal with this problem?

While I try to show the article I am getting this error:

ActiveRecord::RecordNotFound in ArticlesController#show couldn't find
  article with 'id'=show

I am stucking here

@article = Article.find(params[:id])

Here is my code snippets
My article_controller.rb look like this

class ArticlesController < ApplicationController
  def index
    @articles= Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article= current_user.articles.build
  end

  def create
    @article=current_user.articles.build(@article_params)
    if @article.save
      redirect_to articles_path
    else
      render 'new'
    end
  end

  def edit
    @article=Article.new(article_params)
  end
end

my index.html.erb looks like this

welcome index

  <% @articles.each do |article| %>
    <%= article.titile %>
    <%= article.body %>
  <% end %>

my show.html.erb look like this

<%= @article.title %>

<%= @article.body %>

my Routes look like this

Rails.application.routes.draw do
  devise_for :users

  root 'articles#index'

  resources :articles

  get 'articles/show'
end


问:
How can i get information in Network Payload using C#?
I receive information from another page from a payment processor. On the admin panel I can assign the page where it will end its process and redirect there. When I check this final page I use as a response page.

I can see all important information when I enter in Chrome Devtools --> Network --> Payload

How can I get this info in CodeBehind on Page_load?

I tried using request.form.allkeys but didn't return anything.

Here is an example of what I see:

答:
I found what was the error.

If you are using FriendlyUrls on ASP.NET the url you set on your payment processor must not have the ".aspx" extension for the page where is it supposed to receive the info.

After i made the correction i could see the parameters using:

Request.Form["name_of_parameter"]


问:
Maintaining message integrity
I have a message that I am passing to myself which will be subject to man-in-the-middle attacks.  Because of that, I am concerned about the integrity of the message being maintained between the time I send it, and the time that I receive it back.

It should be assumed that once I send the message to myself, no information about the message sent will be available to me in the future.  The message is completely self-contained.

To that end, I know that should hash the message contents and compare the hashes before I send the message, and after I send the message, if they differ, then the message has been tampered with.

Of course, if the man-in-the-middle knows that the hash is really just the hash of the message contents, as-is, then because the message is self-contained, he can just create new contents and apply the same hash algorithm to the contents.

The question is, to what lengths should I go to randomize the message contents when generating the hash?  When does it reach the point of diminishing returns?

In this scenario, I have a set of key/value pairs.  To that end, the steps that I know I HAVE to take are:

Add a salt to the message.  The salt is a secret to the rest of the world.  It gets attached to the contents of the message before hashing.

Order the key/value pairs in a consistent manner before generating the hash.

While not directly relevant, a timestamp is going to be added to the contents of each message before hashing, to prevent replay attacks.

These are the optional steps that I am considering:

Transforming the keys before I order them.  I've considered reversing them, then ordering by count/key.

Playing with the separators that separate key/value pairs (both for the separator for the key/value and the separator for the pair).

NOTE

Message privacy is not a requirement here, so I am not looking for encryption.  The values must be transmitted in plain-text.

Finally, what hashing algorithms should I avoid?

Specifics

I have an ASP.NET MVC site which I have a controller which handles input validation and persistence.

If (based on a heuristic, it's not important which) the input is determined to be an automated spam attempt, a model of IDictionary<string, string> is created with the input values and a ViewResult is sent to a general CAPTCHA page.

In that view, in the form that contains the CAPTCHA control, the contents of the IDictionary<string, string> will be written out in hidden input fields, and the action of the form will be the same action that the contents were originally posted to.  This way, MVC can pick up the values when the form is resubmitted.

It's because of this I can't encrypt the key/value pairs (or maybe I can and should, tell me why and how!).

Of course, I need to add one more value, which contains the hashed message contents.  If that value is there, then the controller will check to see that the message integrity is maintained, and allow the input to be persisted if it has.

Solution

I've opted to go with the SignedCms class in the System.Security.Cyrptography.Pkcs namespace, which represents the signging and verifying of CMS/PKCS #7 messages.

To elaborate, I've created a self-issued certificate with MAKECERT.EXE and then in my code, I use the example here to digitally sign the data:

http://blogs.msdn.com/shawnfa/archive/2006/02/27/539990.aspx

Now, it should be a matter of keeping the password on the exported private key secure, as well as security on the server, which makes it less about programming.

I'll have to add an extra key for the timestamp for replay attacks, but that won't be too hard.

The answer goes to Kalium, not for his initial post, but for his follow up comments which pointed the way to digital signatures, and eventually my discovery of how to utilize them in .NET.

Thanks to everyone who contributed.

答:
The most straight forward approach to allow your application to verify that its own messages have not been tampered with would be to use a keyed hash message authentication code. The message is sent in the clear, but it also includes a hash to prevent tampering. The hash depends on both the message contents and a secret key. The man in the middle can't forge a hash on an altered message without knowing the key. Since your application both creates and verifies the messages, it never needs to disclose the secret key.

I would particularly recommend the implementation described in RFC-2104 http://www.ietf.org/rfc/rfc2104.txt as it has been carefully thought through to avoid most of the likely pitfalls.

If the messages must also be verified for authenticity by untrusted parties, then you should use a digital signature scheme instead.

There is likely some support for both in the .Net libraries. Miles helpfully provided (as a comment) a link to the MSDN web page for the .Net library functions implementing a keyed HMACs using the SHA1 hash: http://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha1.aspx.

OwnerDisplayName: casperOne

ContentLicense: CC BY-SA 2.5

Title: Maintaining message integrity

LastEditorDisplayName: casperOne

OwnerDisplayName: Stephen C. Steel

LastEditorDisplayName: Jonathan Leffler


问:
Detecting CSS capabilities with Javascript
Is it possible to detect CSS support by using Javascript?

For example, is it possible to detect if the browser supports attribute selectors like this?

```<code>input[type='text'] { }
</code>```

答:
```<code>document.querySelectorAll("input[type='text']")
</code>```

But that fails for older browsers, naturally.

Other than that, you could just use the style property to check if a certain CSS property has been applied or not.

```<code>input[type='text'] {
  background-repeat: no-repeat; /* or any other irrelevant, non-default value */
}
</code>```

and

```<code>if (myInputElem.style.backgroundRepeat == "no-repeat") {
  // selector is supported
}
</code>```

Body:
Is it possible to detect CSS support by using Javascript?

For example, is it possible to detect if the browser supports attribute selectors like this?

input[type='text'] { }

Body:
document.querySelectorAll("input[type='text']")

But that fails for older browsers, naturally.

Other than that, you could just use the style property to check if a certain CSS property has been applied or not.

input[type='text'] {
  background-repeat: no-repeat; /* or any other irrelevant, non-default value */
}

and

if (myInputElem.style.backgroundRepeat == "no-repeat") {
  // selector is supported
}


问:
constantly checking if a condition is true or false
I'm new to python and programming in general and I am currently taking a course on Udemy. One of the projects is to create a pick your own adventure game. I've been doing pretty
well until I came across something that has been picking at me. I wanted to display text depending on whether or not you have died by changing the condition of death from False to True. I know I can just add you died after the if/else statement with a print function but I wanted to make it a bit more challenging. Here's an example.

```<code>death = False
if death == True:
  print("\nYou died")

choice_1 = input("left or right:\n")
if choice_1 == "left":
  death = False
  print("*The next piece of dialogue*")
else:
  death = True
  print("*The next piece of dialogue*")
</code>```

It would then print "you died" after the next piece of dialogue if the death changed to True.

答:
If all you're looking to do is constantly run the choices until death = True you just need to use a while loop before your if statements. This will constantly run the input until the value of death changes to True.

def player_died()
   print('Do whatever you want to happen when player dies in this function')

death = False
while death == False:
    choice_1 = input("left or right:\n")

    if choice_1 == 'left':
        death = False
        print("*The next piece of dialogue*")

    elif choice_1 == 'right':
        death = True
        print("\nYou died")
        #This will break the while loop
        player_died()
```

Whatever additional things you wish to do after death = True, I would make a new function for that situation like def player_died(), and call that function under the 'You died' print. The while loop will end, and you will go to the next function.

If you wish to return back to that loop, AFTER you do something else, then change player_died() call to death = player_died() - and have the function return False, and remove the death=True above it.

This will allow you to execute whatever additional actions you want to do in the function, and when all of that is complete it will return back to the while loop and start over.

Body:
I'm new to python and programming in general and I am currently taking a course on Udemy. One of the projects is to create a pick your own adventure game. I've been doing pretty
well until I came across something that has been picking at me. I wanted to display text depending on whether or not you have died by changing the condition of death from False to True. I know I can just add you died after the if/else statement with a print function but I wanted to make it a bit more challenging. Here's an example.

death = False
if death == True:
  print("\nYou died")

choice_1 = input("left or right:\n")
if choice_1 == "left":
  death = False
  print("*The next piece of dialogue*")
else:
  death = True
  print("*The next piece of dialogue*")

It would then print "you died" after the next piece of dialogue if the death changed to True.

Body:
If all you're looking to do is constantly run the choices until death = True you just need to use a while loop before your if statements. This will constantly run the input until the value of death changes to True.

def player_died()
   print('Do whatever you want to happen when player dies in this function')

death = False
while death == False:
    choice_1 = input("left or right:\n")

    if choice_1 == 'left':
        death = False
        print("*The next piece of dialogue*")

    elif choice_1 == 'right':
        death = True
        print("\nYou died")
        #This will break the while loop
        player_died()

Whatever additional things you wish to do after death = True, I would make a new function for that situation like def player_died(), and call that function under the 'You died' print. The while loop will end, and you will go to the next function.

If you wish to return back to that loop, AFTER you do something else, then change player_died() call to death = player_died() - and have the function return False, and remove the death=True above it.

This will allow you to execute whatever additional actions you want to do in the function, and when all of that is complete it will return back to the while loop and start over.


问:
Mocking an rvalue qualified method with gmock
Is there a way I can mock an rvalue qualified method with gmock? Something like the following?

```<code>class Something {
public:
  virtual void test() &&;
};

class MockSomething : public Something {
public:
  MOCK_METHOD(void, test, (), (&&, override));
};
</code>```

Trying this seems to give me a bunch of weird compiler errors that complain about, what it looks like, are preprocessed tokens. I can also not figure out how to make the older numbered mocking macros (eg. MOCK_METHOD1, MOCK_METHOD2, etc) work...

Thanks!

答:
ref(...) - Marks the method with the reference qualification specified. Required if overriding a method that has reference qualifications. Eg ref(&) or ref(&&).

Source: https://google.github.io/googletest/gmock_cook_book.html

Body:
Is there a way I can mock an rvalue qualified method with gmock? Something like the following?

class Something {
public:
  virtual void test() &&;
};

class MockSomething : public Something {
public:
  MOCK_METHOD(void, test, (), (&&, override));
};

Trying this seems to give me a bunch of weird compiler errors that complain about, what it looks like, are preprocessed tokens. I can also not figure out how to make the older numbered mocking macros (eg. MOCK_METHOD1, MOCK_METHOD2, etc) work...

Thanks!