问:
php multidimensional array search by multiple key and value
I have a PHP multidimensional  array

```<code> Array
(
  [0] => Array
    (
        [id] => 128
        [form_id] => 5
        [post_id] =>
        [date_created] => 2019-05-27 10:25:59
        [date_updated] => 2019-05-27 10:25:59
        [is_starred] => 0
        [is_read] => 0
        [ip] => 10.10.10.1
        [source_url] => https://nate.rp.cisinlive.com/?gf_page=preview&id=5
        [user_agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36
        [currency] => USD
        [payment_status] =>
        [payment_date] =>
        [payment_amount] =>
        [payment_method] =>
        [transaction_id] =>
        [is_fulfilled] =>
        [created_by] => 1
        [transaction_type] =>
        [status] => active
        [54] => family
        [59] => 24
        [69] => 24
        [75] => YToyOntpOjA7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjM2IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO31pOjE7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjI0IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO319
        [66] => 2
        [67] => AZ
        [68] => Installation 1
        [71] => apoorv
        [72] => kanungo
        [79] => Lead CYPC
        [82] => (898) 989-8989
        [83] => 89
        [78] => apoorv.k@cisinlabs.com
        [86] => Shawna Harlin-Clifton
        [87] => Army Guards Training
        [90] => 01
        [91] => 00
        [81] => United States
        [94] => test event
        [95] => 2019-05-16
        [96] => 2
        [97] => AK
        [98] => Installation 1
        [99] => Unit
        [100] => apoorv
        [101] => test
        [102] => apoorv.k@cisinlabs.com
        [103] => Lead CYPC
        [106] => United States
        [121.1] => indore
        [121.3] => indore
        [121.4] => Alaska
        [121.5] => 452001
        [121.6] => United States
        [120.1] => 1
        [120.2] => I agree to the Anchored4Life Disclaimer Sentence
        [120.3] => 2
        [58] =>
        [55] =>
        [2] =>
        [57] =>
        [63] =>
        [123] =>
        [61] =>
        [74] =>
        [108] =>
        [60] =>
        [76] =>
        [77] =>
        [124] =>
        [80] =>
        [84] =>
        [126] =>
        [128] =>
        [104] =>
        [129] =>
        [121.2] =>
        [127] =>
        [125] =>
    )

[1] => Array
    (
        [id] => 127
        [form_id] => 5
        [post_id] =>
        [date_created] => 2019-05-24 23:24:52
        [date_updated] => 2019-05-24 23:24:52
        [is_starred] => 0
        [is_read] => 0
        [ip] => 207.255.5.251
        [source_url] => https://nate.rp.cisinlive.com/family-order-2/
        [user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
        [currency] => USD
        [payment_status] =>
        [payment_date] =>
        [payment_amount] =>
        [payment_method] =>
        [transaction_id] =>
        [is_fulfilled] =>
        [created_by] => 1
        [transaction_type] =>
        [status] => active
        [54] => family
        [59] => 24
        [69] => 24
        [75] => YToxOntpOjA7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjM2IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjI6IjU0Ijt9fQ==
        [67] => AL
        [68] => Installation 2
        [71] => Nate
        [72] => Seidel
        [79] => Other
        [82] => (234) 343-2432
        [78] => nate@simcloud.com
        [81] => United States
        [121.6] => United States
        [58] =>
        [55] =>
        [2] =>
        [57] =>
        [63] =>
        [123] =>
        [61] =>
        [74] =>
        [108] =>
        [60] =>
        [76] =>
        [77] =>
        [124] =>
        [66] =>
        [80] =>
        [83] =>
        [84] =>
        [86] =>
        [87] =>
        [90] =>
        [91] =>
        [126] =>
        [128] =>
        [94] =>
        [95] =>
        [96] =>
        [97] =>
        [98] =>
        [99] =>
        [100] =>
        [101] =>
        [102] =>
        [103] =>
        [104] =>
        [106] =>
        [129] =>
        [121.1] =>
        [121.2] =>
        [121.3] =>
        [121.4] =>
        [121.5] =>
        [127] =>
        [120.1] =>
        [120.2] =>
        [120.3] =>
        [125] =>
    )

[2] => Array
    (
        [id] => 126
        [form_id] => 5
        [post_id] =>
        [date_created] => 2019-05-24 09:58:35
        [date_updated] => 2019-05-24 09:58:35
        [is_starred] => 0
        [is_read] => 0
        [ip] => 10.10.10.1
        [source_url] => https://nate.rp.cisinlive.com/?gf_page=preview&id=5
        [user_agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36
        [currency] => USD
        [payment_status] =>
        [payment_date] =>
        [payment_amount] =>
        [payment_method] =>
        [transaction_id] =>
        [is_fulfilled] =>
        [created_by] => 1
        [transaction_type] =>
        [status] => active
        [54] => family
        [59] => 24
        [69] => 24
        [75] => YToyOntpOjA7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjM2IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO31pOjE7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjI0IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO319
        [66] => 2
        [67] => AK
        [68] => Installation 2
        [71] => apoorv
        [72] => test
        [79] => Lead CYPC
        [82] => (898) 998-9898
        [83] => 898989
        [84] => (898) 989-8989
        [78] => apoorv.k@cisinlabs.com
        [86] => Shawna Harlin-Clifton
        [87] => Army Guards Training
        [90] => 00
        [91] => 00
        [94] => test
        [95] => 2019-05-23
        [96] => 2
        [97] => AL
        [98] => Installation 1
        [99] => Unit
        [100] => apoorv
        [101] => test
        [102] => apoorv.k@cisinlabs.com
        [103] => Lead CYPC
        [106] => United States
        [121.1] => indore
        [121.3] => indore
        [121.5] => 452001
        [121.6] => United States
        [120.1] => 1
        [120.2] => I agree to the Anchored4Life Disclaimer Sentence
        [120.3] => 2
        [58] =>
        [55] =>
        [2] =>
        [57] =>
        [63] =>
        [123] =>
        [61] =>
        [74] =>
        [108] =>
        [60] =>
        [76] =>
        [77] =>
        [124] =>
        [80] =>
        [81] =>
        [126] =>
        [128] =>
        [104] =>
        [129] =>
        [121.2] =>
        [121.4] =>
        [127] =>
        [125] =>
    ) )
</code>```

And I would like to search in this array using the multiple key and pair

Currently, I am using the function

```<code>function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
    // This function will search the revisions for a certain value
    // related to the associative key you are looking for.
    $keys = array();
    foreach ($dataArray as $key => $cur_value) {
        if ($cur_value[$key_to_search] == $search_value) {
            if (isset($other_matching_key) && isset($other_matching_value)) {
                if ($cur_value[$other_matching_key] == $other_matching_value) {
                    $keys[] = $key;
                }
            } else {
                // I must keep in mind that some searches may have multiple
                // matches and others would not, so leave it open with no continues.
                $keys[] = $key;
            }
        }
    }
    return $keys;
}
</code>```

borrowed from @amurrell answer here PHP multidimensional array search by value

This Function works well for two key-value pair and return the index of the array But I want to search by multiple keys and pair 4 and maybe five of the key and value pair

I want a function like

```<code>search_by_value($array,$first_key,$first_value,$second_key=null,$second_value=null,$third_key=null,$third_value=null,$fourth_key=null,$fourth_value=null);
</code>```

Or more like

```<code>search_by_value(array('$key',$value));
</code>```

and the output should be index matching the key value

```<code>    Array
(
    [0] => 5
)
</code>```

or if it matches multiple values

```<code>    Array
(
    [0] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

)
</code>```

答:
You can create a associative array and test if all the key/values in that associative array exist in the main array</p>

```<code>function search_by_values($array,$searchValues) {
$keys = [];
foreach($array as $key => $value) {//loop each array value
      $isInArray = false;//
      foreach($searchValues as $searchKey => $searchValue) {//loop the search array
         if($value[$searchKey] != $searchValue) {//test if the key value pair is in the array
              $isInArray = false;//the value of the key doesn't match
               break;//we exit the inner loop with  $isInArray = false
         } else {
            $isInArray = true;//if all the values are in the array we will exit with  $isInArray = true;
         }
      }
      if($isInArray) {
        $keys[] = $key;
      }
}
return $keys;

}
</code>```

Body:
I have a PHP multidimensional  array

 Array
