问:
Making divs appear side by side while using a loop in wordpress
I want to mak 2 divs appear in one row and then display following two in the next row and so on. I am using a php while loop to render the divs on the screen so they are appearing one below the other. How do I make it display them side by side?

Right now it looks like this:
screenshot of the way it is displaying

my code looks like this at the moment:

```<code><?php $decadesFrontPage = new WP_Query(array(
          'posts_per_page' => 2,
          'post_type' => 'Decades',
      ));

      while($decadesFrontPage->have_posts()){
        $decadesFrontPage -> the_post(); ?>

        <div class="row">
          <div class="col-sm-6">
            <div class="card">
              <div class="card-body">
                <h5 class="card-title"><?php the_title() ?></h5>
                <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                <a href="#" class="btn btn-primary">Go somewhere</a>
              </div>
            </div>
          </div>

        </div>

      <?php } ?>
</code>```

答:
Use CSS grid it's very easy to make that kind of layouts with it!
https://www.w3schools.com/css/css_grid.asp

.grid-container {
  display: grid;
  grid-column-gap: 50px;
  grid-template-columns: 1fr 1fr;
}
.grid-item {
  background: blue;
  color: #fff;
  font-weight:bold;
  padding:20px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">9</div>
</div></code>```

Body:
I want to mak 2 divs appear in one row and then display following two in the next row and so on. I am using a php while loop to render the divs on the screen so they are appearing one below the other. How do I make it display them side by side?

Right now it looks like this:
screenshot of the way it is displaying

my code looks like this at the moment:

<?php $decadesFrontPage = new WP_Query(array(
          'posts_per_page' => 2,
          'post_type' => 'Decades',
      ));

      while($decadesFrontPage->have_posts()){
        $decadesFrontPage -> the_post(); ?>

<?php the_title() ?>

With supporting text below as a natural lead-in to additional content.

                Go somewhere

      <?php } ?>

Body:
Use CSS grid it's very easy to make that kind of layouts with it!
https://www.w3schools.com/css/css_grid.asp

.grid-container {
  display: grid;
  grid-column-gap: 50px;
  grid-template-columns: 1fr 1fr;
}
.grid-item {
  background: blue;
  color: #fff;
  font-weight:bold;
  padding:20px
}

<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">9</div>
</div>


来源: stackexchange

问:
Print even number using for loop without using if condition
I have an easy drill to print all the even numbers between 1-1000.

I want to set the condition in the line of the loop and not below it..

This is what I've tried:

```<code>   for (let i = 1; i <= 1000 && i % 2 == 0 ; i++) {
        document.write(i + " ");
// I dont want the condition here !!!

    }
</code>```

I searched the forum and tried this too:

```<code>  for (let i = 1;( (i <= 1000) && (i % 2 == 0) ); i++) {
        document.write(i + " ");
    }
</code>```

It looks like the same code I think, but there is nothing in the console when I run the code..

答:
The test condition in the loop header determines whether the loop will continue to iterate. Because the first value of i is 1, and 1 is not even, the loop body is never run.

The whole test expression must be true (well, "truthy") for the loop not to stop. Therefore, you cannot place the evenness test in the loop header. It must be a separate test inside the loop body.

Now, you could do this without a test by starting the iteration at 2 instead of 1 and adding 2 on each iteration. Then you don't need to test for evenness at all:

```<code>for (let i = 2; i <= 1000; i += 2)
  document.write(i);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an easy drill to print all the even numbers between 1-1000.

I want to set the condition in the line of the loop and not below it..

This is what I've tried:

   for (let i = 1; i <= 1000 && i % 2 == 0 ; i++) {
        document.write(i + " ");
// I dont want the condition here !!!

    }

I searched the forum and tried this too:

  for (let i = 1;( (i <= 1000) && (i % 2 == 0) ); i++) {
        document.write(i + " ");
    }

It looks like the same code I think, but there is nothing in the console when I run the code..

Body:
The test condition in the loop header determines whether the loop will continue to iterate. Because the first value of i is 1, and 1 is not even, the loop body is never run.

The whole test expression must be true (well, "truthy") for the loop not to stop. Therefore, you cannot place the evenness test in the loop header. It must be a separate test inside the loop body.

Now, you could do this without a test by starting the iteration at 2 instead of 1 and adding 2 on each iteration. Then you don't need to test for evenness at all:

for (let i = 2; i <= 1000; i += 2)
  document.write(i);


问:
Finding sum of geometric sequence with modulo 10^9+7 with my program
The problem is given as:
Output the answer of (A^1+A^2+A^3+...+A^K) modulo 1,000,000,007, where 1≤ A, K ≤ 10^9, and A and K must be an integer.

I am trying to write a program to compute the above question. I have tried using the formula for geometric sequence, then applying the modulo on the answer. Since the results must be an integer as well, finding modulo inverse is not required.

Below is the code I have now, its in pascal

Var
a,k,i:longint;
power,sum: int64;
Begin
    Readln(a,k);
    power := 1;
    For i := 1 to k do
    power := ((power mod 1000000007) * a) mod 1000000007;
    sum := a * (power-1) div (a-1);
    Writeln(sum mod 1000000007);
End.
```

This task came from my school, they do not give away their test data to the students. Hence I do not know why or where my program is wrong. I only know that my program outputs the wrong answer for their test data.

答:
If you want to do this without calculating a modular inverse, you can calculate it recursively using:

1+ A + A2 + A3 + ... + Ak

= 1 + (A + A2)(1 + A2 + (A2)2 + ... + (A2)k/2-1)

That's for even k.  For odd k:

1+ A + A2 + A3 + ... + Ak

= (1 + A)(1 + A2 + (A2)2 + ... + (A2)(k-1)/2)

Since k is divided by 2 in each recursive call, the resulting algorithm has O(log k) complexity.  In java:

```<code>static int modSumAtoAk(int A, int k, int mod)
{
    return (modSum1ToAk(A, k, mod) + mod-1) % mod;
}

static int modSum1ToAk(int A, int k, int mod)
{
    long sum;
    if (k < 5) {
        //k is small -- just iterate
        sum = 0;
        long x = 1;
        for (int i=0; i<=k; ++i) {
            sum = (sum+x) % mod;
            x = (x*A) % mod;
        }
        return (int)sum;
    }
    //k is big
    int A2 = (int)( ((long)A)*A % mod );
    if ((k%2)==0) {
        // k even
        sum = modSum1ToAk(A2, (k/2)-1, mod);
        sum = (sum + sum*A) % mod;
        sum = ((sum * A) + 1) % mod;
    } else {
        // k odd
        sum = modSum1ToAk(A2, (k-1)/2, mod);
        sum = (sum + sum*A) % mod;
    }
    return (int)sum;
}
</code>```

Note that I've been very careful to make sure that each product is done in 64 bits, and to reduce by the modulus after each one.

With a little math, the above can be converted to an iterative version that doesn't require any storage:

```<code>static int modSumAtoAk(int A, int k, int mod)
{
    // first, we calculate the sum of all 1... A^k
    // we'll refer to that as SUM1 in comments below

    long fac=1;
    long add=0;

    //INVARIANT: SUM1 = add + fac*(sum 1...A^k)
    //this will remain true as we change k

    while (k > 0) {
        //above INVARIANT is true here, too

        long newmul, newadd;
        if ((k%2)==0) {
            //k is even.  sum 1...A^k = 1+A*(sum 1...A^(k-1))
            newmul = A;
            newadd = 1;
            k-=1;
        } else {
            //k is odd.
            newmul = A+1L;
            newadd = 0;
            A = (int)(((long)A) * A % mod);
            k = (k-1)/2;
        }
        //SUM1 = add + fac * (newadd + newmul*(sum 1...Ak))
        //     = add+fac*newadd + fac*newmul*(sum 1...Ak)

        add = (add+fac*newadd) % mod;
        fac = (fac*newmul) % mod;

        //INVARIANT is restored
    }

    // k == 0
    long sum1 = fac + add;
    return (int)((sum1 + mod -1) % mod);
}
</code>```

Body:
The problem is given as:
Output the answer of (A^1+A^2+A^3+...+A^K) modulo 1,000,000,007, where 1≤ A, K ≤ 10^9, and A and K must be an integer.

I am trying to write a program to compute the above question. I have tried using the formula for geometric sequence, then applying the modulo on the answer. Since the results must be an integer as well, finding modulo inverse is not required.

Below is the code I have now, its in pascal

Var
a,k,i:longint;
power,sum: int64;
Begin
    Readln(a,k);
    power := 1;
    For i := 1 to k do
    power := ((power mod 1000000007) * a) mod 1000000007;
    sum := a * (power-1) div (a-1);
    Writeln(sum mod 1000000007);
End.

This task came from my school, they do not give away their test data to the students. Hence I do not know why or where my program is wrong. I only know that my program outputs the wrong answer for their test data.

Body:
If you want to do this without calculating a modular inverse, you can calculate it recursively using:

1+ A + A2 + A3 + ... + Ak

= 1 + (A + A2)(1 + A2 + (A2)2 + ... + (A2)k/2-1)

That's for even k.  For odd k:

1+ A + A2 + A3 + ... + Ak

= (1 + A)(1 + A2 + (A2)2 + ... + (A2)(k-1)/2)

Since k is divided by 2 in each recursive call, the resulting algorithm has O(log k) complexity.  In java:

static int modSumAtoAk(int A, int k, int mod)
{
    return (modSum1ToAk(A, k, mod) + mod-1) % mod;
}

static int modSum1ToAk(int A, int k, int mod)
{
    long sum;
    if (k < 5) {
        //k is small -- just iterate
        sum = 0;
        long x = 1;
        for (int i=0; i<=k; ++i) {
            sum = (sum+x) % mod;
            x = (x*A) % mod;
        }
        return (int)sum;
    }
    //k is big
    int A2 = (int)( ((long)A)*A % mod );
    if ((k%2)==0) {
        // k even
        sum = modSum1ToAk(A2, (k/2)-1, mod);
        sum = (sum + sum*A) % mod;
        sum = ((sum * A) + 1) % mod;
    } else {
        // k odd
        sum = modSum1ToAk(A2, (k-1)/2, mod);
        sum = (sum + sum*A) % mod;
    }
    return (int)sum;
}

Note that I've been very careful to make sure that each product is done in 64 bits, and to reduce by the modulus after each one.

With a little math, the above can be converted to an iterative version that doesn't require any storage:

static int modSumAtoAk(int A, int k, int mod)
{
    // first, we calculate the sum of all 1... A^k
    // we'll refer to that as SUM1 in comments below

    long fac=1;
    long add=0;

    //INVARIANT: SUM1 = add + fac*(sum 1...A^k)
    //this will remain true as we change k

    while (k > 0) {
        //above INVARIANT is true here, too

        long newmul, newadd;
        if ((k%2)==0) {
            //k is even.  sum 1...A^k = 1+A*(sum 1...A^(k-1))
            newmul = A;
            newadd = 1;
            k-=1;
        } else {
            //k is odd.
            newmul = A+1L;
            newadd = 0;
            A = (int)(((long)A) * A % mod);
            k = (k-1)/2;
        }
        //SUM1 = add + fac * (newadd + newmul*(sum 1...Ak))
        //     = add+fac*newadd + fac*newmul*(sum 1...Ak)

        add = (add+fac*newadd) % mod;
        fac = (fac*newmul) % mod;

        //INVARIANT is restored
    }

    // k == 0
    long sum1 = fac + add;
    return (int)((sum1 + mod -1) % mod);
}


问:
How can I create a class without defining it in JavaScript?
I have a class at server-side like this:

```<code>public class Address
{
    public Address(string countryCode)
    {
        this._CountryCode = countryCode;
    }

    private string _CountryCode = string.Empty;
    public string CountryCode
    {
        get { return _CountryCode; }
        set { _CountryCode = value; }
    }

}
</code>```

and I have a method that called by Ajax methods :

```<code>[AjaxMethod]
public static Address ValidateAddress(Address address)
{
   // Some logic here...
   return address;
}
</code>```

And I want to call this method in client side, but how can I instantiate the Address class in client side? I do not want to define a class named Address in JavaScript file.

```<code><script>

function valaddress(){

  var address = new Address(); // I'm asking here ??
  address.CountryCode = 90;

  // This part is ok, no problem in here :
  var validatedAddress = AddressControlDataHelper.ValidateAddress(address).value;

}

</script>
</code>```

Is there a way to do this? Or do I need to write my Address class in JavaScript?

答:
```<code>var address = {
    CountryCode: "1"
}
</code>```

That should do the trick

```<code><script>
  function valaddress(){

      var address = {
          CountryCode: "90"
      };

      // This part is ok, no problem in here :
      var validatedAddress =
       AddressControlDataHelper.ValidateAddress(address).value;

  }
</script>
</code>```

OwnerDisplayName: ScarletGarden

ContentLicense: CC BY-SA 3.0

Body:
I have a class at server-side like this:

public class Address
{
    public Address(string countryCode)
    {
        this._CountryCode = countryCode;
    }

    private string _CountryCode = string.Empty;
    public string CountryCode
    {
        get { return _CountryCode; }
        set { _CountryCode = value; }
    }

}

and I have a method that called by Ajax methods :

[AjaxMethod]
public static Address ValidateAddress(Address address)
{
   // Some logic here...
   return address;
}

And I want to call this method in client side, but how can I instantiate the Address class in client side? I do not want to define a class named Address in JavaScript file.

Is there a way to do this? Or do I need to write my Address class in JavaScript?

Body:
var address = {
    CountryCode: "1"
}

That should do the trick

<script>
  function valaddress(){

      var address = {
          CountryCode: "90"
      };

      // This part is ok, no problem in here :
      var validatedAddress =
       AddressControlDataHelper.ValidateAddress(address).value;

  }
</script>

OwnerDisplayName: Bob


问:
How to authorize a user belonging to a group that contains hashes
I'm trying to authorize a user depending on his group membership.

Apache is configured as follows:

```<code>AuthLDAPURL "ldap://DOMAIN.COM/DC=FOO,DC=COM?CN?SUB?(objectClass=user)" NONE
AuthLDAPBindDN "CN=..."
AuthLDAPBindPassword "..."
Require ldap-group CN=\#\#SOMETEXT,OU=GSI,OU=DMM,OU=DDSIS,OU=Admin_Exchange,DC=DOMAIN,DC=com
</code>```

The problem comes from the two hashes that appear in the CN.
I tried with and without quotes, with two backslashes and no backslashes, URL encode, but nothing worked.

I always get the following error message.

[Thu Feb 13 18:40:56.728349 2020] [authnz_ldap:debug] [pid 17154]
  mod_authnz_ldap.c(922): [client 10.255.180.148:65050] AH01719:
  auth_ldap authorize: require group
  "CN=##SOMETEXT,OU=GSI,OU=DMM,OU=DDSIS,OU=Admin_Exchange,DC=DOMAIN,DC=com": didn't match with attr Comparison complete [member][34 - Invalid DN
  syntax]

When i remove the hashes, i get a no such object error, that confirms the problem comes from the hashes.

EDIT:

As suggested in the answer, I tried to write the octal representation of the hash character \43 but it gave me the exact same error:

"CN=##SOMETEXT, ...Invalid DN syntax]

So that doesn't seem to change what Apache sends to LDAP

答:
You typically can get around these type of issues with something like:

```<code>CN=\23\23SOMETEXT,OU=GSI,OU=DMM,OU=DDSIS,OU=Admin_Exchange,DC=DOMAIN,DC=com
</code>```

As described in RFC 4514 and Characters to Escape

However, different applications may be trying to parsing these parameters for you and may interfere with the escaping process.

The RIGHT thing to do is rename the group.

The problem you are encountering will persist with other application in the future. Best Practices for LDAP imply all Relative Distinguished Names be "URL Safe" and not require escaping.

Body:
I'm trying to authorize a user depending on his group membership.

Apache is configured as follows:

AuthLDAPURL "ldap://DOMAIN.COM/DC=FOO,DC=COM?CN?SUB?(objectClass=user)" NONE
AuthLDAPBindDN "CN=..."
AuthLDAPBindPassword "..."
Require ldap-group CN=\#\#SOMETEXT,OU=GSI,OU=DMM,OU=DDSIS,OU=Admin_Exchange,DC=DOMAIN,DC=com

The problem comes from the two hashes that appear in the CN.
I tried with and without quotes, with two backslashes and no backslashes, URL encode, but nothing worked.

I always get the following error message.

[Thu Feb 13 18:40:56.728349 2020] [authnz_ldap:debug] [pid 17154]
  mod_authnz_ldap.c(922): [client 10.255.180.148:65050] AH01719:
  auth_ldap authorize: require group
  "CN=##SOMETEXT,OU=GSI,OU=DMM,OU=DDSIS,OU=Admin_Exchange,DC=DOMAIN,DC=com": didn't match with attr Comparison complete [member][34 - Invalid DN
  syntax]

When i remove the hashes, i get a no such object error, that confirms the problem comes from the hashes.

EDIT:

As suggested in the answer, I tried to write the octal representation of the hash character \43 but it gave me the exact same error:

"CN=##SOMETEXT, ...Invalid DN syntax]

So that doesn't seem to change what Apache sends to LDAP

Body:
You typically can get around these type of issues with something like:

CN=\23\23SOMETEXT,OU=GSI,OU=DMM,OU=DDSIS,OU=Admin_Exchange,DC=DOMAIN,DC=com

As described in RFC 4514 and Characters to Escape

However, different applications may be trying to parsing these parameters for you and may interfere with the escaping process.

The RIGHT thing to do is rename the group.

The problem you are encountering will persist with other application in the future. Best Practices for LDAP imply all Relative Distinguished Names be "URL Safe" and not require escaping.


问:
Issue in Passing a 2-D array
I read how to pass 2-D arrays in a function as a parameter and tried to implement the same. There are two problems which I encountered:

1) The first line of the output of the code contains garbage value.
2) What does the line ((arr + in) + j) actually do ? I mean, Why can't we do something like ((arr + i) + j) to access arr[i][j] ?

I also tried passing the matrix using parameter int **arr and then tried printing the value as arr[i][j] but there was no output.

Here is the output that I get:-

```<code>Enter number of nodes: 4
0167772161878012032-1
0000
0000
0000
</code>```

And here is my code :-

```<code>#include <iostream>
using namespace std;

void show(int* arr, int n)
{
    int i, j;

    for(i = 0; i < n; ++i)
    {
        for(j = 0; j < n; ++j)
        {
            cout << *((arr + i*n) + j);
        }

        cout << endl;
    }
}

int main()
{
    int n, i, j;

    cout << "Enter number of nodes: ";
    cin >> n;

    int arr[n][n] = {{0}}; //Will initialize all elements in the matrix with 0.

    show((int*)arr, n);
}
</code>```

答:
Variable length arrays is not a standard C++ feature.

Nevertheless you passed to the function a pointer to the first element of a two-dimensional array.

Each "row" of the two-dimensional array has n elements. So if you have a pointer to the first element of the first row then to get the pointer to the first element of the second row you have to write

```<code>arr + n
</code>```

If you want to get the first pointer to the i-th row of the two-dimensional array you have to write

```<code>arr + i * n
</code>```

To get pointer to an element within the row you have to write

```<code>( arr  + i * n ) + j
</code>```

that is the same as

```<code>arr + i ( n + j
</code>```

to get the element pointed to by the pointer you have to dereference the pointer

```<code>*( arr + i * n + j )
</code>```

Title: Issue in Passing a 2-D array

Body:
I read how to pass 2-D arrays in a function as a parameter and tried to implement the same. There are two problems which I encountered:

1) The first line of the output of the code contains garbage value.
2) What does the line ((arr + in) + j) actually do ? I mean, Why can't we do something like ((arr + i) + j) to access arr[i][j] ?

I also tried passing the matrix using parameter int **arr and then tried printing the value as arr[i][j] but there was no output.

Here is the output that I get:-

Enter number of nodes: 4
0167772161878012032-1
0000
0000
0000

And here is my code :-

#include <iostream>
using namespace std;

void show(int* arr, int n)
{
    int i, j;

    for(i = 0; i < n; ++i)
    {
        for(j = 0; j < n; ++j)
        {
            cout << *((arr + i*n) + j);
        }

        cout << endl;
    }
}

int main()
{
    int n, i, j;

    cout << "Enter number of nodes: ";
    cin >> n;

    int arr[n][n] = {{0}}; //Will initialize all elements in the matrix with 0.

    show((int*)arr, n);
}

Body:
Variable length arrays is not a standard C++ feature.

Nevertheless you passed to the function a pointer to the first element of a two-dimensional array.

Each "row" of the two-dimensional array has n elements. So if you have a pointer to the first element of the first row then to get the pointer to the first element of the second row you have to write

arr + n

If you want to get the first pointer to the i-th row of the two-dimensional array you have to write

arr + i * n

To get pointer to an element within the row you have to write

( arr  + i * n ) + j

that is the same as

arr + i ( n + j

to get the element pointed to by the pointer you have to dereference the pointer

*( arr + i * n + j )


问:
lastsave command for previously saved key
I need to see when the key is saved lastly.
But its returning an error for the command</p>

```<code>redis-cli lastsave "mykey"

 (error) ERR wrong number of arguments for 'lastsave' command
</code>```

答: Read the docs - LASTSAVE accepts 0 arguments and reports the last time that the entire database was persisted.

Body:
I need to see when the key is saved lastly.
But its returning an error for the command

redis-cli lastsave "mykey"

 (error) ERR wrong number of arguments for 'lastsave' command


问:
Easy Digital Downloads - Fire PHP when transaction was successful goes wrong
I’m using Easy Digital Downloads for my Wordpress webshop. After someone buys a item it needs to add credits to the MySQL database. I got this working by adding PHP code to shortcode-receipt.php.

This is working correct but when I reload the receipt via browser or mail the PHP code will fire again:
php
<?php
if( edd_is_payment_complete( $payment->ID ) && edd_receipt_show_download_files( $item['id'], $edd_receipt_args, $item ) ) :
?>

Could someone help me out here?

What is the best method to fire PHP code when a payment is successful?

Thanks in advance!

答:
There is action edd_complete_purchase which fires when order is completed.

So, in your case, I would remove the code from the shortcode and created an plugin. Inside the plugin should be something like this

```<code>function my_edd_receipt( $payment_id ){
if( edd_is_payment_complete( $payment_id ) && edd_receipt_show_download_files( $item['id'], $edd_receipt_args, $item ) ) :
}

add_action( 'edd_complete_purchase', 'my_edd_receipt');
</code>```

Body:
There is action edd_complete_purchase which fires when order is completed.

So, in your case, I would remove the code from the shortcode and created an plugin. Inside the plugin should be something like this

function my_edd_receipt( $payment_id ){
if( edd_is_payment_complete( $payment_id ) && edd_receipt_show_download_files( $item['id'], $edd_receipt_args, $item ) ) :
}

add_action( 'edd_complete_purchase', 'my_edd_receipt');


问:
How to import a large text file containing many small records in Objective-C without using large amounts of memory
I need the ability to import some fairly large text files (100Mb+) into CoreData in an application targeted towards mobile devices where memory is constrained. Each file contains a large number of small records which will be processed before being added to the database. Looking through many sources the recommended method for reading in a text file seems to be:

```<code>NSString *stringFromFileAtPath = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
</code>```

At first glance this seems like a very memory intensive way of doing what I require, but given that there seems to be no other recommended way to read the file would I be right in guessing that Apple have taken this into account and do their own memory management - perhaps faulting in data from the file only when necessary?

If not would the best way to proceed be using NSStream and NSScanner to retrieve and process one line of text at a time?

If the recommended method does handle memory well then the next step is often:

```<code>NSArray *lines = [stringFromFileAtPath componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
</code>```

If I use this method I'm assuming that it would need the complete text file in memory so again it would be memory intensive. To save memory would I be better off using NSScanner or, given the limited processing power of mobile devices (certainly some of the older ones) would it take forever to complete?

Thanks in advance for any help you can give me with this question.

Dave

答: I think the best way to get a lot of data into a database is to deliver a pre-populated database (*.sqlite-file). </p>

ContentLicense: CC BY-SA 2.5

Body:
I need the ability to import some fairly large text files (100Mb+) into CoreData in an application targeted towards mobile devices where memory is constrained. Each file contains a large number of small records which will be processed before being added to the database. Looking through many sources the recommended method for reading in a text file seems to be:

NSString *stringFromFileAtPath = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

At first glance this seems like a very memory intensive way of doing what I require, but given that there seems to be no other recommended way to read the file would I be right in guessing that Apple have taken this into account and do their own memory management - perhaps faulting in data from the file only when necessary?

If not would the best way to proceed be using NSStream and NSScanner to retrieve and process one line of text at a time?

If the recommended method does handle memory well then the next step is often:

NSArray *lines = [stringFromFileAtPath componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

If I use this method I'm assuming that it would need the complete text file in memory so again it would be memory intensive. To save memory would I be better off using NSScanner or, given the limited processing power of mobile devices (certainly some of the older ones) would it take forever to complete?

Thanks in advance for any help you can give me with this question.

Dave


问:
Unhoisted variables (let, const) used in immediately invoked async function before declaration of said variables
Should the following code work?

```<code>(async () => {
  await new Promise(r => setTimeout(r, 1000))
  useNum();
})();

let num = 10;
function useNum() {
  return num + 1;
}
</code>```

https://jsbin.com/tayotitepa/edit?html,output

Safari on iOS (v13.3) says that it's impossible (num variable doesn't exist), whereas Chrome and Firefox think it's fine.

If you remove the await new Promise... line then Chrome and Firefox complain.

It seems like Chrome and Firefox are correct here, because we're not awaiting the immediately invoked async function, and so by the time the await new Promise... line has finished, the rest of the script will have already been processed. But I thought I'd check because maybe the spec says that it's strictly about the ordering of the declaration of the variables and usages of those variables, and so it wouldn't matter about the "timing" of the usage of the variables.

答:
I tried this with different scenarios, What I observed is that

async/await is nothing to do with this.

let num is hoisted but value is undefined.

so the code is look like something

let num; // --- hoisted with value as undefined
setTimeout(() => {}, 1000)
console.log(useNum());

num = 10; // --- value is assigned here
function useNum(str) {
  return num + 1;
}
```

as you know java-script is synchronous, i.e it execute each and every line a at time, so when we are calling the useNum method at that time num will be undefined.

Body:
Should the following code work?

(async () => {
  await new Promise(r => setTimeout(r, 1000))
  useNum();
})();

let num = 10;
function useNum() {
  return num + 1;
}

https://jsbin.com/tayotitepa/edit?html,output

Safari on iOS (v13.3) says that it's impossible (num variable doesn't exist), whereas Chrome and Firefox think it's fine.

If you remove the await new Promise... line then Chrome and Firefox complain.

It seems like Chrome and Firefox are correct here, because we're not awaiting the immediately invoked async function, and so by the time the await new Promise... line has finished, the rest of the script will have already been processed. But I thought I'd check because maybe the spec says that it's strictly about the ordering of the declaration of the variables and usages of those variables, and so it wouldn't matter about the "timing" of the usage of the variables.

Body:
I tried this with different scenarios, What I observed is that

async/await is nothing to do with this.

let num is hoisted but value is undefined.

so the code is look like something

let num; // --- hoisted with value as undefined
setTimeout(() => {}, 1000)
console.log(useNum());

num = 10; // --- value is assigned here
function useNum(str) {
  return num + 1;
}

as you know java-script is synchronous, i.e it execute each and every line a at time, so when we are calling the useNum method at that time num will be undefined.


问:
Without import the Angular Service to the module, can we use it?
Without import the Angular Service to the module, can we use it?

```<code>providers: [ApiService,EmployeeService,DataService,MatDatepickerModule,StudentServiceService
  ,  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
  { provide: MAT_DATE_FORMATS, useValue: DateFormats }],
})
</code>```

here I have imported all the service classes. my question is 'Without import the Angular Service to the module, can we use it?'

答: Yes but you need to inject it where you are going to use it</p>

Body:
Without import the Angular Service to the module, can we use it?

providers: [ApiService,EmployeeService,DataService,MatDatepickerModule,StudentServiceService
  ,  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
  { provide: MAT_DATE_FORMATS, useValue: DateFormats }],
})