(
  [0] => Array
    (
        [id] => 128
        [form_id] => 5
        [post_id] =>
        [date_created] => 2019-05-27 10:25:59
        [date_updated] => 2019-05-27 10:25:59
        [is_starred] => 0
        [is_read] => 0
        [ip] => 10.10.10.1
        [source_url] => https://nate.rp.cisinlive.com/?gf_page=preview&id=5
        [user_agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36
        [currency] => USD
        [payment_status] =>
        [payment_date] =>
        [payment_amount] =>
        [payment_method] =>
        [transaction_id] =>
        [is_fulfilled] =>
        [created_by] => 1
        [transaction_type] =>
        [status] => active
        [54] => family
        [59] => 24
        [69] => 24
        [75] => YToyOntpOjA7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjM2IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO31pOjE7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjI0IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO319
        [66] => 2
        [67] => AZ
        [68] => Installation 1
        [71] => apoorv
        [72] => kanungo
        [79] => Lead CYPC
        [82] => (898) 989-8989
        [83] => 89
        [78] => apoorv.k@cisinlabs.com
        [86] => Shawna Harlin-Clifton
        [87] => Army Guards Training
        [90] => 01
        [91] => 00
        [81] => United States
        [94] => test event
        [95] => 2019-05-16
        [96] => 2
        [97] => AK
        [98] => Installation 1
        [99] => Unit
        [100] => apoorv
        [101] => test
        [102] => apoorv.k@cisinlabs.com
        [103] => Lead CYPC
        [106] => United States
        [121.1] => indore
        [121.3] => indore
        [121.4] => Alaska
        [121.5] => 452001
        [121.6] => United States
        [120.1] => 1
        [120.2] => I agree to the Anchored4Life Disclaimer Sentence
        [120.3] => 2
        [58] =>
        [55] =>
        [2] =>
        [57] =>
        [63] =>
        [123] =>
        [61] =>
        [74] =>
        [108] =>
        [60] =>
        [76] =>
        [77] =>
        [124] =>
        [80] =>
        [84] =>
        [126] =>
        [128] =>
        [104] =>
        [129] =>
        [121.2] =>
        [127] =>
        [125] =>
    )

[1] => Array
    (
        [id] => 127
        [form_id] => 5
        [post_id] =>
        [date_created] => 2019-05-24 23:24:52
        [date_updated] => 2019-05-24 23:24:52
        [is_starred] => 0
        [is_read] => 0
        [ip] => 207.255.5.251
        [source_url] => https://nate.rp.cisinlive.com/family-order-2/
        [user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
        [currency] => USD
        [payment_status] =>
        [payment_date] =>
        [payment_amount] =>
        [payment_method] =>
        [transaction_id] =>
        [is_fulfilled] =>
        [created_by] => 1
        [transaction_type] =>
        [status] => active
        [54] => family
        [59] => 24
        [69] => 24
        [75] => YToxOntpOjA7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjM2IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjI6IjU0Ijt9fQ==
        [67] => AL
        [68] => Installation 2
        [71] => Nate
        [72] => Seidel
        [79] => Other
        [82] => (234) 343-2432
        [78] => nate@simcloud.com
        [81] => United States
        [121.6] => United States
        [58] =>
        [55] =>
        [2] =>
        [57] =>
        [63] =>
        [123] =>
        [61] =>
        [74] =>
        [108] =>
        [60] =>
        [76] =>
        [77] =>
        [124] =>
        [66] =>
        [80] =>
        [83] =>
        [84] =>
        [86] =>
        [87] =>
        [90] =>
        [91] =>
        [126] =>
        [128] =>
        [94] =>
        [95] =>
        [96] =>
        [97] =>
        [98] =>
        [99] =>
        [100] =>
        [101] =>
        [102] =>
        [103] =>
        [104] =>
        [106] =>
        [129] =>
        [121.1] =>
        [121.2] =>
        [121.3] =>
        [121.4] =>
        [121.5] =>
        [127] =>
        [120.1] =>
        [120.2] =>
        [120.3] =>
        [125] =>
    )

[2] => Array
    (
        [id] => 126
        [form_id] => 5
        [post_id] =>
        [date_created] => 2019-05-24 09:58:35
        [date_updated] => 2019-05-24 09:58:35
        [is_starred] => 0
        [is_read] => 0
        [ip] => 10.10.10.1
        [source_url] => https://nate.rp.cisinlive.com/?gf_page=preview&id=5
        [user_agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36
        [currency] => USD
        [payment_status] =>
        [payment_date] =>
        [payment_amount] =>
        [payment_method] =>
        [transaction_id] =>
        [is_fulfilled] =>
        [created_by] => 1
        [transaction_type] =>
        [status] => active
        [54] => family
        [59] => 24
        [69] => 24
        [75] => YToyOntpOjA7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjM2IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO31pOjE7YToyOntzOjEwOiJwcm9kdWN0X2lkIjtzOjI6IjI0IjtzOjE2OiJwcm9kdWN0X3F1YW50aXR5IjtzOjE6IjEiO319
        [66] => 2
        [67] => AK
        [68] => Installation 2
        [71] => apoorv
        [72] => test
        [79] => Lead CYPC
        [82] => (898) 998-9898
        [83] => 898989
        [84] => (898) 989-8989
        [78] => apoorv.k@cisinlabs.com
        [86] => Shawna Harlin-Clifton
        [87] => Army Guards Training
        [90] => 00
        [91] => 00
        [94] => test
        [95] => 2019-05-23
        [96] => 2
        [97] => AL
        [98] => Installation 1
        [99] => Unit
        [100] => apoorv
        [101] => test
        [102] => apoorv.k@cisinlabs.com
        [103] => Lead CYPC
        [106] => United States
        [121.1] => indore
        [121.3] => indore
        [121.5] => 452001
        [121.6] => United States
        [120.1] => 1
        [120.2] => I agree to the Anchored4Life Disclaimer Sentence
        [120.3] => 2
        [58] =>
        [55] =>
        [2] =>
        [57] =>
        [63] =>
        [123] =>
        [61] =>
        [74] =>
        [108] =>
        [60] =>
        [76] =>
        [77] =>
        [124] =>
        [80] =>
        [81] =>
        [126] =>
        [128] =>
        [104] =>
        [129] =>
        [121.2] =>
        [121.4] =>
        [127] =>
        [125] =>
    ) )

And I would like to search in this array using the multiple key and pair

Currently, I am using the function

function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
    // This function will search the revisions for a certain value
    // related to the associative key you are looking for.
    $keys = array();
    foreach ($dataArray as $key => $cur_value) {
        if ($cur_value[$key_to_search] == $search_value) {
            if (isset($other_matching_key) && isset($other_matching_value)) {
                if ($cur_value[$other_matching_key] == $other_matching_value) {
                    $keys[] = $key;
                }
            } else {
                // I must keep in mind that some searches may have multiple
                // matches and others would not, so leave it open with no continues.
                $keys[] = $key;
            }
        }
    }
    return $keys;
}

borrowed from @amurrell answer here PHP multidimensional array search by value

This Function works well for two key-value pair and return the index of the array But I want to search by multiple keys and pair 4 and maybe five of the key and value pair

I want a function like

search_by_value($array,$first_key,$first_value,$second_key=null,$second_value=null,$third_key=null,$third_value=null,$fourth_key=null,$fourth_value=null);

Or more like

search_by_value(array('$key',$value));

and the output should be index matching the key value

    Array
(
    [0] => 5
)

or if it matches multiple values

    Array
(
    [0] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

)

Body:
You can create a associative array and test if all the key/values in that associative array exist in the main array

function search_by_values($array,$searchValues) {
$keys = [];
foreach($array as $key => $value) {//loop each array value
      $isInArray = false;//
      foreach($searchValues as $searchKey => $searchValue) {//loop the search array
         if($value[$searchKey] != $searchValue) {//test if the key value pair is in the array
              $isInArray = false;//the value of the key doesn't match
               break;//we exit the inner loop with  $isInArray = false
         } else {
            $isInArray = true;//if all the values are in the array we will exit with  $isInArray = true;
         }
      }
      if($isInArray) {
        $keys[] = $key;
      }
}
return $keys;

}


来源: stackexchange

问:
MathNet.Numerics.LinearAlgebra: how to append a Vector to another quickly?
I'm converting an algorithm from Matlab to C#.

At a certain point, there's this new vector in the matlab code:

```<code>F = [D * z + v; m1 + rgb];
</code>```

D is a 36x36 matrix, z and v are 36x1 vectors, m1 and rgb are 3x1 vectors. This means that F is a 39x1 vector.

Now, when converting this code to C# using MathNet, I found out that, apparently, there's no append function, and the best that I could come to is this code:

var F = Vector<float>.Build.Dense(39);
var firstElements = Vector<float>.Build.Dense(36);
var lastElements = Vector<float>.Build.Dense(3);
firstElements = D * z + v;
lastElements = m1 + rgb;
firstElements.CopySubVectorTo(F, 0, 0, firstElements.Count);
lastElements.CopySubVectorTo(F, 0, firstElements.Count, lastElements.Count);
```

Is there a quicker way to create the F vector?

答:
Not especially pretty, but this would work:

```<code>F = firstElements.ToColumnMatrix().Stack(lastElements.ToColumnMatrix()).Column(0);
</code>```

It would probably be a good feature to add, a function to Stack 2 vectors.

ContentLicense: CC BY-SA 4.0

Body:
I'm converting an algorithm from Matlab to C#.

At a certain point, there's this new vector in the matlab code:

F = [D * z + v; m1 + rgb];

D is a 36x36 matrix, z and v are 36x1 vectors, m1 and rgb are 3x1 vectors. This means that F is a 39x1 vector.

Now, when converting this code to C# using MathNet, I found out that, apparently, there's no append function, and the best that I could come to is this code:

var F = Vector<float>.Build.Dense(39);
var firstElements = Vector<float>.Build.Dense(36);
var lastElements = Vector<float>.Build.Dense(3);
firstElements = D * z + v;
lastElements = m1 + rgb;
firstElements.CopySubVectorTo(F, 0, 0, firstElements.Count);
lastElements.CopySubVectorTo(F, 0, firstElements.Count, lastElements.Count);

Is there a quicker way to create the F vector?

Body:
Not especially pretty, but this would work:

F = firstElements.ToColumnMatrix().Stack(lastElements.ToColumnMatrix()).Column(0);

It would probably be a good feature to add, a function to Stack 2 vectors.


问:
How to do "docker load" for multiple tar files
I have list of .tar docker image files , I have tried loading docker images using below commands

docker load -i *.tar

docker load -i alldockerimages.tar

where alldockerimages.tar contains all individual tar files .

Let me know how we can load multiple tar files.

答:
Use the script described in save-load-docker-images.sh to save or load the images. For your case it would be </p>

```<code>./save-load-docker-images.sh load -d <directory-location>
</code>```

Body:
Use the script described in save-load-docker-images.sh to save or load the images. For your case it would be

./save-load-docker-images.sh load -d <directory-location>


问:
pandoc lua filter to replace tex macro
I am trying to write a pandoc lua filter to replace the \ce{} command from the latex package mhchem.

This is what I tried with the example of \ce{NO3-}, but it doesn't work and renders a blank in the rtf output file:

return {
  {
    Str = function (elem)
      if elem.text == "\\ce%{%NO3-%}%" then
        return {pandoc.Str "NO3"}
      else
        return elem
      end
    end,
  }
}
```

<p>My pandoc command is:</p>

<pre class="lang-sh prettyprint-override"><code>pandoc -s myfile.tex --lua-filter myfilter.lua -o myfile.rtf
</code>```

答:
The main issue here is how pandoc handles these mhchem snippets: pandoc, by default, drops all LaTeX code which it cannot parse. Example:

$ printf 'Nitrate (\\ce{NO3-})' | pandoc --from latex -t native
[Para [Str "Nitrate",Space,Str "()"]]
```

<p>We want to keep those snippets, which we can by using the <code>raw_tex</code> extension:</p>

<pre class="lang-none prettyprint-override"><code>$ printf 'Nitrate (\\ce{NO3-})' | pandoc --from latex+raw_tex -t native
[Para [Str "Nitrate",Space,Str "(",RawInline (Format "latex") "\\ce{NO3-}",Str ")"]]
</code>```

Now we have a chance of matching this text.  As we can see, we need to match on RawInline elements instead of Str:

return {
  {
    RawInline = function (raw)
      local formula = raw.text:match '\\ce{([^ ]+)}'
      if raw.format == 'latex' and formula then
        return pandoc.Str(formula)
      end
    end
  }
}
```

<p>Which will remove the tex command and render the raw code inside.
To match the initial example:</p>

<pre class="lang-lua prettyprint-override"><code>return {
  {
    RawInline = function (raw)
      local formula = raw.text:match '\\ce{NO3%-}'
      if raw.format == 'latex' and formula then
        return pandoc.Str('NO3')
      end
    end
  }
}
</code>```

Finally, the pandoc command is:

pandoc --from latex+raw_tex -s myfile.tex --lua-filter myfilter.lua -o myfile.rtf
```

The pattern used for matching wasn't quite correct, as @PaulKulchenko noted. See "Patterns" section of the Lua reference manual.

Title: pandoc lua filter to replace tex macro

Body:
I am trying to write a pandoc lua filter to replace the \ce{} command from the latex package mhchem.

This is what I tried with the example of \ce{NO3-}, but it doesn't work and renders a blank in the rtf output file:

return {
  {
    Str = function (elem)
      if elem.text == "\\ce%{%NO3-%}%" then
        return {pandoc.Str "NO3"}
      else
        return elem
      end
    end,
  }
}

My pandoc command is:

pandoc -s myfile.tex --lua-filter myfilter.lua -o myfile.rtf

Body:
The main issue here is how pandoc handles these mhchem snippets: pandoc, by default, drops all LaTeX code which it cannot parse. Example:

$ printf 'Nitrate (\\ce{NO3-})' | pandoc --from latex -t native
[Para [Str "Nitrate",Space,Str "()"]]

We want to keep those snippets, which we can by using the raw_tex extension:

$ printf 'Nitrate (\\ce{NO3-})' | pandoc --from latex+raw_tex -t native
[Para [Str "Nitrate",Space,Str "(",RawInline (Format "latex") "\\ce{NO3-}",Str ")"]]

Now we have a chance of matching this text.  As we can see, we need to match on RawInline elements instead of Str:

return {
  {
    RawInline = function (raw)
      local formula = raw.text:match '\\ce{([^ ]+)}'
      if raw.format == 'latex' and formula then
        return pandoc.Str(formula)
      end
    end
  }
}

Which will remove the tex command and render the raw code inside.
To match the initial example:

return {
  {
    RawInline = function (raw)
      local formula = raw.text:match '\\ce{NO3%-}'
      if raw.format == 'latex' and formula then
        return pandoc.Str('NO3')
      end
    end
  }
}

Finally, the pandoc command is:

pandoc --from latex+raw_tex -s myfile.tex --lua-filter myfilter.lua -o myfile.rtf

The pattern used for matching wasn't quite correct, as @PaulKulchenko noted. See "Patterns" section of the Lua reference manual.


问:
How to Color Code Gridview based on date values
I would like to allow my Gridview control to display various colours based on conditions. A person has a date for a medical. I want the gridview to show a green color when the day has arrived. I want the date to show red when one day has passed on from the due date and orange like 7 days before the medical date. I have only managed to fix it for the green color which shows the medical on the day but I am having difficulties for the other conditions.

This is what i currently have. The first part of the If Statement works when i change the row to green based on the due date and the current date that is equal but I do not know how to set the if statement for the other conditions mentioned above. Please assist

```<code> If e.Row.RowType = DataControlRowType.DataRow Then

            Dim row As DataRow = (CType(e.Row.DataItem, DataRowView)).Row
            Dim DueDate As DateTime = row.Field(Of DateTime)(7)

            If DueDate.Date = DateTime.Today Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Green
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Green
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Green
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Green
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Green
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Green
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Green
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Green
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Green
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Green
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Green
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Green
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Green
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Green
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            ElseIf Day(DateTime.Now) > 1 Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            End If

        End If

</code>```

答:
You can use code behind method as follows:

Add the template column in GridView like this:

```<code><asp:TemplateField HeaderText="Due Date">
    <ItemTemplate>
        <asp:Label ID="Label4" runat="server" Text='<%# Eval("DueDate") %>'
            Style='<%# GetColorStyles(0, Eval("DueDate"))%>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>
</code>```

and use the following method for each cell:

```<code>Function GetColorStyles(ByVal cellindex As String, ByVal DueDate As DateTime) As String
    Dim RES As String = "color:#000000" 'default color
    If DueDate.Date = DateTime.Today Then
        RES = "color:#00FF00"
    ElseIf Day(DateTime.Now) > 1 Then
        RES = "color:#FF0000;"
    End If
    Return RES
End Function
</code>```

Body:
I would like to allow my Gridview control to display various colours based on conditions. A person has a date for a medical. I want the gridview to show a green color when the day has arrived. I want the date to show red when one day has passed on from the due date and orange like 7 days before the medical date. I have only managed to fix it for the green color which shows the medical on the day but I am having difficulties for the other conditions.

This is what i currently have. The first part of the If Statement works when i change the row to green based on the due date and the current date that is equal but I do not know how to set the if statement for the other conditions mentioned above. Please assist

 If e.Row.RowType = DataControlRowType.DataRow Then

            Dim row As DataRow = (CType(e.Row.DataItem, DataRowView)).Row
            Dim DueDate As DateTime = row.Field(Of DateTime)(7)

            If DueDate.Date = DateTime.Today Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Green
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Green
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Green
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Green
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Green
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Green
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Green
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Green
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Green
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Green
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Green
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Green
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Green
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Green
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            ElseIf Day(DateTime.Now) > 1 Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            End If

        End If

Body:
You can use code behind method as follows:

Add the template column in GridView like this:

<asp:TemplateField HeaderText="Due Date">
    <ItemTemplate>
        <asp:Label ID="Label4" runat="server" Text='<%# Eval("DueDate") %>'
            Style='<%# GetColorStyles(0, Eval("DueDate"))%>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

and use the following method for each cell:

Function GetColorStyles(ByVal cellindex As String, ByVal DueDate As DateTime) As String
    Dim RES As String = "color:#000000" 'default color
    If DueDate.Date = DateTime.Today Then
        RES = "color:#00FF00"
    ElseIf Day(DateTime.Now) > 1 Then
        RES = "color:#FF0000;"
    End If
    Return RES
End Function


问:
How to use SQL using Active Record
I am trying to optimise the performance of a query in Active Record. Previously I would do two SQL queries and it should be possible to do it in one.

These are the tables that I am running the queries on:

```<code># Table name: notifications
#
#  id         :integer          not null, primary key
#  content    :text(65535)
#  position   :integer

# Table name: dismissed_notifications
#
#  id              :integer          not null, primary key
#  notification_id :integer
#  user_id         :integer
</code>```

This is the existing query:

```<code>where.not(id: user.dismissed_notifications.pluck(:id))
</code>```

which produces:

```<code>SELECT `dismissed_notifications`.`id` FROM `dismissed_notifications` WHERE `dismissed_notifications`.`user_id` = 655

SELECT  `notifications`.* FROM `notifications` WHERE (`notifications`.`id` != 1)
</code>```

This is the SQL I would like to get, which returns the same records:

```<code>select *
from notifications n
where not exists(
    select 1
    from dismissed_notifications dn
    where dn.id = n.id
      and dn.user_id = 655)
</code>```

答:
You can write not exists Query like below

```<code>where('NOT EXISTS (' + user.dismissed_notifications.where('dismissed_notifications.id = notifications.id').to_sql + ')')
</code>```

OR

There is also another way to reduce the number of queries is use select instead of pluck, it will create sub-query instead pulling records from database. Rails ActiveRecord Subqueries

```<code>where.not(id: user.dismissed_notifications.select(:id))
</code>```

Which will generate below SQL query

```<code>SELECT  `notifications`.*
  FROM `notifications`
  WHERE (
    `notifications`.`id` NOT IN
      (SELECT `dismissed_notifications`.`id`
        FROM `dismissed_notifications`
        WHERE `dismissed_notifications`.`user_id` = 655
      )
  )
</code>```

Title: How to use SQL using Active Record

Body:
I am trying to optimise the performance of a query in Active Record. Previously I would do two SQL queries and it should be possible to do it in one.

These are the tables that I am running the queries on:

# Table name: notifications
#
#  id         :integer          not null, primary key
#  content    :text(65535)
#  position   :integer

# Table name: dismissed_notifications
#
#  id              :integer          not null, primary key
#  notification_id :integer
#  user_id         :integer

This is the existing query:

where.not(id: user.dismissed_notifications.pluck(:id))

which produces:

SELECT `dismissed_notifications`.`id` FROM `dismissed_notifications` WHERE `dismissed_notifications`.`user_id` = 655

SELECT  `notifications`.* FROM `notifications` WHERE (`notifications`.`id` != 1)

This is the SQL I would like to get, which returns the same records:

select *
from notifications n
where not exists(
    select 1
    from dismissed_notifications dn
    where dn.id = n.id
      and dn.user_id = 655)

Body:
You can write not exists Query like below

where('NOT EXISTS (' + user.dismissed_notifications.where('dismissed_notifications.id = notifications.id').to_sql + ')')

OR

There is also another way to reduce the number of queries is use select instead of pluck, it will create sub-query instead pulling records from database. Rails ActiveRecord Subqueries

where.not(id: user.dismissed_notifications.select(:id))

Which will generate below SQL query

SELECT  `notifications`.*
  FROM `notifications`
  WHERE (
    `notifications`.`id` NOT IN
      (SELECT `dismissed_notifications`.`id`
        FROM `dismissed_notifications`
        WHERE `dismissed_notifications`.`user_id` = 655
      )
  )


问:
How to use Slick carousel slider?
I really want to be able to use the slick carousel slider by Ken Wheeler, but having difficulties understanding how to use it. i followed the instructions on Ken Wheeler's github but nothing is happening! Can anyone point out where i am going wrong? I have used a couple of tutorials online but still can not get it to work!

  <title>My Now Amazing Webpage</title>
    <link rel="stylesheet" type="text/css" href="slick/slick.css"/>
    <link rel="stylesheet" type="text/css" href="slick/slick-theme.css"/>

 Slide  1

 Slide  2

 Slide  3

  ```

答:
```<code>$(document).ready(function(){
   $('.demo').slick();
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use Slick carousel slider?


问:
Oracle dbms_scheduler error with BYTIME
I was trying to get a job run every business day (MON to SAT) at 6:30am which the Oracle scheduler refused with

ORA-27419 "unable to determine valid execution date from repeat
  interval"

I started losing my mind when i discovered the following behaviour:

First, create a dummy job. Note that it has no schedule and is not enabled.

```<code>BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
            job_name => '"TMP_DUMMY"',
            job_type => 'PLSQL_BLOCK',
            job_action => 'begin
                              dbms_lock.sleep(5);
                           end;',
            number_of_arguments => 0,
            start_date => NULL,
            end_date => NULL,
            enabled => FALSE,
            auto_drop => FALSE,
            comments => 'Test Job');

    DBMS_SCHEDULER.SET_ATTRIBUTE(
             name => '"TMP_DUMMY"', attribute => 'store_output', value => TRUE);
    DBMS_SCHEDULER.SET_ATTRIBUTE( name => '"TMP_DUMMY"',    attribute => 'logging_level', value => DBMS_SCHEDULER.LOGGING_OFF);

END;
/
</code>```

Next step, set a repeat_interval using BYTIME with any execution time which is equal to or less than 02:55 (MI:SS) after the full hour. It does not matter whether this is done with or without the Hour part and for the former option the exact hour does not matter as well.

```<code>BEGIN
   DBMS_SCHEDULER.set_attribute( name => '"TMP_DUMMY"', attribute => 'repeat_interval', value => 'FREQ=DAILY;BYTIME=010255');
   DBMS_SCHEDULER.enable(name=>'"TMP_DUMMY"');
END;
/
</code>```

This works perfectly fine for me.

Now i want to increase the BYTIME by 1 second to 02:56 (MI:SS)

```<code>BEGIN
   DBMS_SCHEDULER.set_attribute( name => '"TMP_DUMMY"', attribute => 'repeat_interval', value => 'FREQ=DAILY;BYTIME=010256');
END;
/
</code>```

Running this attribute change i get

ORA-27470: failed to re-enable "[schema]"."TMP_DUMMY" after making requested change
  ORA-27419: unable to determined valid execution date from repeat interval

I have verified this behaviour for all MI:SS combinations:

```<code>set serveroutput on
DECLARE
  l_rep_interval VARCHAR2(50 CHAR);
BEGIN
FOR mi IN 0..59
LOOP
  FOR ss IN 0..59
  LOOP
    l_rep_interval := 'FREQ=DAILY;BYTIME='||lpad(to_char(mi*100+ss),4,'0');
    DBMS_SCHEDULER.set_attribute( name => '"TMP_DUMMY"', attribute => 'repeat_interval', value => l_rep_interval);
    DBMS_SCHEDULER.enable(name=>'"TMP_DUMMY"');
    DBMS_OUTPUT.PUT_LINE(l_rep_interval);
  END LOOP; --end ss
END LOOP; --end mi

EXCEPTION WHEN OTHERS THEN NULL;

END;
/
</code>```

It is working properly from 00:00 until 02:55 and fails for all other times.
For me this looks like the MI:SS part is treated as a tinyint and higher values cause a type overflow.

Is this a Bug in the scheduler or am i missing something here?
Oracle version is 12c.

答:
I just ran into this same issue. It looks like (from the documentation) that BYTIME is not recognised (even though SQLDeveloper uses it if you look at the SQL tab of the job GUI)

I found that the following works using BYMinute and ByHour

DBMS_SCHEDULER.set_attribute( name => '"TEST"."JOB"', attribute => 'repeat_interval', value => 'FREQ=DAILY;BYHOUR=9;BYMINUTE=30;BYDAY=MON,TUE,WED,THU,FRI,SAT,SUN');

Hope this helps someone.

Title: Oracle dbms_scheduler error with BYTIME

Body:
I was trying to get a job run every business day (MON to SAT) at 6:30am which the Oracle scheduler refused with

ORA-27419 "unable to determine valid execution date from repeat
  interval"

I started losing my mind when i discovered the following behaviour:

First, create a dummy job. Note that it has no schedule and is not enabled.

BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
            job_name => '"TMP_DUMMY"',
            job_type => 'PLSQL_BLOCK',
            job_action => 'begin
                              dbms_lock.sleep(5);
                           end;',
            number_of_arguments => 0,
            start_date => NULL,
            end_date => NULL,
            enabled => FALSE,
            auto_drop => FALSE,
            comments => 'Test Job');

    DBMS_SCHEDULER.SET_ATTRIBUTE(
             name => '"TMP_DUMMY"', attribute => 'store_output', value => TRUE);
    DBMS_SCHEDULER.SET_ATTRIBUTE( name => '"TMP_DUMMY"',    attribute => 'logging_level', value => DBMS_SCHEDULER.LOGGING_OFF);

END;
/

Next step, set a repeat_interval using BYTIME with any execution time which is equal to or less than 02:55 (MI:SS) after the full hour. It does not matter whether this is done with or without the Hour part and for the former option the exact hour does not matter as well.

BEGIN
   DBMS_SCHEDULER.set_attribute( name => '"TMP_DUMMY"', attribute => 'repeat_interval', value => 'FREQ=DAILY;BYTIME=010255');
   DBMS_SCHEDULER.enable(name=>'"TMP_DUMMY"');
END;
/

This works perfectly fine for me.

Now i want to increase the BYTIME by 1 second to 02:56 (MI:SS)

BEGIN
   DBMS_SCHEDULER.set_attribute( name => '"TMP_DUMMY"', attribute => 'repeat_interval', value => 'FREQ=DAILY;BYTIME=010256');
END;
/

Running this attribute change i get

ORA-27470: failed to re-enable "[schema]"."TMP_DUMMY" after making requested change
  ORA-27419: unable to determined valid execution date from repeat interval

I have verified this behaviour for all MI:SS combinations:

set serveroutput on
DECLARE
  l_rep_interval VARCHAR2(50 CHAR);
BEGIN
FOR mi IN 0..59
LOOP
  FOR ss IN 0..59
  LOOP
    l_rep_interval := 'FREQ=DAILY;BYTIME='||lpad(to_char(mi*100+ss),4,'0');
    DBMS_SCHEDULER.set_attribute( name => '"TMP_DUMMY"', attribute => 'repeat_interval', value => l_rep_interval);
    DBMS_SCHEDULER.enable(name=>'"TMP_DUMMY"');
    DBMS_OUTPUT.PUT_LINE(l_rep_interval);
  END LOOP; --end ss
END LOOP; --end mi

EXCEPTION WHEN OTHERS THEN NULL;

END;
/

It is working properly from 00:00 until 02:55 and fails for all other times.
For me this looks like the MI:SS part is treated as a tinyint and higher values cause a type overflow.

Is this a Bug in the scheduler or am i missing something here?
Oracle version is 12c.


问:
Dependency Injection on Class Instantiated Elsewhere
I am trying to inject ehcache via the Play Framework. I am injecting it into a companion class, but that class is being instantiated in an abstract class elsewhere as well as the companion object. I do not want to inject anything into the abstract class because it is being used elsewhere.

For example, this is basically how the companion class and object are set up (removed some logic and extensions for better readability):

class Setting @Inject()(cached: DefaultSyncCacheApi) {
   def isCached(id:String): Boolean = {
       val cachedItem = cached.get(id)
       cachedItem.isDefined
   }
}

object Setting {
   def getId(id:String): Setting = {
      val setting = new Setting //I know this doesn't work
      if (setting.isCached(id)) {
          //retrieval logic
      }
      setting
   }
}
```

<p>This is the abstract class where it is being instantiated: </p>

<pre class="lang-scala prettyprint-override"><code>abstract class UsingSettingAbstract {
   def methodUsingSetting(): String = {
       val setting = new Setting
       val str = new String
       //logic in here
       str
   }
}
</code>```

I have tried to create an empty constructor in the Setting class with def this() { }, and creating a chain of constructors, but have so far been unsuccessful in getting the cache to be successfully injected.

I did different versions of below, initializing the cache variable with cached or trying to pass through cached:

class Setting @Inject()(cached: DefaultSyncCacheApi) {
   val cache:DefaultSyncCacheApi
   def this() {
      this(cache)
   }
}
```

Is there a way to get DI to work with this setup, or would something like a factory pattern work better?

答:
With guice you can pass any created instance to the injectors "requestInjection()" method. This will trigger method and field injection on that instance.

So as long as you have access to the injector, you can get injections done.

Body:
I am trying to inject ehcache via the Play Framework. I am injecting it into a companion class, but that class is being instantiated in an abstract class elsewhere as well as the companion object. I do not want to inject anything into the abstract class because it is being used elsewhere.

For example, this is basically how the companion class and object are set up (removed some logic and extensions for better readability):

class Setting @Inject()(cached: DefaultSyncCacheApi) {
   def isCached(id:String): Boolean = {
       val cachedItem = cached.get(id)
       cachedItem.isDefined
   }
}

object Setting {
   def getId(id:String): Setting = {
      val setting = new Setting //I know this doesn't work
      if (setting.isCached(id)) {
          //retrieval logic
      }
      setting
   }
}

This is the abstract class where it is being instantiated:

abstract class UsingSettingAbstract {
   def methodUsingSetting(): String = {
       val setting = new Setting
       val str = new String
       //logic in here
       str
   }
}

I have tried to create an empty constructor in the Setting class with def this() { }, and creating a chain of constructors, but have so far been unsuccessful in getting the cache to be successfully injected.

I did different versions of below, initializing the cache variable with cached or trying to pass through cached:

class Setting @Inject()(cached: DefaultSyncCacheApi) {
   val cache:DefaultSyncCacheApi
   def this() {
      this(cache)
   }
}

Is there a way to get DI to work with this setup, or would something like a factory pattern work better?


问:
NodeJS output doesn't display Strings correctly in Windows "cmd"
My NodeJS console.log() function no longer displays Strings correctly in Window's cmd. They render as black text with a black background. I don't remember changing anything that could have lead to this.

I'm pretty sure it's the colors, though not the ones of the terminal itself (I've tried changing those), since when I copy the text, it has the correct output. I've included a screenshot of how it looks.

Screenshot:

Text output:

```<code>{ key1: 'value',
  key2: 51,
  key3: 2019-05-31T08:05:51.492Z,
  key4: [ '12', '23', '24' ] }
</code>```

Has anyone else had the same problem? What could have caused this (wasn't always like this).

EDIT: From what I gathered, the Object.toString method is causing the objects to display incorrectly. Node tells me it is native code though. What could be causing this issue?

答:
Looks like maybe somebody monkey-patched console.log and used something like https://www.npmjs.com/package/cli-highlight to color the output before it is written.

I'd ask around in your team and search for commits mentioning console in your source code repository.

If you can, check the behavior on a different environment, to learn whether it's something specific to your machine, like your terminal configuration.

Body:
My NodeJS console.log() function no longer displays Strings correctly in Window's cmd. They render as black text with a black background. I don't remember changing anything that could have lead to this.

I'm pretty sure it's the colors, though not the ones of the terminal itself (I've tried changing those), since when I copy the text, it has the correct output. I've included a screenshot of how it looks.

Screenshot:

Text output:

{ key1: 'value',
  key2: 51,
  key3: 2019-05-31T08:05:51.492Z,
  key4: [ '12', '23', '24' ] }

Has anyone else had the same problem? What could have caused this (wasn't always like this).

EDIT: From what I gathered, the Object.toString method is causing the objects to display incorrectly. Node tells me it is native code though. What could be causing this issue?


问:
onResume() and onPause() is being called on the first launch
I am having an activity and on Launching the activity through Intent from one of my service, onCreate(), onPause() and onResume() is called.

I am not very sure where i am doing wrong, i have removed all the code, just the basic function codes are available, and also i have removed all the codes which were opening that particular activity, still the behaviour is same.

I am including the simplest code i am using

ActivityClass.java

```<code>public class ActivityClass extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("TEST : onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lockscreen);
        ButterKnife.bind(this);

    }

    @Override
    protected void onPause() {
        System.out.println("TEST : onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        System.out.println("TEST : onDestroy");
        super.onDestroy();
    }

}
</code>```

Service class

```<code>public class OverlayService extends Service {

    Context context;
    public static final String TAG = OverlayService.class.getSimpleName();

    public OverlayService(Context applicationContext) {
        super();
        context = applicationContext;
    }

    public OverlayService() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "[onCreateService]");
        super.onStartCommand(intent, flags, startId);
        KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        if(myKM.inKeyguardRestrictedInputMode()) {
            //it is locked
            showOverlayActivity();
        } else {
            //it is not locked
        }
        registerOverlayReceiver();
        context = this;
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterOverlayReceiver();
        Log.i("EXIT", "ondestroy!");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
        sendBroadcast(broadcastIntent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void unregisterOverlayReceiver() {
        if (overlayReceiver != null) {
            unregisterReceiver(overlayReceiver);
        }
    }

    private static final String ACTION_DEBUG = "kunal.lockoverlay.action.DEBUG";

    private void registerOverlayReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(ACTION_DEBUG);
        registerReceiver(overlayReceiver, filter);
    }

    private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "[onReceive]" + action);
            if (action.equals(Intent.ACTION_SCREEN_ON)) {
                // ACTON_SCREEN_ON
                showOverlayActivity();
            } else if (action.equals(ACTION_DEBUG)) {
                showOverlayActivity();
            }
        }
    };

    private void showOverlayActivity() {
        Intent intent = new Intent();
        intent.setClass(this, ActivityClass.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

}
</code>```

Can someone point some of the possible reasons for this behaviour or could identify where i am doing wrong?

答:
Well everything will be called regardless, you have defined it in your ClassName.java file.

You override the method and define it in your class to perform certain action/function when that is called.

For eg.,

You could use onResume to clear an arraylist and add updated elements to arraylist (OR) dismiss all notifications from your app on moving to that activity, say

```<code>@Override
public void onResume() {
    super.onResume();
    calendarList.clear();
//dismiss all notifications here
 NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager!=null)
            notificationManager.cancelAll();
}
</code>```

OR eg., onDestroy to destroy the bluetooth service,

```<code> @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBluetoothService != null) {
            mBluetoothService.stop();
        }
     }