here I have imported all the service classes. my question is 'Without import the Angular Service to the module, can we use it?'


问:
LLVM build using cmake fails during tsan_libdispatch_mac.cc; "Error: conflicting types for ..."
I have at least successfully configured the build for the llvm compiler according to the directions here.

When I go to build using cmake --build . -v I get the following error output:

```<code>$ cmake --build . -v
...
[ 63%] Building CXX object projects/compiler-rt/lib/tsan/CMakeFiles/clang_rt.tsan_osx_dynamic.dir/rtl/tsan_libdispatch_mac.cc.o
cd /Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/build/projects/compiler-rt/lib/tsan && /usr/bin/clang++ --sysroot=/  -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -Dclang_rt_tsan_osx_dynamic_EXPORTS -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/build/projects/compiler-rt/lib/tsan -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/build/include -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/include -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/..  -isystem / -fPIC -fvisibility-inlines-hidden -Wall -W -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wcovered-switch-default -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -std=c++11 -Wall -std=c++11 -O3 -DNDEBUG -arch x86_64 -arch x86_64h -fPIC    -stdlib=libc++ -mmacosx-version-min=10.9 -fPIC -fno-builtin -fno-exceptions -fomit-frame-pointer -funwind-tables -fno-stack-protector -fno-sanitize=safe-stack -fvisibility=hidden -fvisibility-inlines-hidden -fno-function-sections -fno-lto -O3 -gline-tables-only -Wno-gnu -Wno-variadic-macros -Wno-c99-extensions -Wno-non-virtual-dtor -fPIE -fno-rtti -msse3 -Wframe-larger-than=512 -Wglobal-constructors -o CMakeFiles/clang_rt.tsan_osx_dynamic.dir/rtl/tsan_libdispatch_mac.cc.o -c /Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc
/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc:144:22: error:
      conflicting types for 'dispatch_sync'
DISPATCH_INTERCEPT_B(dispatch_sync)
                     ^
/usr/include/dispatch/queue.h:292:1: note: previous declaration is here
dispatch_sync(dispatch_queue_t queue, DISPATCH_NOESCAPE dispatch_block_t block);
^
/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc:145:22: error:
      conflicting types for 'dispatch_barrier_sync'
DISPATCH_INTERCEPT_B(dispatch_barrier_sync)
                     ^
/usr/include/dispatch/queue.h:1278:1: note: previous declaration is here
dispatch_barrier_sync(dispatch_queue_t queue,
^
/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc:162:24: error:
      conflicting types for 'dispatch_once'
TSAN_INTERCEPTOR(void, dispatch_once, dispatch_once_t *predicate,
                       ^
/usr/include/dispatch/once.h:73:1: note: previous declaration is here
dispatch_once(dispatch_once_t *predicate,
^
3 errors generated.
make[2]: *** [projects/compiler-rt/lib/tsan/CMakeFiles/clang_rt.tsan_osx_dynamic.dir/rtl/tsan_libdispatch_mac.cc.o] Error 1
make[1]: *** [projects/compiler-rt/lib/tsan/CMakeFiles/clang_rt.tsan_osx_dynamic.dir/all] Error 2
make: *** [all] Error 2
</code>```

I was previously able to workaround buggy compiler flags set by cmake by simply copying and pasting the verbose output and correcting it in the command line, but I'm not sure what to edit here to get things to work.

I've tried changing -isysroot, copying and pasting header files into llvm/include from /usr/include or the MacOSX10.14.sdk file, and the persistent issue is the error: conflicting types ...

I've even tried doing small modifications to tsan_libdispatch_mac.cc but none of them worked (e.g., changing #include <dispatch/dispatch.h> to #include <dispatch.h>, changing "user_alloc" to "user_alloc_internal"...).

Any suggestions are welcome.

Anthony

答: Basically I had to replace my original tsan_libdispatch_mac.cc with the one form here. I have yet to complete the full installation, much less test performance, but my build is proceeding past this point now. </p>

Body:
I have at least successfully configured the build for the llvm compiler according to the directions here.

When I go to build using cmake --build . -v I get the following error output:

$ cmake --build . -v
...
[ 63%] Building CXX object projects/compiler-rt/lib/tsan/CMakeFiles/clang_rt.tsan_osx_dynamic.dir/rtl/tsan_libdispatch_mac.cc.o
cd /Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/build/projects/compiler-rt/lib/tsan && /usr/bin/clang++ --sysroot=/  -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -Dclang_rt_tsan_osx_dynamic_EXPORTS -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/build/projects/compiler-rt/lib/tsan -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/build/include -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/include -I/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/..  -isystem / -fPIC -fvisibility-inlines-hidden -Wall -W -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wcovered-switch-default -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -std=c++11 -Wall -std=c++11 -O3 -DNDEBUG -arch x86_64 -arch x86_64h -fPIC    -stdlib=libc++ -mmacosx-version-min=10.9 -fPIC -fno-builtin -fno-exceptions -fomit-frame-pointer -funwind-tables -fno-stack-protector -fno-sanitize=safe-stack -fvisibility=hidden -fvisibility-inlines-hidden -fno-function-sections -fno-lto -O3 -gline-tables-only -Wno-gnu -Wno-variadic-macros -Wno-c99-extensions -Wno-non-virtual-dtor -fPIE -fno-rtti -msse3 -Wframe-larger-than=512 -Wglobal-constructors -o CMakeFiles/clang_rt.tsan_osx_dynamic.dir/rtl/tsan_libdispatch_mac.cc.o -c /Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc
/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc:144:22: error:
      conflicting types for 'dispatch_sync'