</code>```

Hope that clarifies. Happy coding!

Body:
I am having an activity and on Launching the activity through Intent from one of my service, onCreate(), onPause() and onResume() is called.

I am not very sure where i am doing wrong, i have removed all the code, just the basic function codes are available, and also i have removed all the codes which were opening that particular activity, still the behaviour is same.

I am including the simplest code i am using

ActivityClass.java

public class ActivityClass extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("TEST : onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lockscreen);
        ButterKnife.bind(this);

    }

    @Override
    protected void onPause() {
        System.out.println("TEST : onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        System.out.println("TEST : onDestroy");
        super.onDestroy();
    }

}

Service class

public class OverlayService extends Service {

    Context context;
    public static final String TAG = OverlayService.class.getSimpleName();

    public OverlayService(Context applicationContext) {
        super();
        context = applicationContext;
    }

    public OverlayService() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "[onCreateService]");
        super.onStartCommand(intent, flags, startId);
        KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        if(myKM.inKeyguardRestrictedInputMode()) {
            //it is locked
            showOverlayActivity();
        } else {
            //it is not locked
        }
        registerOverlayReceiver();
        context = this;
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterOverlayReceiver();
        Log.i("EXIT", "ondestroy!");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
        sendBroadcast(broadcastIntent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void unregisterOverlayReceiver() {
        if (overlayReceiver != null) {
            unregisterReceiver(overlayReceiver);
        }
    }

    private static final String ACTION_DEBUG = "kunal.lockoverlay.action.DEBUG";

    private void registerOverlayReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(ACTION_DEBUG);
        registerReceiver(overlayReceiver, filter);
    }

    private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "[onReceive]" + action);
            if (action.equals(Intent.ACTION_SCREEN_ON)) {
                // ACTON_SCREEN_ON
                showOverlayActivity();
            } else if (action.equals(ACTION_DEBUG)) {
                showOverlayActivity();
            }
        }
    };

    private void showOverlayActivity() {
        Intent intent = new Intent();
        intent.setClass(this, ActivityClass.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

}

Can someone point some of the possible reasons for this behaviour or could identify where i am doing wrong?

Body:
Well everything will be called regardless, you have defined it in your ClassName.java file.

You override the method and define it in your class to perform certain action/function when that is called.

For eg.,

You could use onResume to clear an arraylist and add updated elements to arraylist (OR) dismiss all notifications from your app on moving to that activity, say

@Override
public void onResume() {
    super.onResume();
    calendarList.clear();
//dismiss all notifications here
 NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager!=null)
            notificationManager.cancelAll();
}

OR eg., onDestroy to destroy the bluetooth service,

 @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBluetoothService != null) {
            mBluetoothService.stop();
        }
     }

Hope that clarifies. Happy coding!


问:
Html Action Link Not hiding when view page load in mvc
I have html.Action link and i need to hide the link when page load depend on the some condition.That condition when bool value False it should hide else need to show..on the page...

```<code>        @{
        if (item.Approved)
        {
            @Html.ActionLink("Approve", "Approve", new { id = item.ClusterID }, new { @class = "btn btn-info" })*@
        }
        else
        {
            @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
        }
    }
  }