DISPATCH_INTERCEPT_B(dispatch_sync)
                     ^
/usr/include/dispatch/queue.h:292:1: note: previous declaration is here
dispatch_sync(dispatch_queue_t queue, DISPATCH_NOESCAPE dispatch_block_t block);
^
/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc:145:22: error:
      conflicting types for 'dispatch_barrier_sync'
DISPATCH_INTERCEPT_B(dispatch_barrier_sync)
                     ^
/usr/include/dispatch/queue.h:1278:1: note: previous declaration is here
dispatch_barrier_sync(dispatch_queue_t queue,
^
/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/llvm/projects/compiler-rt/lib/tsan/rtl/tsan_libdispatch_mac.cc:162:24: error:
      conflicting types for 'dispatch_once'
TSAN_INTERCEPTOR(void, dispatch_once, dispatch_once_t *predicate,
                       ^
/usr/include/dispatch/once.h:73:1: note: previous declaration is here
dispatch_once(dispatch_once_t *predicate,
^
3 errors generated.
make[2]: *** [projects/compiler-rt/lib/tsan/CMakeFiles/clang_rt.tsan_osx_dynamic.dir/rtl/tsan_libdispatch_mac.cc.o] Error 1
make[1]: *** [projects/compiler-rt/lib/tsan/CMakeFiles/clang_rt.tsan_osx_dynamic.dir/all] Error 2
make: *** [all] Error 2

I was previously able to workaround buggy compiler flags set by cmake by simply copying and pasting the verbose output and correcting it in the command line, but I'm not sure what to edit here to get things to work.

I've tried changing -isysroot, copying and pasting header files into llvm/include from /usr/include or the MacOSX10.14.sdk file, and the persistent issue is the error: conflicting types ...

I've even tried doing small modifications to tsan_libdispatch_mac.cc but none of them worked (e.g., changing #include <dispatch/dispatch.h> to #include <dispatch.h>, changing "user_alloc" to "user_alloc_internal"...).

Any suggestions are welcome.

Anthony


问:
Type script filtering between 2 dates
I filter on the search screen you see in the picture, but it doesn't work properly. When you write 03.03.2020 on the day of payment, it brings all the records. I want to filter the payment date together with my login date, bring the records in between. How can I fix the code?

.html

```<code><div class="rez">
    <input id="hotelName" type="text" placeholder="Enter Hotel Name" [(ngModel)]="hotelName" (ngModelChange)="changeHotelName()" /><br />
    <input class="textbox-n" placeholder="Enter check in date" [(ngModel)]="startDate" type="text" onfocus="(this.type='date')" id="entry" (ngModelChange)="changeStartDate()" />
    <input class="textbox-n" placeholder="Enter payDate" [(ngModel)]="endDate" type="text" onfocus="(this.type='date')" id="exit" (ngModelChange)="changeEndDate()" /><br />
    <label id="lblAdults">Number of adults</label> <label id="lblChilds">Number of childs</label><br />
    <input id="adult" type="number" [(ngModel)]="adult" (ngModelChange)="changeNumberOfAdults()" />
    <input id="child" type="number" max="3" [(ngModel)]="childCount" [(ngModel)]="chd" (ngModelChange)="changeNumberOfChilds()" />
    <label id="chd1" *ngIf="childCount>=1">Child Ages</label><br />
    <select class="custom-select" id="chd_1" *ngIf="childCount >= 1">
        <option selected>0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select>
    <select class="custom-select" id="chd_2" *ngIf="childCount>=2">
        <option selected>0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select>
    <select class="custom-select" id="chd_3" *ngIf="childCount>=3">
        <option selected>0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select>
    <button id="search" class="btn btn-warning" type="button">Search</button>
</div>
</code>```

.ts

```<code>private isEqual(date1: Date, date2: Date) {
    return date1.getDate() == date2.getDate() && date1.getMonth() == date2.getMonth() && date1.getFullYear() == date2.getFullYear();
}

changeStartDate() {
    const filtered = this.hotels.filter(x => this.isEqual(new Date(x.checkInDate), new Date(this.startDate)));
    if (filtered) this.dsHotels.data = filtered;
    else return false;
}

changeEndDate() {
    const filtered = this.hotels.filter(x => this.isEqual(new Date(x.payDate), new Date(this.endDate)));
    this.dsHotels.data = filtered;
}
</code>```

[pictures]

```<code>https://i.stack.imgur.com/0IeDK.png
https://i.stack.imgur.com/ZDYCD.png
https://i.stack.imgur.com/wPguo.png
</code>```

答:
So I think the issue is you need to check that both checkInDate and payDate match in your filter. In the current code, only one of the values are being checked at a time

I think the fix may be something like this:

private isEqual(date1: Date, date2: Date) {
    return date1.getDate() == date2.getDate() && date1.getMonth() == date2.getMonth() && date1.getFullYear() == date2.getFullYear();
}

private isDataEqualToDate(value1: any, date2: Date) {
   if (value1 == null) return true;
   return isEqual(new Date(value1), date2);
}

private getFilteredHotels() {
   return this.hotels.filter(
     x => this.isDataEqualToDate(this.startDate, new Date(x.checkInDate))
       && this.isDataEqualToDate(this.endDate, new Date(x.payDate))
   );
}

changeStartDate() {
    this.dsHotels.data = this.getFilteredHotels();

}

changeEndDate() {
    this.dsHotels.data = this.getFilteredHotels();
}
```

Title: Type script filtering between 2 dates

Body:
I filter on the search screen you see in the picture, but it doesn't work properly. When you write 03.03.2020 on the day of payment, it brings all the records. I want to filter the payment date together with my login date, bring the records in between. How can I fix the code?

.html

    <input id="hotelName" type="text" placeholder="Enter Hotel Name" [(ngModel)]="hotelName" (ngModelChange)="changeHotelName()" />

    <input class="textbox-n" placeholder="Enter check in date" [(ngModel)]="startDate" type="text" onfocus="(this.type='date')" id="entry" (ngModelChange)="changeStartDate()" />
    <input class="textbox-n" placeholder="Enter payDate" [(ngModel)]="endDate" type="text" onfocus="(this.type='date')" id="exit" (ngModelChange)="changeEndDate()" />

    Number of adults Number of childs

    <input id="adult" type="number" [(ngModel)]="adult" (ngModelChange)="changeNumberOfAdults()" />
    <input id="child" type="number" max="3" [(ngModel)]="childCount" [(ngModel)]="chd" (ngModelChange)="changeNumberOfChilds()" />
    =1">Child Ages

    <select class="custom-select" id="chd_1" *ngIf="childCount >= 1">
        <option selected>0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select>
    <select class="custom-select" id="chd_2" *ngIf="childCount>=2">
        <option selected>0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select>
    <select class="custom-select" id="chd_3" *ngIf="childCount>=3">
        <option selected>0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select>
    <button id="search" class="btn btn-warning" type="button">Search</button>

.ts

private isEqual(date1: Date, date2: Date) {
    return date1.getDate() == date2.getDate() && date1.getMonth() == date2.getMonth() && date1.getFullYear() == date2.getFullYear();
}

changeStartDate() {
    const filtered = this.hotels.filter(x => this.isEqual(new Date(x.checkInDate), new Date(this.startDate)));
    if (filtered) this.dsHotels.data = filtered;
    else return false;
}

changeEndDate() {
    const filtered = this.hotels.filter(x => this.isEqual(new Date(x.payDate), new Date(this.endDate)));
    this.dsHotels.data = filtered;
}

[pictures]

https://i.stack.imgur.com/0IeDK.png
https://i.stack.imgur.com/ZDYCD.png
https://i.stack.imgur.com/wPguo.png


问:
Finger print on php
Is there a way to recognize an image or something like a fingerprint or a very complex image on  php?

Do you know a library or anything to recognize images like this?

答:
imageMagick : imagMagick Doc

```<code><?php

$image1 = new imagick("image1.png");

$image2 = new imagick("image2.png");

$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");

header("Content-Type: image/png");
echo $result[0];

?>
</code>```

from the php doc.

This class can do the job too :
Comparison class

Oh and for fingerprint, the comparison is basically based on a very complicated methods (comparing 12 identical areas), you can't just do it with simple php script

Title: Finger print on php

Body:
imageMagick : imagMagick Doc

<?php

$image1 = new imagick("image1.png");

$image2 = new imagick("image2.png");

$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");

header("Content-Type: image/png");
echo $result[0];

?>

from the php doc.

This class can do the job too :
Comparison class

Oh and for fingerprint, the comparison is basically based on a very complicated methods (comparing 12 identical areas), you can't just do it with simple php script


问:
Can we call a parameterized constructor from a parameterless constructor?
For example I have class like this

```<code>public class ABC
{
  private readonly IMemoryCache _cache;
  private readonly IConfiguration _config;
  private readonly IDistributedCache _distributedCache;

  public ABC(IMemoryCache memoryCache, IConfiguration config, IDistributedCache distributedCache)
  {
   _cache = memoryCache;
   _config = config;
   _distributedCache = distributedCache;
  }
  public ABC() : this(IMemoryCache , IConfiguration ,IDistributedCache )
  {
  }
}
</code>```

As you can see that I have tried to call a Parameterized constructor from a Parameter-less constructor, but that's not possible. Is there any other way to achieve this concept?

答:
You need to pass in concrete implementations of those interfaces, It's just like calling a method. There is nothing magical about this() syntax apart from where it appears. For example if you have a default implementation of IMemoryCache implemented in class DefaultMemoryCache you can just 'new that up' and pass it in:

```<code>public ABC() : this(new DefaultMemoryCache(), etc.)
{
}
</code>```

Alternatively, you can use a static factory method if constructing these dependencies is a bit too complicated:

```<code>public static ABC CreateNew()
{
    var others = ...
    var cache = new DefaultCache(others, etc.)
    ...
    return new ABC(cache, etc.);
}
</code>```

But if you want to be able to use the interface as your input, this is what you can do: (Now, this is just an example to make a point, I do not recommend doing this since it would be very confusing and fragile)

```<code>    public ABC() : this
    (
        (IMemoryCache) Activator.CreateInstance
        (
            Assembly.GetExecutingAssembly().GetTypes().First
            (
                t => typeof(IMemoryCache).IsAssignableFrom(t) && !t.IsInterface
            )
        )
    )
    {
    }
</code>```

The reflection code snippet above, in essence, what a dependency injection library would do, and you might want to consider using one if your project is suitable for it.

One last thing, just to have a complete answer, of course, you can also implement a body in your overloaded contractors:

```<code>public class ABC
{
    private readonly ICache _cache;

    public ABC()
    {
        _cache = new Cache();
    }

    public ABC(ICache cache)
    {
        _cache = cache;
    }
}
</code>```

: this() syntax is only required if you want to call other constructors in the same class for code reuse.

Body:
For example I have class like this

public class ABC
{
  private readonly IMemoryCache _cache;
  private readonly IConfiguration _config;
  private readonly IDistributedCache _distributedCache;

  public ABC(IMemoryCache memoryCache, IConfiguration config, IDistributedCache distributedCache)
  {
   _cache = memoryCache;
   _config = config;
   _distributedCache = distributedCache;
  }
  public ABC() : this(IMemoryCache , IConfiguration ,IDistributedCache )
  {
  }
}

As you can see that I have tried to call a Parameterized constructor from a Parameter-less constructor, but that's not possible. Is there any other way to achieve this concept?

Body:
You need to pass in concrete implementations of those interfaces, It's just like calling a method. There is nothing magical about this() syntax apart from where it appears. For example if you have a default implementation of IMemoryCache implemented in class DefaultMemoryCache you can just 'new that up' and pass it in:

public ABC() : this(new DefaultMemoryCache(), etc.)
{
}

Alternatively, you can use a static factory method if constructing these dependencies is a bit too complicated:

public static ABC CreateNew()
{
    var others = ...
    var cache = new DefaultCache(others, etc.)
    ...
    return new ABC(cache, etc.);
}

But if you want to be able to use the interface as your input, this is what you can do: (Now, this is just an example to make a point, I do not recommend doing this since it would be very confusing and fragile)

    public ABC() : this
    (
        (IMemoryCache) Activator.CreateInstance
        (
            Assembly.GetExecutingAssembly().GetTypes().First
            (
                t => typeof(IMemoryCache).IsAssignableFrom(t) && !t.IsInterface
            )
        )
    )
    {
    }

The reflection code snippet above, in essence, what a dependency injection library would do, and you might want to consider using one if your project is suitable for it.

One last thing, just to have a complete answer, of course, you can also implement a body in your overloaded contractors:

public class ABC
{
    private readonly ICache _cache;

    public ABC()
    {
        _cache = new Cache();
    }

    public ABC(ICache cache)
    {
        _cache = cache;
    }
}

: this() syntax is only required if you want to call other constructors in the same class for code reuse.


问:
python key phrase extraction using pke module
I was trying to extract key phrases using https://github.com/boudinfl/pke module.
When I run it once it is perfectly working. But when I am running it for several times it emits following error.
ZeroDivisionError: float division by zero

my code is as follows.

```<code>extractor = TopicRank()
def key_phrase_extract(path_to_json):
   //get_temp_text.txt from json
   extractor.load_document(input='temp_text.txt', language="en", max_length=10000000,
                        normalization='stemming')
   extractor.candidate_selection(pos={'NOUN', 'PROPN', 'ADJ'},stoplist=stoplist)
   extractor.candidate_weighting(threshold=0.74,
                                  method='average')
   kpe_results = []
   for (keyphrase, score) in extractor.get_n_best(n=10, stemming=True):
      kpe_results.append([keyphrase, score])
   print(kpe_results)

for each_json in json_list()
    key_phrase_extract('each_json')
</code>```

It perfectly runs for the first json file but when starting the second one it gives me the
ZeroDivisionError: float division by zero

答:
I was able to fix the issue. The problem was initializing the extractor outside the function.</p>

```<code>def key_phrase_extract(path_to_json):
   extractor = TopicRank()
   //get_temp_text.txt from json
   extractor.load_document(input='temp_text.txt', language="en", max_length=10000000,
                        normalization='stemming')
   extractor.candidate_selection(pos={'NOUN', 'PROPN', 'ADJ'},stoplist=stoplist)
   extractor.candidate_weighting(threshold=0.74,
                                  method='average')
   kpe_results = []
   for (keyphrase, score) in extractor.get_n_best(n=10, stemming=True):
      kpe_results.append([keyphrase, score])
   print(kpe_results)

for each_json in json_list()
    key_phrase_extract('each_json')
</code>```

Body:
I was trying to extract key phrases using https://github.com/boudinfl/pke module.
When I run it once it is perfectly working. But when I am running it for several times it emits following error.
ZeroDivisionError: float division by zero

my code is as follows.

extractor = TopicRank()
def key_phrase_extract(path_to_json):
   //get_temp_text.txt from json
   extractor.load_document(input='temp_text.txt', language="en", max_length=10000000,
                        normalization='stemming')
   extractor.candidate_selection(pos={'NOUN', 'PROPN', 'ADJ'},stoplist=stoplist)
   extractor.candidate_weighting(threshold=0.74,
                                  method='average')
   kpe_results = []
   for (keyphrase, score) in extractor.get_n_best(n=10, stemming=True):
      kpe_results.append([keyphrase, score])
   print(kpe_results)

for each_json in json_list()
    key_phrase_extract('each_json')

It perfectly runs for the first json file but when starting the second one it gives me the
ZeroDivisionError: float division by zero

Body:
I was able to fix the issue. The problem was initializing the extractor outside the function.

def key_phrase_extract(path_to_json):
   extractor = TopicRank()
   //get_temp_text.txt from json
   extractor.load_document(input='temp_text.txt', language="en", max_length=10000000,
                        normalization='stemming')
   extractor.candidate_selection(pos={'NOUN', 'PROPN', 'ADJ'},stoplist=stoplist)
   extractor.candidate_weighting(threshold=0.74,
                                  method='average')
   kpe_results = []
   for (keyphrase, score) in extractor.get_n_best(n=10, stemming=True):
      kpe_results.append([keyphrase, score])
   print(kpe_results)

for each_json in json_list()
    key_phrase_extract('each_json')


问:
TestNG - providing parameters for class level test
I am running tests using TestNG, Java & Eclipse work-space.
I can run tests in a number of ways.
I can run a TestNG file, or I can run individual classes.
If I run from an individual class, the parameters are not picked up from the TestNG.xml file.
I may want to switch testings to a different URL.
This form, given in Tutorials, does not work, & only produces errors.

```<code>import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterizedTest1 {
   @Test
   @Parameters("myName")
   public void parameterTest(String myName) {
      System.out.println("Parameterized value is : " + myName);
   }
}
</code>```

This is from a Tutorial at https://www.tutorialspoint.com/testng/testng_parameterized_test.htm

Error says this: [Utils] [ERROR] [Error] org.testng.TestNGException:
Parameter 'url' is required by @Test on method addProjectTask but has not been marked @Optional or defined
in C:\Users\SStaple\AppData\Local\Temp\testng-eclipse-38561327\testng-customsuite.xml

*** I called my parameter url. i.e:

```<code>@Test(groups = { "all", "projects", "create", "simple" })
@Parameters("url")
public void addProjectTask(String url) {
    System.out.println("Parameterized value is : " + url);
</code>```

I don't want to have to re-code this every time I switch URL.

Testng.xml looks like this:

```<code> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite allow-return-values="false" configfailurepolicy="skip"
    data-provider-thread-count="10" group-by-instances="false" guice-stage="DEVELOPMENT"
    junit="false" name="hardening-simple" parallel="none" preserve-order="true"
    skipfailedinvocationcounts="false" thread-count="5">
    <parameter name="browser" value="firefox" />
    <parameter name="url" value="https://url/#/" />
    <parameter name="printToFile" value="true" />
    <parameter name="trace" value="false" />
    <parameter name="opt" value="true" />
    <parameter name="customer" value="Demo" />
    <parameter name="network" value="NSG Designated Streets (Type 1/2)" />
    <parameter name="buildNo" value="025" />
    <parameter name="teamCity" value="false" />
    <parameter name="retest" value="0" />
    <parameter name="user" value="normal" />
    <listeners>
        <listener class-name="listeners.TestNGCustomReportListener" />
    </listeners>
    <test allow-return-values="false" group-by-instances="false"
        junit="false" name="firefoxTest" preserve-order="true"
        skipfailedinvocationcounts="false">
        <parameter name="browser" value="firefox" />
        <parameter name="url" value="https://url/#/" />
        <parameter name="opt" value="true" />
        <parameter name="user" value="normal" />
        <groups>
            <define name="simple">
                <include name="simple" />
            </define>
            <run>
                <include name="simple" />
                <exclude name="not-implemented" />
            </run>
        </groups>
        <classes>
</code>```

Does anyone know the correct method?

答:
Using parameters is not a optimal solution. Drive your values from properties file, this way you can maintain all your data. You can create variables in your code and use the values from properties file. You can change the data in properties file without changing the code but in more manageable way. If there are more than one set of data, then you can use multiple properties file and just provide the address of the file.

Tutorial for properties file:
https://www.youtube.com/watch?v=bljA8dpfWeQ

Body:
I am running tests using TestNG, Java & Eclipse work-space.
I can run tests in a number of ways.
I can run a TestNG file, or I can run individual classes.
If I run from an individual class, the parameters are not picked up from the TestNG.xml file.
I may want to switch testings to a different URL.
This form, given in Tutorials, does not work, & only produces errors.

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterizedTest1 {
   @Test
   @Parameters("myName")
   public void parameterTest(String myName) {
      System.out.println("Parameterized value is : " + myName);
   }
}

This is from a Tutorial at https://www.tutorialspoint.com/testng/testng_parameterized_test.htm

Error says this: [Utils] [ERROR] [Error] org.testng.TestNGException:
Parameter 'url' is required by @Test on method addProjectTask but has not been marked @Optional or defined
in C:\Users\SStaple\AppData\Local\Temp\testng-eclipse-38561327\testng-customsuite.xml

*** I called my parameter url. i.e:

@Test(groups = { "all", "projects", "create", "simple" })
@Parameters("url")
public void addProjectTask(String url) {
    System.out.println("Parameterized value is : " + url);

I don't want to have to re-code this every time I switch URL.

Testng.xml looks like this:

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite allow-return-values="false" configfailurepolicy="skip"
    data-provider-thread-count="10" group-by-instances="false" guice-stage="DEVELOPMENT"
    junit="false" name="hardening-simple" parallel="none" preserve-order="true"
    skipfailedinvocationcounts="false" thread-count="5">
    <parameter name="browser" value="firefox" />
    <parameter name="url" value="https://url/#/" />
    <parameter name="printToFile" value="true" />
    <parameter name="trace" value="false" />
    <parameter name="opt" value="true" />
    <parameter name="customer" value="Demo" />
    <parameter name="network" value="NSG Designated Streets (Type 1/2)" />
    <parameter name="buildNo" value="025" />
    <parameter name="teamCity" value="false" />
    <parameter name="retest" value="0" />
    <parameter name="user" value="normal" />
    <listeners>
        <listener class-name="listeners.TestNGCustomReportListener" />
    </listeners>
    <test allow-return-values="false" group-by-instances="false"
        junit="false" name="firefoxTest" preserve-order="true"
        skipfailedinvocationcounts="false">
        <parameter name="browser" value="firefox" />
        <parameter name="url" value="https://url/#/" />
        <parameter name="opt" value="true" />
        <parameter name="user" value="normal" />
        <groups>
            <define name="simple">
                <include name="simple" />
            </define>
            <run>
                <include name="simple" />
                <exclude name="not-implemented" />
            </run>
        </groups>
        <classes>

Does anyone know the correct method?


问:
What is the purpose of the key pairs (public and private) available in aws ec2?
In the AWS EC2 console/service, you are able to view several key pairs - what exactly is the purpose of these key pairs? Are they relevant to the ec2 instances or the rds?</p>

答:
From AWS documentation:

Amazon EC2 uses public key cryptography to encrypt and decrypt login information. Public key cryptography uses a public key to encrypt a piece of data, and then the recipient uses the private key to decrypt the data. The public and private keys are known as a key pair. Public key cryptography enables you to securely access your instances using a private key instead of a password.
  When you launch an instance, you specify the key pair. You can specify an existing key pair or a new key pair that you create at launch. At boot time, the public key content is placed on the instance in an entry within ~/.ssh/authorized_keys. To log in to your instance, you must specify the private key when you connect to the instance.

So, we can see what the purpose of the key pair is. It is used to ensure safe login and connection to your EC2 instance.


问:
Postgres - Optimized dynamic headers in separate table
I have 2 tables in PostgreSQL:

```<code>CREATE TABLE contacts (
    id bigint NOT NULL,
    header_1 text NOT NULL,
    header_2 text,
    header_3 text );

CREATE TABLE headers (
    id bigint NOT NULL,
    name character varying,
    header_type text NOT NULL,
    organization_id bigint );

INSERT INTO contacts
(id, header_1, header_2, header_3)
VALUES
(1,'bob1@hotmail.com','Bob1','lol'),
(2,'bob2@hotmail.com','Bob2','lol'),
(3,'bob3@hotmail.com','Bob3','lol'),
(4,'bob4@hotmail.com','Bob4','lol'),
(5,'bob5@hotmail.com','Bob5','lol');

INSERT INTO headers
(id, name, header_type, organization_id)
VALUES
(1,'Email','email', 1),
(2,'First Name','first_name', 1),
(3,'Last Name','last_name', 1);
</code>```

I wanna end up with this structure, the tricky part is that the headers are dynamic, meaning there can be n amount of headers, "contacts" columns will always start with 'header_' and "headers" will always match the contact id,

```<code>Email             | First Name | Last Name
------------------|------------|-----------
bob1@hotmail.com  | Bob1       | lol
bob2@hotmail.com  | Bob2       | lol
bob3@hotmail.com  | Bob3       | lol
bob4@hotmail.com  | Bob4       | lol
bob5@hotmail.com  | Bob5       | lol
</code>```

Optimized querys are prefered

EDIT: Just to clarify
1.- There can be n amount of contact tables (contact1, contact2, etc)
2.- There can be n amount of rows in both header and contact tables.
3.- You can asume the data will always be integral, if table "contacts24" has a column named "header_57", you can asume theres gonna be a row in headers table with id: 57

答: At SQL, the table can not have a different number of columns for each row. So, it means you can not have a dynamic count of headers for each row on your contacts table.

Body:
I have 2 tables in PostgreSQL:

CREATE TABLE contacts (
    id bigint NOT NULL,
    header_1 text NOT NULL,
    header_2 text,
    header_3 text );

CREATE TABLE headers (
    id bigint NOT NULL,
    name character varying,
    header_type text NOT NULL,
    organization_id bigint );

INSERT INTO contacts
(id, header_1, header_2, header_3)
VALUES
(1,'bob1@hotmail.com','Bob1','lol'),
(2,'bob2@hotmail.com','Bob2','lol'),
(3,'bob3@hotmail.com','Bob3','lol'),
(4,'bob4@hotmail.com','Bob4','lol'),
(5,'bob5@hotmail.com','Bob5','lol');

INSERT INTO headers
(id, name, header_type, organization_id)
VALUES
(1,'Email','email', 1),
(2,'First Name','first_name', 1),
(3,'Last Name','last_name', 1);

I wanna end up with this structure, the tricky part is that the headers are dynamic, meaning there can be n amount of headers, "contacts" columns will always start with 'header_' and "headers" will always match the contact id,

Email             | First Name | Last Name
------------------|------------|-----------
bob1@hotmail.com  | Bob1       | lol
bob2@hotmail.com  | Bob2       | lol
bob3@hotmail.com  | Bob3       | lol
bob4@hotmail.com  | Bob4       | lol
bob5@hotmail.com  | Bob5       | lol

Optimized querys are prefered

EDIT: Just to clarify
1.- There can be n amount of contact tables (contact1, contact2, etc)
2.- There can be n amount of rows in both header and contact tables.
3.- You can asume the data will always be integral, if table "contacts24" has a column named "header_57", you can asume theres gonna be a row in headers table with id: 57


问:
Disable download button for Google Chrome?
Google Chrome is now shipping with a download button for videos that are just embedded videos (i.e. not MSE):

I'm having a hard time find any documentation for Chrome's implementation of the <video> tag. Does anyone know if there is a way - short of disabling "controls" and creating your own video player controls - of disabling this feature?

I realize that if this is showing, it's already easy to download the video, I just want to disable that functionality from appearing as part of the controls.

Thank you!

答:
I using following JavaScript snippet which is working very well:

```<code>document.querySelectorAll("video[id^=media-player]").forEach((elem) => elem.controlsList.add("nodownload"));
</code>```

Example: www.ring-cafe-finsterwalde.de/archiv/archiv.html#archiv4

Body:
I using following JavaScript snippet which is working very well:

document.querySelectorAll("video[id^=media-player]").forEach((elem) => elem.controlsList.add("nodownload"));

Example: www.ring-cafe-finsterwalde.de/archiv/archiv.html#archiv4


答:
use instances not types. create an instance of what ever class fulfills your Interface.</p>

```<code>public class ABC
{
  private readonly IMemoryCache _cache;
  private readonly IConfiguration _config;
  private readonly IDistributedCache _distributedCache;

  public ABC(IMemoryCache memoryCache, IConfiguration config, IDistributedCache distributedCache)
  {
   _cache = memoryCache;
   _config = config;
   _distributedCache = distributedCache;
  }
  public ABC() : this(new MemoryCache(), new Configuration(), new DistributedCache() )
  {
  }
}
</code>```

Title: Can we call a parameterized constructor from a parameterless constructor?

Body:
use instances not types. create an instance of what ever class fulfills your Interface.

public class ABC
{
  private readonly IMemoryCache _cache;
  private readonly IConfiguration _config;
  private readonly IDistributedCache _distributedCache;

  public ABC(IMemoryCache memoryCache, IConfiguration config, IDistributedCache distributedCache)
  {
   _cache = memoryCache;
   _config = config;
   _distributedCache = distributedCache;
  }
  public ABC() : this(new MemoryCache(), new Configuration(), new DistributedCache() )
  {
  }
}


问:
Django Signals - creating folder on model create
I got a model where I would like to create a folder when a model is created:
The model:

class Drive(models.Model):
    user = models.ManyToManyField(User)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    path = models.CharField(max_length=150, editable=False,
                            default='C:/Users/User/Desktop/Python/RavNet/media/storage/drives/{}'.format(str(id)))

    def save(self):
        super().save()
```

<p>I am trying to use signals, but I must admit this is my first ever attempt at making a signal not following a tutorial on point, and even after reading the documentation I am having a tough time.</p>

<pre class="lang-py prettyprint-override"><code>from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Drive
import os

@receiver(post_save, sender=Drive)
def create_drive(sender, instance, created, **kwargs):
    if created:
        os.mkdir(Drive.path)
</code>```

Nothing happens when I create a new drive model via the django admin. I have tested out my code in the shell and using a placeholder path (C:/Users/User/Desktop/Python/RavNet/media/storage/drives/test) that I know works in the signal in a try to debug, and have gotten as far as realising I am having two issues.

The first: When calling the Drive.path in the shell, I am getting the path:

```<code>'C:/Users/User/Desktop/Python/RavNet/media/storage/drives/<django.db.models.fields.UUIDField>'
</code>```

Instead of a path with the actual id as I hoped for. How do I solve this?

Secondly, my signal isn't working. It's like it isn't getting called. What am I doing wrong?

答:
You must import your signals in app.py. Please check your app.py. It must be like this:

```<code>from django.apps import AppConfig

class YourAppConfig(AppConfig):
    name = '...'

    def ready(self):
        import your_project.your_app.signals
</code>```

Also your app/__init__.py must include this code:

```<code>default_app_config = 'your_project.your_app.apps.YourAppConfig'
</code>```

Body:
I got a model where I would like to create a folder when a model is created:
The model:

class Drive(models.Model):
    user = models.ManyToManyField(User)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    path = models.CharField(max_length=150, editable=False,
                            default='C:/Users/User/Desktop/Python/RavNet/media/storage/drives/{}'.format(str(id)))

    def save(self):
        super().save()

I am trying to use signals, but I must admit this is my first ever attempt at making a signal not following a tutorial on point, and even after reading the documentation I am having a tough time.

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Drive
import os

@receiver(post_save, sender=Drive)
def create_drive(sender, instance, created, **kwargs):
    if created:
        os.mkdir(Drive.path)

Nothing happens when I create a new drive model via the django admin. I have tested out my code in the shell and using a placeholder path (C:/Users/User/Desktop/Python/RavNet/media/storage/drives/test) that I know works in the signal in a try to debug, and have gotten as far as realising I am having two issues.

The first: When calling the Drive.path in the shell, I am getting the path:

'C:/Users/User/Desktop/Python/RavNet/media/storage/drives/<django.db.models.fields.UUIDField>'

Instead of a path with the actual id as I hoped for. How do I solve this?

Secondly, my signal isn't working. It's like it isn't getting called. What am I doing wrong?

Body:
You must import your signals in app.py. Please check your app.py. It must be like this:

from django.apps import AppConfig

class YourAppConfig(AppConfig):
    name = '...'

    def ready(self):
        import your_project.your_app.signals

Also your app/__init__.py must include this code:

default_app_config = 'your_project.your_app.apps.YourAppConfig'


问:
Move-class does not get applied to remaining items in transition-group if other items got removed
I got an item list where each item is put in a flex-box, displaying the list like a matrix (several rows and items per row). Using <transition-group class="move"> I apply a simple move transition on the

```<code>move {
  transition: transform 1s;
}
</code>```

Now, this works perfectly when changing the order of the items or when adding new items; meaning all existing items move to their new place smoothly.

But: If I remove items from the list and some gaps occur, the existing items do NOT fill these gaps smoothly but jump to their new position without animation.

What's the reason for those existing items to behave differently, smoothly moving in their new position if a new item is put in between them but jump back without animation when the very same item is removed? How can I achieve a smooth move both ways?

答: Found the answer: Using the move transition, the -leave-active transition class must apply a position: absolute declaration, in order to take it out of the layout flow, so the siblings can -move in to place around it.

Body:
I got an item list where each item is put in a flex-box, displaying the list like a matrix (several rows and items per row). Using <transition-group class="move"> I apply a simple move transition on the

move {
  transition: transform 1s;
}

Now, this works perfectly when changing the order of the items or when adding new items; meaning all existing items move to their new place smoothly.

But: If I remove items from the list and some gaps occur, the existing items do NOT fill these gaps smoothly but jump to their new position without animation.

What's the reason for those existing items to behave differently, smoothly moving in their new position if a new item is put in between them but jump back without animation when the very same item is removed? How can I achieve a smooth move both ways?


问:
Utilize CommandLineJobRunner parameters in job XML
I believe I'm missing something very basic here. I've got a spring-batch batch job I'm modifying to take in a parameter on job run to allow for temp files to be stored in timestamped per job run temp folders. Currently all temp files sit in the same folder and if jobs run non-sequentially the temp files crash into each other.

I have a job runner bat file that I use to actually start the job, and it's creating a timestamp and appending it to the arguments passed to CommandLineJobRunner. So it runs CommandLineJobRunner.main(args) with 3 arguments:

```<code>String[] args = new String[]{[File.XML], [JobName], build.timestamp=[timestamp]}
CommandLineJobRunner.main(args)
</code>```

In my XML I have the following

```<code><bean id="tempfiledir" class="org.springframework.core.io.FileSystemResource">
    <constructor-arg value="${batch.file.drive}:/${batch.file.writer.input.root.directory}/${batch.input_file}/${build.timestamp}" />
</bean>
</code>```

The other variables there are set in my batch.properties file. They're obviously static.

From there, I pass the resource into the bean like so:

```<code><bean id="[beanTaskletID]" class="[taskletDir]">
    <property name="temporaryFilesDir" ref="tempfiledir"/>
</bean>
</code>```

And then in the actual step I have:

```<code><step id="[stepID]">
        <tasklet ref="[beanTaskletID]"/>
        <next on="FAILED" to="[failStepID]"/>
        <next on="COMPLETED" to="[completeStepID]"/>
    </step>
</code>```

Inside my tasklet I'm getting the passed parameter like so:

```<code>Resource tempDirectory;
public void setTemporaryFilesDir(Resource temporaryFilesDir) {
    this.tempDirectory = temporaryFilesDir;
}
</code>```

When I attempt to run this, I get the following error:

```<code>lassPathXmlApplicationContext [WARN] Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'tempfiledir' defined in class path resource [XML FILE]: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:211)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.processProperties(PropertySourcesPlaceholderConfigurer.java:180)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.postProcessBeanFactory(PropertySourcesPlaceholderConfigurer.java:155)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:162)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:290)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:590)
    at com.batch.myJobRunner.main(myJobRunner.java:28)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitGenericArgumentValues(BeanDefinitionVisitor.java:159)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:85)
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:208)
    ... 11 more