</code>```

the above code not working could you tell me what is wrong above code?

答:
Please check your server side code first. If you are getting your bool value as expected or not. you are applying wrong condition. It should be.</p>

```<code>@if(item.Approverd){@Html.ActionLink("Approve","Apporoved",new{@id=item.clusterID)}
</code>```

Body:
I have html.Action link and i need to hide the link when page load depend on the some condition.That condition when bool value False it should hide else need to show..on the page...

        @{
        if (item.Approved)
        {
            @Html.ActionLink("Approve", "Approve", new { id = item.ClusterID }, new { @class = "btn btn-info" })*@
        }
        else
        {
            @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
        }
    }
  }

the above code not working could you tell me what is wrong above code?

Body:
Please check your server side code first. If you are getting your bool value as expected or not. you are applying wrong condition. It should be.

@if(item.Approverd){@Html.ActionLink("Approve","Apporoved",new{@id=item.clusterID)}


问:
cURL + PHP: Submitting a form with duplicate forms of the same form names
I am trying to POST to a page that has two forms with duplicate name elements.  The problem is that one form gets the password value and the other form gets the login value. (I can see this by printing out curl_exec($ch);)  I will include my code for the target URL and the formdata.  How do I fix this?

```<code>// my target url and form data
$target = "http://www.example.com/login";
$formdata = "id=$login&password=$password&Submit=Log In";
</code>```

Forms:

```<code><form id="login" name="login" method="post" action="login">

            <label for="id">LOGIN ID</label>  <input type="text" value="" name="id" maxlength="50" size="30"><br>
            <label for="password">Password ID</label>  <input type="password" name="password" maxlength="12" size="30">
            <div align="center"><button class="siteSprite signInSm" value="Log In" name="Submit" type="submit"></button></div>
</form>

<form section="login" id="loginform" name="loginform" action="http://www.example.com/login" method="post">
<input type="text" size="20" value=" Log-in" onfocus="this.value=''" name="id"></td>
<input type="password" value="Password" maxlength="15" size="12" onfocus="this.value=''" name="password">
<input type="submit" class="siteSprite signInSm" value="Sign-In">
</form>
</code>```

答:
<s>$formdata = "id=$login&password=$password&Submit=Sign-In"; might do the trick; note the fact that the second form has a submit button with a value, and the first form has a <button> which won't send a value (or, maybe, sends a different value via script or something)</s>

I just noticed that the submit button doesn't have a name; try passing it with NO submit parameter, i.e.:

```<code>$formdata = "id=$login&password=$password
</code>```

Body:
I am trying to POST to a page that has two forms with duplicate name elements.  The problem is that one form gets the password value and the other form gets the login value. (I can see this by printing out curl_exec($ch);)  I will include my code for the target URL and the formdata.  How do I fix this?

// my target url and form data
$target = "http://www.example.com/login";
$formdata = "id=$login&password=$password&Submit=Log In";

Forms:

<form id="login" name="login" method="post" action="login">

            LOGIN ID  <input type="text" value="" name="id" maxlength="50" size="30">

            Password ID  <input type="password" name="password" maxlength="12" size="30">

<button class="siteSprite signInSm" value="Log In" name="Submit" type="submit"></button>

</form>

<form section="login" id="loginform" name="loginform" action="http://www.example.com/login" method="post">
<input type="text" size="20" value=" Log-in" onfocus="this.value=''" name="id">
<input type="password" value="Password" maxlength="15" size="12" onfocus="this.value=''" name="password">
<input type="submit" class="siteSprite signInSm" value="Sign-In">
</form>

Body:
<s>$formdata = "id=$login&password=$password&Submit=Sign-In"; might do the trick; note the fact that the second form has a submit button with a value, and the first form has a <button> which won't send a value (or, maybe, sends a different value via script or something)</s>

I just noticed that the submit button doesn't have a name; try passing it with NO submit parameter, i.e.:

$formdata = "id=$login&password=$password


问:
Unity exceptions on load texture with WWW
I need to download an image from a server and show in sprite. All example I can find recommended next code:

```<code>WWW www = new WWW(requestUrl);
yield return www;
onTextureLoaded(www.texture,id);
</code>```

But I can't find the way how to handle exceptions in this case. Should I add Try catch? Or is there any way to check if the request was successful?

答:
Like JeanLuc you should check www.error.
But you should avoid WWW class since it's obsolete:
https://docs.unity3d.com/ScriptReference/WWW.html

you should use UnityWebRequest instead

https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Get.html

In that link you also find an example on how to check error with UnityWebRequest

Body:
I need to download an image from a server and show in sprite. All example I can find recommended next code:

WWW www = new WWW(requestUrl);
yield return www;
onTextureLoaded(www.texture,id);

But I can't find the way how to handle exceptions in this case. Should I add Try catch? Or is there any way to check if the request was successful?


问:
wxPython : Change ComboBox choices
I'm trying to change the choices of the second wx.ComboBox if the user chooses "Campaign" in the first wx.ComboBox.

The code below is not working, I mean the choices on the second wx.ComboBox remain the same.

I need your help with this one. Thank you,

```<code>class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        self.filterValues = ['Campaign','Spent', 'Network Impr.', 'Network Clicks', 'Rev. /1000', 'GA Impr.', 'Revenue', 'eCPC', 'CPC', 'CTR']
        self.filterComboColumns = wx.ComboBox(self.panel,choices = self.filterValues, size = (100,-1))
        self.Bind(wx.EVT_COMBOBOX, self.onComboValues, self.filterComboColumns)

        self.filterContainsValues = ['Contains', 'Doesn\'t contain' , '<', '>']
        self.filterComboContains = wx.ComboBox(self.panel,choices = self.filterContainsValues, size = (100,-1))
        self.filterComboContains.Enable(False)
        self.Bind(wx.EVT_COMBOBOX, self.onComboContains, self.filterComboContains)

        self.filterInput = wx.TextCtrl(self.panel, wx.ID_ANY, size=(145, 24))
        self.filterInput.Enable(False)
        self.filterInput.SetFont(font)
        self.Bind(wx.EVT_TEXT, self.onComboInput, self.filterInput)

    def onComboValues(self, event):
      cb = event.GetEventObject()

      if cb.GetValue() == "Campaign":
        self.filterComboContains.Enable(True)
        self.filterContainsValues = []
        self.filterContainsValues.append('Contains')
        self.filterContainsValues.append('Doesn\'t contain')
</code>```

答:
You were missing only a call to the Set method. It is not enough to change the list containing the options, you need to tell the wx.ComboBox that the list changed. The Set method is the one that does this.

Code with comments (####):

```<code>import wx

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        self.panel = wx.Panel(self)

        self.filterValues = ['Campaign','Spent', 'Network Impr.', 'Network Clicks', 'Rev. /1000', 'GA Impr.', 'Revenue', 'eCPC', 'CPC', 'CTR']
        self.filterComboColumns = wx.ComboBox(self.panel, choices = self.filterValues, size = (100,-1))
        self.Bind(wx.EVT_COMBOBOX, self.onComboValues, self.filterComboColumns)

        self.filterContainsValues = ['Contains', 'Doesn\'t contain' , '<', '>']
        self.filterComboContains = wx.ComboBox(self.panel,choices = self.filterContainsValues, size = (100,-1))
        self.filterComboContains.Enable(False)
        #self.Bind(wx.EVT_COMBOBOX, self.onComboContains, self.filterComboContains)

        self.filterInput = wx.TextCtrl(self.panel, wx.ID_ANY, size=(145, 24))
        self.filterInput.Enable(False)
        #self.filterInput.SetFont(font)
        #self.Bind(wx.EVT_TEXT, self.onComboInput, self.filterInput)

        #### Sizer
        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.filterComboColumns)
        self.sizer.Add(self.filterComboContains)
        self.sizer.Add(self.filterInput)
        self.panel.SetSizer(self.sizer)

    def onComboValues(self, event):
        cb = event.GetEventObject()

        if cb.GetValue() == "Campaign":
            self.filterComboContains.Enable(True)
            self.filterContainsValues = []
            self.filterContainsValues.append('Contains')
            self.filterContainsValues.append('Doesn\'t contain')
            #### The line below is the line you were missing
            self.filterComboContains.Set(self.filterContainsValues)
            #### This is to avoid showing an empty field when the values change
            self.filterComboContains.SetSelection(0)
        else:
            pass