2020-02-14 15:49:36 CommandLineJobRunner [ERROR] Job Terminated in error: Invalid bean definition with name 'tempfiledir' defined in class path resource [XML FILE]: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.nput_file}/${build.timestamp}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'tempfiledir' defined in class path resource [XML FILE]: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:211)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.processProperties(PropertySourcesPlaceholderConfigurer.java:180)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.postProcessBeanFactory(PropertySourcesPlaceholderConfigurer.java:155)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:162)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:290)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:590)
    at com.batch.myJobRunner.main(myJobRunner.java:28)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveValue(BeanDefinitionVisitor.java:204)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitGenericArgumentValues(BeanDefinitionVisitor.java:159)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:85)
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:208)
    ... 11 more
</code>```

I thought maybe I needed a declared placeholder for the param being set, so I added the following to batch.properties:

```<code>build.timestamp=
</code>```

I had read that job params passed in on run will override any properties file setting of the same param. But when I run the job like this, build.timestamp is always just an empty string. So either that isn't the case, or the passed in param on job run isn't actually getting set anywhere.

Either that, or I just very clearly have no idea how to access a passed in parameter from a job run in the XML file. Any help for how to do this would be much appreciated. I've spent hours digging through spring-batch documentation, and nothing has indicated clearly how to access the parameter in the XML file, all it's done is noted you can do it. All the documentation I've found for accessing parameters like this successfully work by creating the job in java, rather than having it housed in XML. And clearly that's not my approach to this batch job.

答:
You can access job parameters using Spring Expression Language.

```<code>#{jobParameters['build.timestamp']}
</code>```

so bean definition will be like this. Since you are using file system resource you can directly inject file to beanTaskletID. So no need to define tempfiledir bean separately. Don't forget to add scope step.

```<code> <bean id="[beanTaskletID]" class="[taskletDir]" scope="step">
        <property name="temporaryFilesDir" value="file:${batch.file.drive}:/${batch.file.writer.input.root.directory}/${batch.input_file}/#{jobParameters['build.timestamp']}"/>
    </bean>
</code>```

Body:
I believe I'm missing something very basic here. I've got a spring-batch batch job I'm modifying to take in a parameter on job run to allow for temp files to be stored in timestamped per job run temp folders. Currently all temp files sit in the same folder and if jobs run non-sequentially the temp files crash into each other.

I have a job runner bat file that I use to actually start the job, and it's creating a timestamp and appending it to the arguments passed to CommandLineJobRunner. So it runs CommandLineJobRunner.main(args) with 3 arguments:

String[] args = new String[]{[File.XML], [JobName], build.timestamp=[timestamp]}
CommandLineJobRunner.main(args)

In my XML I have the following

<bean id="tempfiledir" class="org.springframework.core.io.FileSystemResource">
    <constructor-arg value="${batch.file.drive}:/${batch.file.writer.input.root.directory}/${batch.input_file}/${build.timestamp}" />
</bean>

The other variables there are set in my batch.properties file. They're obviously static.

From there, I pass the resource into the bean like so:

<bean id="[beanTaskletID]" class="[taskletDir]">
    <property name="temporaryFilesDir" ref="tempfiledir"/>
</bean>

And then in the actual step I have:

<step id="[stepID]">
        <tasklet ref="[beanTaskletID]"/>
        <next on="FAILED" to="[failStepID]"/>
        <next on="COMPLETED" to="[completeStepID]"/>
    </step>

Inside my tasklet I'm getting the passed parameter like so:

Resource tempDirectory;
public void setTemporaryFilesDir(Resource temporaryFilesDir) {
    this.tempDirectory = temporaryFilesDir;
}

When I attempt to run this, I get the following error:

lassPathXmlApplicationContext [WARN] Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'tempfiledir' defined in class path resource [XML FILE]: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:211)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.processProperties(PropertySourcesPlaceholderConfigurer.java:180)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.postProcessBeanFactory(PropertySourcesPlaceholderConfigurer.java:155)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:162)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:290)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:590)
    at com.batch.myJobRunner.main(myJobRunner.java:28)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitGenericArgumentValues(BeanDefinitionVisitor.java:159)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:85)
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:208)
    ... 11 more
2020-02-14 15:49:36 CommandLineJobRunner [ERROR] Job Terminated in error: Invalid bean definition with name 'tempfiledir' defined in class path resource [XML FILE]: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.nput_file}/${build.timestamp}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'tempfiledir' defined in class path resource [XML FILE]: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:211)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.processProperties(PropertySourcesPlaceholderConfigurer.java:180)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.postProcessBeanFactory(PropertySourcesPlaceholderConfigurer.java:155)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:162)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:290)
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:590)
    at com.batch.myJobRunner.main(myJobRunner.java:28)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'build.timestamp' in string value "${batch.file.drive}:/${batch.file.writer.input.root.directory}${batch.input_file}/${build.timestamp}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveValue(BeanDefinitionVisitor.java:204)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitGenericArgumentValues(BeanDefinitionVisitor.java:159)
    at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:85)
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:208)
    ... 11 more

I thought maybe I needed a declared placeholder for the param being set, so I added the following to batch.properties:

build.timestamp=

I had read that job params passed in on run will override any properties file setting of the same param. But when I run the job like this, build.timestamp is always just an empty string. So either that isn't the case, or the passed in param on job run isn't actually getting set anywhere.

Either that, or I just very clearly have no idea how to access a passed in parameter from a job run in the XML file. Any help for how to do this would be much appreciated. I've spent hours digging through spring-batch documentation, and nothing has indicated clearly how to access the parameter in the XML file, all it's done is noted you can do it. All the documentation I've found for accessing parameters like this successfully work by creating the job in java, rather than having it housed in XML. And clearly that's not my approach to this batch job.

Body:
You can access job parameters using Spring Expression Language.

#{jobParameters['build.timestamp']}

so bean definition will be like this. Since you are using file system resource you can directly inject file to beanTaskletID. So no need to define tempfiledir bean separately. Don't forget to add scope step.

 <bean id="[beanTaskletID]" class="[taskletDir]" scope="step">
        <property name="temporaryFilesDir" value="file:${batch.file.drive}:/${batch.file.writer.input.root.directory}/${batch.input_file}/#{jobParameters['build.timestamp']}"/>
    </bean>