# Run the program
if __name__ == "__main__":
    app = wx.App()
    frame = Test(None, 1)
    frame.Show()
    app.MainLoop()
</code>```

Title: wxPython : Change ComboBox choices

Body:
I'm trying to change the choices of the second wx.ComboBox if the user chooses "Campaign" in the first wx.ComboBox.

The code below is not working, I mean the choices on the second wx.ComboBox remain the same.

I need your help with this one. Thank you,

class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        self.filterValues = ['Campaign','Spent', 'Network Impr.', 'Network Clicks', 'Rev. /1000', 'GA Impr.', 'Revenue', 'eCPC', 'CPC', 'CTR']
        self.filterComboColumns = wx.ComboBox(self.panel,choices = self.filterValues, size = (100,-1))
        self.Bind(wx.EVT_COMBOBOX, self.onComboValues, self.filterComboColumns)

        self.filterContainsValues = ['Contains', 'Doesn\'t contain' , '<', '>']
        self.filterComboContains = wx.ComboBox(self.panel,choices = self.filterContainsValues, size = (100,-1))
        self.filterComboContains.Enable(False)
        self.Bind(wx.EVT_COMBOBOX, self.onComboContains, self.filterComboContains)

        self.filterInput = wx.TextCtrl(self.panel, wx.ID_ANY, size=(145, 24))
        self.filterInput.Enable(False)
        self.filterInput.SetFont(font)
        self.Bind(wx.EVT_TEXT, self.onComboInput, self.filterInput)

    def onComboValues(self, event):
      cb = event.GetEventObject()

      if cb.GetValue() == "Campaign":
        self.filterComboContains.Enable(True)
        self.filterContainsValues = []
        self.filterContainsValues.append('Contains')
        self.filterContainsValues.append('Doesn\'t contain')

Body:
You were missing only a call to the Set method. It is not enough to change the list containing the options, you need to tell the wx.ComboBox that the list changed. The Set method is the one that does this.

Code with comments (####):

import wx

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        self.panel = wx.Panel(self)

        self.filterValues = ['Campaign','Spent', 'Network Impr.', 'Network Clicks', 'Rev. /1000', 'GA Impr.', 'Revenue', 'eCPC', 'CPC', 'CTR']
        self.filterComboColumns = wx.ComboBox(self.panel, choices = self.filterValues, size = (100,-1))
        self.Bind(wx.EVT_COMBOBOX, self.onComboValues, self.filterComboColumns)

        self.filterContainsValues = ['Contains', 'Doesn\'t contain' , '<', '>']
        self.filterComboContains = wx.ComboBox(self.panel,choices = self.filterContainsValues, size = (100,-1))
        self.filterComboContains.Enable(False)
        #self.Bind(wx.EVT_COMBOBOX, self.onComboContains, self.filterComboContains)

        self.filterInput = wx.TextCtrl(self.panel, wx.ID_ANY, size=(145, 24))
        self.filterInput.Enable(False)
        #self.filterInput.SetFont(font)
        #self.Bind(wx.EVT_TEXT, self.onComboInput, self.filterInput)

        #### Sizer
        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.filterComboColumns)
        self.sizer.Add(self.filterComboContains)
        self.sizer.Add(self.filterInput)
        self.panel.SetSizer(self.sizer)

    def onComboValues(self, event):
        cb = event.GetEventObject()

        if cb.GetValue() == "Campaign":
            self.filterComboContains.Enable(True)
            self.filterContainsValues = []
            self.filterContainsValues.append('Contains')
            self.filterContainsValues.append('Doesn\'t contain')
            #### The line below is the line you were missing
            self.filterComboContains.Set(self.filterContainsValues)
            #### This is to avoid showing an empty field when the values change
            self.filterComboContains.SetSelection(0)
        else:
            pass

# Run the program
if __name__ == "__main__":
    app = wx.App()
    frame = Test(None, 1)
    frame.Show()
    app.MainLoop()


问:
How to specify JSON node property values when parsing/iterating in Azure Logic Apps?
TL;DR How do I specify a specific JSON node property within Azure Logic Apps' ParseJSON > For Each step, when the designer only gives me access to the parent nodes?

I'm building a Logic App that:

Receives and parses a list of people as JSON data from an external system

Constructs a new JSON file with different structure

Posts the new file to a second external system

The JSON response from item 1 has this structure:

```<code>{
    "Success": true,
    "Message": "Completed",
    "Result": [
        {
            "EmployeeId": {
                "DisplayValue": "PW123",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        {
            "EmployeeId": {
                "DisplayValue": "PW789",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        .... removed for brevity
    ]
}
</code>```

Within the designer, if I add a Data Operations > Parse JSON > For Each step, it lets me specify the properties, but at too high a level:

Notice the designer gives me EmployeeId, but I actually need EmployeeId.DisplayValue, which is both properties and their values in JSON format, rather than a simple string containing only the EmployeeId or EmailId values.

Can the JSON be read at the deeper level I require using the designer?

答:
To support the input by AdAstra and provide a canonical answer for future reference...

The ForEach block was misleading, and wasn't actually required.  Instead a Select block was required, but which then had to be edited in Code View (as advised by @AdAstra) to cherry-pick the desired fields:

I still need to figure out wrapping the output in my desired structure, and will update when that's solved.  It turns out that reforming the JSON into a new structure is also super-simple thanks to code view.  I just specified my desired output around the existing logic:

```<code>             "from": "@body('Parse_JSON')?['Result']",
             "select": {
                 "Option1": "Value1",
                 "Option2": "Value2",
                 "People": [
                     {
                         "Email": "@item()['EmailId']['DisplayValue']",
                         "FirstName": "@item()['FirstName']['DisplayValue']"
                     }
                  ]
             }
</code>```

Note that Designer View does not allow for modifications to the more complex selections after specifying them in code.

Body:
TL;DR How do I specify a specific JSON node property within Azure Logic Apps' ParseJSON > For Each step, when the designer only gives me access to the parent nodes?

I'm building a Logic App that:

Receives and parses a list of people as JSON data from an external system

Constructs a new JSON file with different structure

Posts the new file to a second external system

The JSON response from item 1 has this structure:

{
    "Success": true,
    "Message": "Completed",
    "Result": [
        {
            "EmployeeId": {
                "DisplayValue": "PW123",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        {
            "EmployeeId": {
                "DisplayValue": "PW789",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        .... removed for brevity
    ]
}

Within the designer, if I add a Data Operations > Parse JSON > For Each step, it lets me specify the properties, but at too high a level:

Notice the designer gives me EmployeeId, but I actually need EmployeeId.DisplayValue, which is both properties and their values in JSON format, rather than a simple string containing only the EmployeeId or EmailId values.

Can the JSON be read at the deeper level I require using the designer?

Body:
To support the input by AdAstra and provide a canonical answer for future reference...

The ForEach block was misleading, and wasn't actually required.  Instead a Select block was required, but which then had to be edited in Code View (as advised by @AdAstra) to cherry-pick the desired fields:

I still need to figure out wrapping the output in my desired structure, and will update when that's solved.  It turns out that reforming the JSON into a new structure is also super-simple thanks to code view.  I just specified my desired output around the existing logic:

             "from": "@body('Parse_JSON')?['Result']",
             "select": {
                 "Option1": "Value1",
                 "Option2": "Value2",
                 "People": [
                     {
                         "Email": "@item()['EmailId']['DisplayValue']",
                         "FirstName": "@item()['FirstName']['DisplayValue']"
                     }
                  ]
             }

Note that Designer View does not allow for modifications to the more complex selections after specifying them in code.


问:
How to add flask-admin to my existing flask
For the past two days I've been trying to intergrate flask-admin to my already existing flask application. But the problem is that I keep getting the same error:

builtins.AssertionError

AssertionError: A name collision occurred between blueprints <flask.blueprints.Blueprint object at 0x000001D8F121B2B0> and <flask.blueprints.Blueprint object at 0x000001D8ECD95A90>. Both share the same name "admin". Blueprints that are created on the fly need unique names.

and that error comes from this block of lines:

Main flask application:

```<code>app.route("/admin")
def admin():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    return adminScreen.adminPage()
</code>```

admin.py

```<code>def adminPage():
    admin=Admin(app)
    admin.add_view(ModelView(User, db.session))
    admin.add_view(ModelView(Role, db.session))
    admin.add_view(ModelView(PointOfSale, db.session))
    return admin
</code>```

And what I want to do is to manage the users that I already have in my database by using the functions that flask-admin provide.

So my question is; is there a simple way to route flask-admin to my pre-existing flask application?

P.S I already know that there is this post from May of 2018, but I have no idea how to implement the solution that was provided.

答:
In order to use blueprints correctly you should update your app to use app factory instead global variable. Otherwise you cannot have multiple instances of the application.
In existing project it may require some work to do but it's worth it.
Example factory may looki like this:

```<code>def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)

    from yourapplication.model import db
    db.init_app(app)

    from yourapplication.views.admin import admin
    from yourapplication.views.frontend import frontend
    app.register_blueprint(admin)
    app.register_blueprint(frontend)

    return app
</code>```

You can find more information here:

http://flask.pocoo.org/docs/1.0/patterns/appfactories/

Body:
For the past two days I've been trying to intergrate flask-admin to my already existing flask application. But the problem is that I keep getting the same error:

builtins.AssertionError

AssertionError: A name collision occurred between blueprints <flask.blueprints.Blueprint object at 0x000001D8F121B2B0> and <flask.blueprints.Blueprint object at 0x000001D8ECD95A90>. Both share the same name "admin". Blueprints that are created on the fly need unique names.

and that error comes from this block of lines:

Main flask application:

app.route("/admin")
def admin():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    return adminScreen.adminPage()

admin.py

def adminPage():
    admin=Admin(app)
    admin.add_view(ModelView(User, db.session))
    admin.add_view(ModelView(Role, db.session))
    admin.add_view(ModelView(PointOfSale, db.session))
    return admin

And what I want to do is to manage the users that I already have in my database by using the functions that flask-admin provide.

So my question is; is there a simple way to route flask-admin to my pre-existing flask application?

P.S I already know that there is this post from May of 2018, but I have no idea how to implement the solution that was provided.

Body:
In order to use blueprints correctly you should update your app to use app factory instead global variable. Otherwise you cannot have multiple instances of the application.
In existing project it may require some work to do but it's worth it.
Example factory may looki like this:

def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)

    from yourapplication.model import db
    db.init_app(app)

    from yourapplication.views.admin import admin
    from yourapplication.views.frontend import frontend
    app.register_blueprint(admin)
    app.register_blueprint(frontend)

    return app

You can find more information here:

http://flask.pocoo.org/docs/1.0/patterns/appfactories/


问:
SPARQL query to get a node sub graph at n level depth
I am looking to get a sub graph of a given node to a given k level of depth as shown in the following image for k=2.

if I go to https://dbpedia.org/sparql and select a ?city I want to get all the details of the city graph to say 5 levels. I am looking for a generic query that do not need to have knowledge of the graph to fetch the data like below.

```<code>CONSTRUCT {
  ?city a ?plebs .
  ?mayor foaf:gender ?gender.
  ?city dbo:country ?ctr .
  ?city dbo:populationTotal ?pop.
  ?city dbo:leaderParty ?party .
  ?city rdfs:label ?cityName .
  ?party dbo:ideology ?ideology
} WHERE {
   ?plebs rdfs:subClassOf dbo:Settlement.
   ?city a ?plebs .
   ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader | dbo:leaderName) ?mayor .
   ?mayor foaf:gender ?gender.
   ?city dbo:populationTotal ?pop .
   ?city rdfs:label ?cityName .
   ?city dbo:country ?ctr .
   ?city dbo:leaderParty ?party .
   ?party dbo:ideology ?ideology .
   FILTER(str(?gender) = "female")
  }
ORDER BY DESC(?pop)
</code>```

Can someone please help me with a generic SPARQL query that can work on any database for a given node.

Regards
Kiran

答:
It's actually pretty easy:

```<code>construct {

?s ?p ?o.
?o ?op ?oo.
?oo ?oop ?ooo.
?ooo ?ooop ?oooo.
?oooo ?oooop ?ooooo.
}
where {
bind(city:_London as ?s)
?s ?p ?o.
optional {
   ?o ?op ?oo.
   optional {
      ?oo ?oop ?ooo.
       optional {
          ?ooo ?ooop ?oooo.
          optional {
              ?oooo ?oooop ?ooooo.
           }
        }
     }
  }
}
</code>```

The construct statement will return the graph of all outbound links from the city in question, and any time you have a null returned, that triple will simply not be constructed.

Body:
I am looking to get a sub graph of a given node to a given k level of depth as shown in the following image for k=2.

if I go to https://dbpedia.org/sparql and select a ?city I want to get all the details of the city graph to say 5 levels. I am looking for a generic query that do not need to have knowledge of the graph to fetch the data like below.

CONSTRUCT {
  ?city a ?plebs .
  ?mayor foaf:gender ?gender.
  ?city dbo:country ?ctr .
  ?city dbo:populationTotal ?pop.
  ?city dbo:leaderParty ?party .
  ?city rdfs:label ?cityName .
  ?party dbo:ideology ?ideology
} WHERE {
   ?plebs rdfs:subClassOf dbo:Settlement.
   ?city a ?plebs .
   ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader | dbo:leaderName) ?mayor .
   ?mayor foaf:gender ?gender.
   ?city dbo:populationTotal ?pop .
   ?city rdfs:label ?cityName .
   ?city dbo:country ?ctr .
   ?city dbo:leaderParty ?party .
   ?party dbo:ideology ?ideology .
   FILTER(str(?gender) = "female")
  }
ORDER BY DESC(?pop)

Can someone please help me with a generic SPARQL query that can work on any database for a given node.

Regards
Kiran

Body:
It's actually pretty easy:

construct {

?s ?p ?o.
?o ?op ?oo.
?oo ?oop ?ooo.
?ooo ?ooop ?oooo.
?oooo ?oooop ?ooooo.
}
where {
bind(city:_London as ?s)
?s ?p ?o.
optional {
   ?o ?op ?oo.
   optional {
      ?oo ?oop ?ooo.
       optional {
          ?ooo ?ooop ?oooo.
          optional {
              ?oooo ?oooop ?ooooo.
           }
        }
     }
  }
}

The construct statement will return the graph of all outbound links from the city in question, and any time you have a null returned, that triple will simply not be constructed.


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
I use ToString() a ton for datetime formats.

http://hunterconcepts.com/content/tools/formats/

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

OwnerDisplayName: Hunter


问:
JQuery Accordion Bigger Icons
I'm trying to put an icon bigger than the default 16x16 in the accordion header.  I do this by using the following code:

```<code>.ui-accordion-header.user .ui-icon {
background: url(../../Content/Images/User.gif);
height: 32px;
width: 32px;
</code>```

}

The problem is the bottom of the icon is cut off and is not centered.  Is there something I'm missing or do I need to go in and override some of the CSS defaults.

答:
In my own personal experience, customizing the jQuery components is only worth-while if you are using a suite of them and are trying to maintain a consistent look & feel.

If you are just looking to create an accordion, you can certainly code one yourself that's equally as good as theirs. Here is one I whipped up a little while ago with larger icons. I'm sure it can be optimized and improved. Feel free to use/modify it as you need to.

Title: JQuery Accordion Bigger Icons

Body:
I'm trying to put an icon bigger than the default 16x16 in the accordion header.  I do this by using the following code:

.ui-accordion-header.user .ui-icon {
background: url(../../Content/Images/User.gif);
height: 32px;
width: 32px;

}

The problem is the bottom of the icon is cut off and is not centered.  Is there something I'm missing or do I need to go in and override some of the CSS defaults.


问:
Pandas, astype(int) applied to float column returns negative numbers
My task is to read data from excel to dataframe. The data is a bit messy and to clean that up I've done:

```<code>df_1 = pd.read_excel(offers[0])
df_1 = df_1.rename(columns={'Наименование [Дата Файла: 29.05.2019 время: 10:29:42 ]':'good_name',
                     'Штрихкод':'barcode',
                     'Цена шт. руб.':'price',
                     'Остаток': 'balance'
                    })
df_1 = df_1[new_columns]
# I don't know why but without replacing NaN with another char code doesn't work
df_1.barcode = df_1.barcode.fillna('_')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to numeric
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer').fillna(0)
df_1.head()
</code>```

It returns column barcode with type float64 (why so?)

```<code>0    0.000000e+00
1    7.613037e+12
2    7.613037e+12
3    7.613034e+12
4    7.613035e+12
Name: barcode, dtype: float64
</code>```

Then I try to convert that column to integer.

```<code>df_1.barcode = df_1.barcode.astype(int)
</code>```

But I keep getting silly negative numbers.

```<code>df_1.barcode[0:5]
0             0
1   -2147483648
2   -2147483648
3   -2147483648
4   -2147483648

Name: barcode, dtype: int32
</code>```

Thanks to @Will and @micric eventually I've got a solution.

```<code>df_1 = pd.read_excel(offers[0])
df_1 = df_1[new_columns]
# replacing NaN with 0, it'll help to convert the column explicitly to dtype integer
df_1.barcode = df_1.barcode.fillna('0')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to integer
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer')
</code>```

Resume:

pd.to_numeric converts NaN to float64. As a result from column with
both NaN and not-Nan values we should expect column dtype float64.

Check size of number you're dealing with. int32 has its limit, which
is 2**32 = 4294967296.
Thanks a lot for your help, guys!

答:
Many questions in one.

So your expected dtype...

```<code>pd.to_numeric(df_1.barcode, downcast='integer').fillna(0)
</code>```

pd.to_numeric downcast to integer would give you an integer, however, you have NaNs in your data and pandas needs to use a float64 type to represent NaNs

Body:
My task is to read data from excel to dataframe. The data is a bit messy and to clean that up I've done:

df_1 = pd.read_excel(offers[0])
df_1 = df_1.rename(columns={'Наименование [Дата Файла: 29.05.2019 время: 10:29:42 ]':'good_name',
                     'Штрихкод':'barcode',
                     'Цена шт. руб.':'price',
                     'Остаток': 'balance'
                    })
df_1 = df_1[new_columns]
# I don't know why but without replacing NaN with another char code doesn't work
df_1.barcode = df_1.barcode.fillna('_')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to numeric
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer').fillna(0)
df_1.head()

It returns column barcode with type float64 (why so?)

0    0.000000e+00
1    7.613037e+12
2    7.613037e+12
3    7.613034e+12
4    7.613035e+12
Name: barcode, dtype: float64

Then I try to convert that column to integer.

df_1.barcode = df_1.barcode.astype(int)

But I keep getting silly negative numbers.

df_1.barcode[0:5]
0             0
1   -2147483648
2   -2147483648
3   -2147483648
4   -2147483648

Name: barcode, dtype: int32

Thanks to @Will and @micric eventually I've got a solution.

df_1 = pd.read_excel(offers[0])
df_1 = df_1[new_columns]
# replacing NaN with 0, it'll help to convert the column explicitly to dtype integer
df_1.barcode = df_1.barcode.fillna('0')
# remove all non-numeric characters
df_1.barcode = df_1.barcode.apply(lambda row: re.sub('[^0-9]', '', row))
# convert str to integer
df_1.barcode = pd.to_numeric(df_1.barcode, downcast='integer')

Resume:

pd.to_numeric converts NaN to float64. As a result from column with
both NaN and not-Nan values we should expect column dtype float64.

Check size of number you're dealing with. int32 has its limit, which
is 2**32 = 4294967296.
Thanks a lot for your help, guys!

Body:
Many questions in one.

So your expected dtype...

pd.to_numeric(df_1.barcode, downcast='integer').fillna(0)

pd.to_numeric downcast to integer would give you an integer, however, you have NaNs in your data and pandas needs to use a float64 type to represent NaNs