问:
How to hide certain texts retrieved from Strings.xml
I have an English teaching app where the users are given some sentences with their Turkish equivalents. I retrieve the data from Strings.xml as follows:

<.b>Possession (Aitlik)\n\nhave
        (sahip olmak)\npossess (sahip olmak)\nown (sahip olmak)\nbelong (ait olmak)\nconsist (-den meydana gelmek)\nlack (eksik olmak)\ninvolve
        (içermek)\n\n<.b>Emotions (Duygular)\n\nlike (sevmek)\ndislike (sevmemek)\nprefer (tercih etmek)\nappreciate (takdir etmek)\nneed
        (ihtiyacı olmak)\nwish (istemek, dilemek)\nhope (ummak)\nvalue (değer vermek)\nadore (hayran olmak)\nfear (korkmak)\nsurprise (şaşırtmak)\nenvy
        (kıskanmak)\nhate (nefret etmek)\nlove (sevmek)\n\n
    ...
```
<p>If the user wishes, I'd like to hide the translations of the words. Is there a way to do it? So far, I tried separating the example sentences from their translations and hiding the translations from the code:</p>
<pre class="lang-xml prettyprint-override"><code><string name=header_one>"<.b>Possession</b>"</string>
<string name=header_one_translation>"<.b>Aitlik</b>"</string>
</code>```

binding.hideTranslationsButton.setOnClickListener {
            binding.headerOneTranslation.isGone = true
            binding.translationOne.isGone = true
            binding.translationTwo.isGone = true
            binding.translationThree.isGone = true
            binding.translationFour.isGone = true
            binding.translationFive.isGone = true
            binding.translationSix.isGone = true
            ...
        }
```

but it took too much time and it feels like my code has gotten messier considering I have 50 other grammar topics like this (I put dots intentionally --> <.b>).

答: use recycleview and handle hide text in adapter of recycleview</p>

Body:
I have an English teaching app where the users are given some sentences with their Turkish equivalents. I retrieve the data from Strings.xml as follows:

<.b>Possession (Aitlik)\n\nhave
        (sahip olmak)\npossess (sahip olmak)\nown (sahip olmak)\nbelong (ait olmak)\nconsist (-den meydana gelmek)\nlack (eksik olmak)\ninvolve
        (içermek)\n\n<.b>Emotions (Duygular)\n\nlike (sevmek)\ndislike (sevmemek)\nprefer (tercih etmek)\nappreciate (takdir etmek)\nneed
        (ihtiyacı olmak)\nwish (istemek, dilemek)\nhope (ummak)\nvalue (değer vermek)\nadore (hayran olmak)\nfear (korkmak)\nsurprise (şaşırtmak)\nenvy
        (kıskanmak)\nhate (nefret etmek)\nlove (sevmek)\n\n
    ...

If the user wishes, I'd like to hide the translations of the words. Is there a way to do it? So far, I tried separating the example sentences from their translations and hiding the translations from the code:

<string name=header_one>"<.b>Possession"</string>
<string name=header_one_translation>"<.b>Aitlik"</string>

binding.hideTranslationsButton.setOnClickListener {
            binding.headerOneTranslation.isGone = true
            binding.translationOne.isGone = true
            binding.translationTwo.isGone = true
            binding.translationThree.isGone = true
            binding.translationFour.isGone = true
            binding.translationFive.isGone = true
            binding.translationSix.isGone = true
            ...
        }

but it took too much time and it feels like my code has gotten messier considering I have 50 other grammar topics like this (I put dots intentionally --> <.b>).


来源: stackexchange

问:
do i host react app, node js and mongo db separatly to host my whole website for free?
I have made mern stack website that uses react, node, mongo and API. I want to ask if I want to host my website for free to test its functionalities, should I need to host it separately or can I host it on cpannel ?

and can you recommend me youtube video or document to host mern app to cpannel for free

答:
You can host your backend with Heroku:
A video for it as you asked (https://www.youtube.com/watch?v=27GoRa4d15c)

There are two ways I prefer to host the frontend:

With netlify

Github pages
Using netlify is easy however using it free will limit hours it can be active monthly or something. But GitHub pages is also free.

https://www.c-sharpcorner.com/article/how-to-deploy-react-application-on-github-pages/

This is a site for deploying on github pages.
And here is a video on deploying with netlify (https://www.youtube.com/watch?v=8KGLOJHqNMg)

Before you judge me on the videos I have not watched them fully so I do not know how good they explain it but you can search on youtube and find plenty of other videos on deploying with these methods if you do not understand from these videos.

ContentLicense: CC BY-SA 4.0


问:
Average of rows in SQL
here my table
Table

I want to find the average of MTK+IPA+PJOK
table 2

with this code

```<code>SELECT induk, nama, kelas,
       SUM(if (kdmapel=“111”,ratarata,0)) as MTK,
       SUM(if (kdmapel=“112”,ratarata,0)) as IPA,
       SUM(if (kdmapel=“115”,ratarata,0)) as PJOK,
       ((MTK+IPA+PJOK)/3) as NAR
from nilai
WHERE kelas=1 and semester=“ganjil”
group by induk
</code>```

but it doesn't work, the error said

#1054 - Unknown column 'MTK' in 'field list'

答:
The MTK, IPA and PJOK are calculated from group functions.

So they can't be used directly like that.

One way is to wrap it all in a sub-query, then calculate NAR in the outer query.

However, their calculation is quite simple and similar.

So the calculation for NAR isn't much harder.

```<code>SELECT induk, nama, kelas,
       SUM(if(kdmapel='111',ratarata,0)) as MTK,
       SUM(if(kdmapel='112',ratarata,0)) as IPA,
       SUM(if(kdmapel='115',ratarata,0)) as PJOK,
       (SUM(if(kdmapel IN('111','112','115'),ratarata,0))/3) as NAR
FROM nilai
WHERE kelas=1 and semester='ganjil'
GROUP BY induk
</code>```

Title: Average of rows in SQL

Body:
here my table
Table

I want to find the average of MTK+IPA+PJOK
table 2

with this code

SELECT induk, nama, kelas,
       SUM(if (kdmapel=“111”,ratarata,0)) as MTK,
       SUM(if (kdmapel=“112”,ratarata,0)) as IPA,
       SUM(if (kdmapel=“115”,ratarata,0)) as PJOK,
       ((MTK+IPA+PJOK)/3) as NAR
from nilai
WHERE kelas=1 and semester=“ganjil”
group by induk

but it doesn't work, the error said

#1054 - Unknown column 'MTK' in 'field list'

Body:
The MTK, IPA and PJOK are calculated from group functions.

So they can't be used directly like that.

One way is to wrap it all in a sub-query, then calculate NAR in the outer query.

However, their calculation is quite simple and similar.

So the calculation for NAR isn't much harder.

SELECT induk, nama, kelas,
       SUM(if(kdmapel='111',ratarata,0)) as MTK,
       SUM(if(kdmapel='112',ratarata,0)) as IPA,
       SUM(if(kdmapel='115',ratarata,0)) as PJOK,
       (SUM(if(kdmapel IN('111','112','115'),ratarata,0))/3) as NAR
FROM nilai
WHERE kelas=1 and semester='ganjil'
GROUP BY induk


问:
Displaying one result on a query with LIMIT 10
Today i'm makeing this new question because this is not posible to display one result on a query with limit 10.

Here is the query:

```<code>$query = "SELECT * FROM articol WHERE status = 1 ORDER BY data DESC LIMIT 10";
$result = mysql_query($query) or die ("Could not execute query");
 while($row = mysql_fetch_array($result))
 {
    $id = $row["id"];
    $titlu = $row["titlu"];
    $data = $row["data"];
    $desc = $row["continut"];
    $part = strip_tags($desc);
 }
</code>```

And this is the echo to display

```<code><link>http://dirlink.ro/articol.php?art_id=<?php echo $id; ?></link>
<title><?php echo $titlu; ?></title>
<description><?php echo substr($part,0,180); ?> ...{Citeste tot} </description>
<pubDate><?php echo $data; ?></pubDate>
</code>```

The same code is putted on other page, for other category of my website and it's work just fine. I don't understand why at this section is echoing only one result.

答:
I have fixed it: I checked the RSS field with rssvalidator.org and there it showed me the errors and how to fix it.

So I fixed the error, which seem to originate from some &circi;, which is a character of a Romanian language.

ContentLicense: CC BY-SA 3.0

Body:
Today i'm makeing this new question because this is not posible to display one result on a query with limit 10.

Here is the query:

$query = "SELECT * FROM articol WHERE status = 1 ORDER BY data DESC LIMIT 10";
$result = mysql_query($query) or die ("Could not execute query");
 while($row = mysql_fetch_array($result))
 {
    $id = $row["id"];
    $titlu = $row["titlu"];
    $data = $row["data"];
    $desc = $row["continut"];
    $part = strip_tags($desc);
 }

And this is the echo to display

<link>http://dirlink.ro/articol.php?art_id=<?php echo $id; ?></link>
<title><?php echo $titlu; ?></title>
<description><?php echo substr($part,0,180); ?> ...{Citeste tot} </description>
<pubDate><?php echo $data; ?></pubDate>

The same code is putted on other page, for other category of my website and it's work just fine. I don't understand why at this section is echoing only one result.


问:
Typing unused arguments
I have a function that has to take two arguments, like:

```<code>def f(first_arg: int, unused_arg) -> int:
    first_arg += 1
    return first_arg
</code>```

I want to type my function, what should be the type of unused_arg ? From this question I guess None could be used.

For context, I'm using lax.scan from jax which needs a function with two arguments even when the second one is unused.

答:
The doc (https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.scan.html) gives the type of f as:

```<code>Callable[[~Carry, ~X], Tuple[~Carry, ~Y]]
</code>```

so I'd maybe do it with a TypeVar named X if I didn't have a more specific type:

```<code>from typing import TypeVar

X = TypeVar("X")

def f(first_arg: int, _second_arg: X) -> int:
    ...
</code>```

Using Any can be problematic since it masks typechecking -- it doesn't matter for a variable you aren't ever using, but if your function implementation ever changes you might not realize that the formerly-unused arg isn't being typechecked, whereas if you use a TypeVar you'll get errors if you make any assumptions that aren't backed up by a bound on that variable.  I try to avoid even importing Any just to make sure it's not creeping in anyplace without me noticing.

Note that per the doc it seems like your f is expected to return a tuple of two items; I'm not sure if that matters for your use case.

The standard way (at least as enforced by linters I've used) of indicating an unused parameter is to prefix it with an underscore, so I'd do that instead of naming it unused_arg).

Title: Typing unused arguments

Body:
I have a function that has to take two arguments, like:

def f(first_arg: int, unused_arg) -> int:
    first_arg += 1
    return first_arg

I want to type my function, what should be the type of unused_arg ? From this question I guess None could be used.

For context, I'm using lax.scan from jax which needs a function with two arguments even when the second one is unused.

Body:
The doc (https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.scan.html) gives the type of f as:

Callable[[~Carry, ~X], Tuple[~Carry, ~Y]]

so I'd maybe do it with a TypeVar named X if I didn't have a more specific type:

from typing import TypeVar

X = TypeVar("X")

def f(first_arg: int, _second_arg: X) -> int:
    ...

Using Any can be problematic since it masks typechecking -- it doesn't matter for a variable you aren't ever using, but if your function implementation ever changes you might not realize that the formerly-unused arg isn't being typechecked, whereas if you use a TypeVar you'll get errors if you make any assumptions that aren't backed up by a bound on that variable.  I try to avoid even importing Any just to make sure it's not creeping in anyplace without me noticing.

Note that per the doc it seems like your f is expected to return a tuple of two items; I'm not sure if that matters for your use case.

The standard way (at least as enforced by linters I've used) of indicating an unused parameter is to prefix it with an underscore, so I'd do that instead of naming it unused_arg).


问:
Error while deploying Spring boot app to Heroku
I have an issue while deploying my Spring boot app to Heroku.

I am trying to deploy it as a java app instead of building and deploying a jar file.

I have used the free Postgresql in Heroku.

The error while pushing the app to Heroku master is:

```<code>remote:        [INFO] Changes detected - recompiling the module!
remote:        [INFO] Compiling 18 source files to /tmp/build_79201803/target/classes
remote:        [INFO] -------------------------------------------------------------
remote:        [ERROR] COMPILATION ERROR :
remote:        [INFO] -------------------------------------------------------------
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/post.java:[15,8] class Post is public, should be declared in a file named Post.java
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/user.java:[12,8] class User is public, should be declared in a file named User.java
remote:        [INFO] 2 errors
remote:        [INFO] -------------------------------------------------------------
remote:        [INFO] ------------------------------------------------------------------------
remote:        [INFO] BUILD FAILURE
remote:        [INFO] ------------------------------------------------------------------------
remote:        [INFO] Total time:  16.300 s
remote:        [INFO] Finished at: 2020-08-11T11:09:38Z
remote:        [INFO] ------------------------------------------------------------------------
remote:        [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project springblog: Compilation failure: Compilation failure:
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/post.java:[15,8] class Post is public, should be declared in a file named Post.java
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/user.java:[12,8] class User is public, should be declared in a file named User.java
remote:        [ERROR] -> [Help 1]
remote:        [ERROR]
remote:        [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
remote:        [ERROR] Re-run Maven using the -X switch to enable full debug logging.
remote:        [ERROR]
remote:        [ERROR] For more information about the errors and possible solutions, please read the following articles:
remote:        [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
remote:
remote:  !     ERROR: Failed to build app with Maven
remote:        We're sorry this build is failing! If you can't find the issue in application code,
remote:        please submit a ticket so we can help: https://help.heroku.com/
remote:
remote:  !     Push rejected, failed to compile Java app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
</code>```

The error here specifies that my User and Post models file name starts with lowercase letters.

But my file structure is:

I do not think the error is in the Models, and I am not able to find out the issue.

答:
```<code><build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                <source>1.8</source>
                <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

Put this in the pom.xml.

git add .

git commit -m "Pom Changed"

git push heroku master

Body:
I have an issue while deploying my Spring boot app to Heroku.

I am trying to deploy it as a java app instead of building and deploying a jar file.

I have used the free Postgresql in Heroku.

The error while pushing the app to Heroku master is:

remote:        [INFO] Changes detected - recompiling the module!
remote:        [INFO] Compiling 18 source files to /tmp/build_79201803/target/classes
remote:        [INFO] -------------------------------------------------------------
remote:        [ERROR] COMPILATION ERROR :
remote:        [INFO] -------------------------------------------------------------
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/post.java:[15,8] class Post is public, should be declared in a file named Post.java
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/user.java:[12,8] class User is public, should be declared in a file named User.java
remote:        [INFO] 2 errors
remote:        [INFO] -------------------------------------------------------------
remote:        [INFO] ------------------------------------------------------------------------
remote:        [INFO] BUILD FAILURE
remote:        [INFO] ------------------------------------------------------------------------
remote:        [INFO] Total time:  16.300 s
remote:        [INFO] Finished at: 2020-08-11T11:09:38Z
remote:        [INFO] ------------------------------------------------------------------------
remote:        [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project springblog: Compilation failure: Compilation failure:
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/post.java:[15,8] class Post is public, should be declared in a file named Post.java
remote:        [ERROR] /tmp/build_79201803/src/main/java/com/pukitbanta/springblog/model/user.java:[12,8] class User is public, should be declared in a file named User.java
remote:        [ERROR] -> [Help 1]
remote:        [ERROR]
remote:        [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
remote:        [ERROR] Re-run Maven using the -X switch to enable full debug logging.
remote:        [ERROR]
remote:        [ERROR] For more information about the errors and possible solutions, please read the following articles:
remote:        [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
remote:
remote:  !     ERROR: Failed to build app with Maven
remote:        We're sorry this build is failing! If you can't find the issue in application code,
remote:        please submit a ticket so we can help: https://help.heroku.com/
remote:
remote:  !     Push rejected, failed to compile Java app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:

The error here specifies that my User and Post models file name starts with lowercase letters.

But my file structure is:

I do not think the error is in the Models, and I am not able to find out the issue.

Body:
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                <source>1.8</source>
                <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Put this in the pom.xml.

git add .

git commit -m "Pom Changed"

git push heroku master


问:
Checking for values in Vectors of strings in Rust
I'm just getting started with Rust and have hit upon an issue where I'm getting a bit lost in types, pointers, borrowing and ownership.

I have a vector of Person structs, each of which has a name property. I'd like to collect all the names into another vector, and then check if that list contains a given string.

This is my code:

struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| p.name).collect();

    let some_name = String::from("bob");
    if names.iter().any(|n| n == some_name) {
    }
}
```
<p>This fails to compile:</p>
```error[E0277]: can't compare `&String` with `String`
  --> src/main.rs:13:31
   |
13 |     if names.iter().any(|n| n == some_name) {
   |                               ^^ no implementation for `&String == String`
   |
   = help: the trait `PartialEq<String>` is not implemented for `&String`
```

I think names should have the type Vec<String>, so I'm a bit lost as to where the &String comes from. Is this a case of me holding it wrong? I'm most familiar with JavaScript so I'm trying to apply those patterns, and may be not doing it in the most "rusty" way!

答:
The type of p is not Person but &Person, i.e. a reference to a value. In JavaScript there are no structs. The closest alternative is an object and JS objects are always stored in the heap and are accessed via references (although that's less explicit). In Rust you really need to think more about the memory layout of your data. That can complicate parts of your code, but it also gives you power and allows for better performance.

Here is a correct version of your code:

```<code>struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| &p.name).cloned().collect();

    let some_name = String::from("bob");
    if names.iter().any(|n| n == &some_name) {
    }
}
</code>```

Notice that in n == &some_name we are now comparing a &String with a &String.

Also note I added .cloned(), so that you avoid another error, related to moving the name strings.

A slightly more optimized version would be to only collect the references to the names, like this:

```<code>    let names: Vec<_> = people.iter().map(|p| &p.name).collect();
    let some_name = String::from("bob");
    if names.iter().any(|n| *n == &some_name) {
    }
</code>```

Note that in this version n is of type &&String, so we dereference it once via *n. That way we are again comparing a &String with a &String. Rust also allows you to write something like this: |&n| n == &some_name, which is practically the same.

Body:
I'm just getting started with Rust and have hit upon an issue where I'm getting a bit lost in types, pointers, borrowing and ownership.

I have a vector of Person structs, each of which has a name property. I'd like to collect all the names into another vector, and then check if that list contains a given string.

This is my code:

struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| p.name).collect();

    let some_name = String::from("bob");
    if names.iter().any(|n| n == some_name) {
    }
}

This fails to compile:

error[E0277]: can't compare `&String` with `String`
  --> src/main.rs:13:31
   |
13 |     if names.iter().any(|n| n == some_name) {
   |                               ^^ no implementation for `&String == String`
   |
   = help: the trait `PartialEq<String>` is not implemented for `&String`

I think names should have the type Vec<String>, so I'm a bit lost as to where the &String comes from. Is this a case of me holding it wrong? I'm most familiar with JavaScript so I'm trying to apply those patterns, and may be not doing it in the most "rusty" way!

Body:
The type of p is not Person but &Person, i.e. a reference to a value. In JavaScript there are no structs. The closest alternative is an object and JS objects are always stored in the heap and are accessed via references (although that's less explicit). In Rust you really need to think more about the memory layout of your data. That can complicate parts of your code, but it also gives you power and allows for better performance.

Here is a correct version of your code:

struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| &p.name).cloned().collect();

    let some_name = String::from("bob");
    if names.iter().any(|n| n == &some_name) {
    }
}

Notice that in n == &some_name we are now comparing a &String with a &String.

Also note I added .cloned(), so that you avoid another error, related to moving the name strings.

A slightly more optimized version would be to only collect the references to the names, like this:

    let names: Vec<_> = people.iter().map(|p| &p.name).collect();
    let some_name = String::from("bob");
    if names.iter().any(|n| *n == &some_name) {
    }

Note that in this version n is of type &&String, so we dereference it once via *n. That way we are again comparing a &String with a &String. Rust also allows you to write something like this: |&n| n == &some_name, which is practically the same.


问:
The return type 'int?' isn't a 'int', as required by the closure's contex
The following:

```<code>  var sortedByValue = SplayTreeMap<int, String>.from(
      fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2]));
</code>```

complains about null safety, then I add "?" to fruit[key1]?, ok then I.... ahhh?

```<code>import 'dart:collection';

void splayTreeMapExample(){
  var fruit = SplayTreeMap<int, String>();

  fruit[0] = 'Banana';
  fruit[5] = 'Plum';
  fruit[6] = 'Strawberry';
  fruit[2] = 'Orange';
  fruit[3] = 'Mango';
  fruit[4] = 'Blueberry';
  fruit[1] = 'Apple';

  print(fruit);

  fruit.forEach((key, val) {
    print('{ key: $key, value: $val}');
  });

  var sortedByValue = SplayTreeMap<int, String>.from(
      fruit, (key1, key2) => fruit[key1]?.compareTo(fruit[key2]));

  print(sortedByValue);
}
</code>```

答:
You got to love null safety(Null safety principles - Non-nullable by default, hmm, right - well it must be the "Map/fruit" return value):</p>
```<code>fruit, (key1, key2) => fruit[key1]!.compareTo(fruit[key2]!));
</code>```

Body:
The following:

  var sortedByValue = SplayTreeMap<int, String>.from(
      fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2]));

complains about null safety, then I add "?" to fruit[key1]?, ok then I.... ahhh?

import 'dart:collection';

void splayTreeMapExample(){
  var fruit = SplayTreeMap<int, String>();

  fruit[0] = 'Banana';
  fruit[5] = 'Plum';
  fruit[6] = 'Strawberry';
  fruit[2] = 'Orange';
  fruit[3] = 'Mango';
  fruit[4] = 'Blueberry';
  fruit[1] = 'Apple';

  print(fruit);

  fruit.forEach((key, val) {
    print('{ key: $key, value: $val}');
  });

  var sortedByValue = SplayTreeMap<int, String>.from(
      fruit, (key1, key2) => fruit[key1]?.compareTo(fruit[key2]));

  print(sortedByValue);
}

Body:
You got to love null safety(Null safety principles - Non-nullable by default, hmm, right - well it must be the "Map/fruit" return value):

fruit, (key1, key2) => fruit[key1]!.compareTo(fruit[key2]!));


问:
C# code to Display a Query Result in a List Box in windows forms
I am working on a software in which i need to display the search query results in a listbox.
mine is a medical software and im trying to display the list of medicines in the listbox.
im using c# for coding under Windows Visual studio 10 platform.
please help me wid this.
regards

Im using Sql server management studio as backend.
im using a button which when clicked will fire an event performing a query.
the query is select * from Table_name
i want to show the query list in the listbox..

答:
Within the button_click event:

Configure a SqlCommand with CommandType=Text and CommandText="your query".

Execute the SqlCommand with ExecuteReader.

Convert the resulting SqlDataReader in a DataTable with dataTable.Load(dataReader);

Make that datatable your ListBox's Data Source (libYourListBox.DataSource = dataTable).

Define your list box's DisplayMember to the name of the column that holds the medicine's name.

Define your list box's ValueMember to the id or code of the medicin.

That should work.


问:
Drupal 8 - Ajax modal not working from dynamically created links
I have added link in my website like bellow

```<code><a href="/product/info/100" class="use-ajax" data-dialog-type="modal">Info</a>
</code>```

This is working if it is loaded at the time of page load.
But the issue is, I need to create the links when user chooses some option . I have created new link like this during some customer action after page load.But the modal not showing from the newly created links.

答:
```<code>When html is loaded by ajax and drupal modal popup does not work.
For me below code worked.

HTML code:
    <button class="use-ajax" onclick="function_name("/url") ></button>

Jquery code
    function function_name(url){
      Drupal.ajax({url: url}).execute();
    }
</code>```

Body:
I have added link in my website like bellow

Info

This is working if it is loaded at the time of page load.
But the issue is, I need to create the links when user chooses some option . I have created new link like this during some customer action after page load.But the modal not showing from the newly created links.


问:
What’s the best way to compute multiple hashes of small integer numbers for Bloom filter?
I’ve looked at Murmur3 and Meow but they both seem to be optimized for bandwidth when hashing long arrays. I don’t have any arrays, I only have uint32_t integers on input. My inputs are small non-negative numbers usually under a few millions, all divisible by 3. The probability density is uniform over the range [ 0 .. N*3 ] for some integer number N.

Is the following code good enough in terms of performance, and quality of distribution?

```<code>// Count of bits in the complete Bloom filter
// Using 32kb or memory to hopefully stay in L1D cache
constexpr size_t countBits = 1024 * 32 * 8;

// These bytes are from random.org
// Cryptographic strength is irrelevant, we only need performance here.
static const __m128i seed = _mm_setr_epi8( (char)0x8a, (char)0xf4, 0x30, (char)0x91, (char)0x07, 0x05, 0x45, (char)0x99, 0x2f, (char)0x95, 0x4a, (char)0xa2, (char)0x84, (char)0x88, (char)0xe6, (char)0x09 );

// Mask to extract lower bits from the hash
static const __m128i andMask = _mm_set1_epi32( countBits - 1 );

// Compute 16 bytes of hash function, mask upper bits in every 32-bit lane, computing 4 bit positions for the Bloom filter.
inline __m128i hash( uint32_t key )
{
    // Broadcast integer to 32-bit lanes
    __m128i a = _mm_set1_epi32( (int)key );
    // Abuse AES-NI decrypting instruction to make a 16-byte hash.
    // That thing only takes 4 cycles of latency to complete.
    a = _mm_aesdec_si128( a, seed );
    // Mask upper bits in the lanes so the _mm_extract_epi32 returns position of bits in the Bloom filter to set or test
    a = _mm_and_si128( a, andMask );
    return a;
}
</code>```

Update: the question is not opinion based because count of hash collisions is trivially measurable. It’s for this very reason I’ve specified the distribution of my input values.

答:
It sounds like you might not need to use a hash function at all:

My inputs are small non-negative numbers usually under a few millions, all divisible by 3. The probability density is uniform over the range [ 0 .. N*3 ] for some integer number N.

The whole point of using a hash function for a bloom filter is that given an input whose probability density is not uniform, to make it uniform. Of course, even if statistically every value is equally likely to occur, it can still be that a given input is correlated with a previous input (say, values close together are likely to appear in groups), in which case you still might need to apply a hash function.

Is the following code good enough in terms of performance, and quality of distribution?

That is hard to answer, only you can tell if it meets the requirements of your application. A single round of AES should not be considered cryptographically secure, and even if it were, using a known fixed seed would allow an attacker that can control the inputs to your Bloom filter to distribute the inputs in such a way that your Bloom filter is very inefficient. But you said it yourself:

[...] count of hash collisions is trivially measurable.

You can measure the distribution of hash values before and after applying the AES decryption round on realistic input, and thus check if it is good enough for you.

Body:
I’ve looked at Murmur3 and Meow but they both seem to be optimized for bandwidth when hashing long arrays. I don’t have any arrays, I only have uint32_t integers on input. My inputs are small non-negative numbers usually under a few millions, all divisible by 3. The probability density is uniform over the range [ 0 .. N*3 ] for some integer number N.

Is the following code good enough in terms of performance, and quality of distribution?

// Count of bits in the complete Bloom filter
// Using 32kb or memory to hopefully stay in L1D cache
constexpr size_t countBits = 1024 * 32 * 8;

// These bytes are from random.org
// Cryptographic strength is irrelevant, we only need performance here.
static const __m128i seed = _mm_setr_epi8( (char)0x8a, (char)0xf4, 0x30, (char)0x91, (char)0x07, 0x05, 0x45, (char)0x99, 0x2f, (char)0x95, 0x4a, (char)0xa2, (char)0x84, (char)0x88, (char)0xe6, (char)0x09 );

// Mask to extract lower bits from the hash
static const __m128i andMask = _mm_set1_epi32( countBits - 1 );

// Compute 16 bytes of hash function, mask upper bits in every 32-bit lane, computing 4 bit positions for the Bloom filter.
inline __m128i hash( uint32_t key )
{
    // Broadcast integer to 32-bit lanes
    __m128i a = _mm_set1_epi32( (int)key );
    // Abuse AES-NI decrypting instruction to make a 16-byte hash.
    // That thing only takes 4 cycles of latency to complete.
    a = _mm_aesdec_si128( a, seed );
    // Mask upper bits in the lanes so the _mm_extract_epi32 returns position of bits in the Bloom filter to set or test
    a = _mm_and_si128( a, andMask );
    return a;
}

Update: the question is not opinion based because count of hash collisions is trivially measurable. It’s for this very reason I’ve specified the distribution of my input values.


问:
I keep getting a blank screen in React.JS
I was following a tutorial and my localhost is completely blank after importing {Link} from react-router-dom. Followed word for word but my local host is blank as soon as I added link in navbar.js.

```<code>import React from 'react';
import {Link} from 'react-router-dom';

function Navbar() {
    return(
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <div class="container-fluid">

                <Link to="/" class="navbar-brand">SkyCloud</Link>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-togglser-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <Link to="/" class="nav-link active">Home</Link>
                    </li>

                    <li class="nav-item">
                    <Link to="/about" class="nav-link active">About</Link>
                    </li>

                    <li class="nav-item">
                    <Link to="/contact" class="nav-link active">Contact</Link>
                    </li>

                    </ul>

                </div>
                </div>
      </nav>

    );

}

export default Navbar;
</code>```

And this is my App.js file...

```<code>import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

    <Router>
    <div>
     <Navbar/>
    <Home/>
   <About/>
   <Contact/>

    </div>
    </Router>

  );
}

export default App;
</code>```

答:
If you don't know which version you use . please check package.json and search react-router-dom . Then you will see the version.
(React router dom v6)
If you use link ,You need to use router and routes. I think no error is shown your project. This is the documentation

https://reactrouter.com/docs/en/v6/getting-started/installation#create-react-app

This is demo code of routes , route

```<code>       import * as React from "react";
       import { Routes, Route, Link } from "react-router-dom";

       function App() {
        return (
         <div className="App">
            <h1>Welcome to React Router!</h1>
             <Routes>
               <Route path="/" element={<Home />} />
               <Route path="about" element={<About />} />
            </Routes>
        </div>
      );
     }
</code>```

If you Use V5

```<code> import {
   BrowserRouter,
   Switch,
   Route,
   Link,
   useRouteMatch
  } from "react-router-dom";

 function App() {
   return (
     <BrowserRouter>
      <Switch>
        <Route exact path="/">
         <Home />
       </Route>
       <Route path="/users">
         <Users />
       </Route>
    </Switch>
  </BrowserRouter>
 );
}
</code>```

react router dom v5 documentation
https://reactrouter.com/docs/en/v6/upgrading/v5

Body:
I was following a tutorial and my localhost is completely blank after importing {Link} from react-router-dom. Followed word for word but my local host is blank as soon as I added link in navbar.js.

import React from 'react';
import {Link} from 'react-router-dom';

function Navbar() {
    return(

                <Link to="/" class="navbar-brand">SkyCloud</Link>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                        <Link to="/" class="nav-link active">Home</Link>

                    <Link to="/about" class="nav-link active">About</Link>

                    <Link to="/contact" class="nav-link active">Contact</Link>

    );

}

export default Navbar;

And this is my App.js file...

import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

    <Router>

     <Navbar/>
    <Home/>
   <About/>
   <Contact/>

    </Router>

  );
}

export default App;

Body:
If you don't know which version you use . please check package.json and search react-router-dom . Then you will see the version.
(React router dom v6)
If you use link ,You need to use router and routes. I think no error is shown your project. This is the documentation

https://reactrouter.com/docs/en/v6/getting-started/installation#create-react-app

This is demo code of routes , route

       import * as React from "react";
       import { Routes, Route, Link } from "react-router-dom";

       function App() {
        return (
         <div className="App">
            <h1>Welcome to React Router!</h1>
             <Routes>
               <Route path="/" element={<Home />} />
               <Route path="about" element={<About />} />
            </Routes>
        </div>
      );
     }

If you Use V5

 import {
   BrowserRouter,
   Switch,
   Route,
   Link,
   useRouteMatch
  } from "react-router-dom";

 function App() {
   return (
     <BrowserRouter>
      <Switch>
        <Route exact path="/">
         <Home />
       </Route>
       <Route path="/users">
         <Users />
       </Route>
    </Switch>
  </BrowserRouter>
 );
}

react router dom v5 documentation
https://reactrouter.com/docs/en/v6/upgrading/v5


答:
Several things going on there:

&String comes from the fact that iter() iterates over the collection without consuming it, and therefore can only give you references into items of the collection.

You can address the inability to compare &String to String by borrowing the latter, i.e. changing n == some_name to n == &some_name.

After you do that, the compiler will tell you that p.name attempts to move name out of the reference p. To get rid of it, you can change p.name to &p.name, thus creating a Vec<&String>.

...after which n will become &&String (!), so you'll need n == &&some_name. The example then compiles.

Title: Checking for values in Vectors of strings in Rust


问:
Why does hard-coding in numbers work, but using variables with the same values, doesn't?
I'm writing a program that is a game where you have to guess whichever random 4 digit integer that the computer generates. I'm having trouble with the input validation - more specifically, my isDigit() method, which aims to make sure all inputs from userGuess are digits 0 - 9:

```<code>    private static boolean isDigit(char indexPos) { // verifies if the input char is a digit 0-9 or not
        if(indexPos == 0 || indexPos == 1 || indexPos == 2 || indexPos == 3 || indexPos == 4 || indexPos == 5 || indexPos == 6 || indexPos == 7 || indexPos == 8 || indexPos == 9) {
            return true;
        }
        else {
            return false;
        }
    }
</code>```

If I hardcode in things like

```<code>isDigit(1)
</code>```

it evaluates as true, but if I plug in variables, it returns false. Mainly, this returns false, even when all index positions of userGuess are digits 0-9:

```<code>isDigit(userGuess.charAt(i)) // returns false even when index pos i is [0-9]
</code>```

I'm utterly confused and stumped as to why this happens. For context, here's the whole if and for loop situation for the validation:

```<code>numGuess++;
System.out.print("Guess " + numGuess + ": ");
userGuess = kbd.nextLine();
System.out.println("DEBUG: userGuess.length() : " + userGuess.length());

// validate that the input is a valid input (a 4 digit natural number, incl 0000)
if(userGuess.length() < 4 || userGuess.length() >= 5){
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
}
else if(userGuess.length() == 4) {
   for(int i = 0;  i <= 3; i++) {
     if(isDigit(userGuess.charAt(i)) == true) {
        validateCount++;
     }
}
</code>```

I also have, what I assume to be the same issue, on validating if userGuess.length() == 4. If I output userGuess.legnth() on the console, it provides the correct number, and when == 4, this if loop doesn't run, even though the condition is met:

```<code>if (userGuess.length() < 4 || userGuess.length() >= 5) {
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
} else if (userGuess.length() == 4) { // avoid out of bounds errors for inputs less than 4 digits
   for (int i = 0; i <= 3; i++) { // userGuess will never have an index above 3, as it is a 4 digit number
if (isDigit(userGuess.charAt(i)) == true && userGuess.length() == 4) { // verify that the userInput is a 4 digit integer
    validateCount++;
}
</code>```

答:
You are comparing the char indexPos with the integers from 0 to 9. Try comparing indexPos with '0','1','2',...
That way you compared if the char indexPos with another char.</p>

Body:
I'm writing a program that is a game where you have to guess whichever random 4 digit integer that the computer generates. I'm having trouble with the input validation - more specifically, my isDigit() method, which aims to make sure all inputs from userGuess are digits 0 - 9:

    private static boolean isDigit(char indexPos) { // verifies if the input char is a digit 0-9 or not
        if(indexPos == 0 || indexPos == 1 || indexPos == 2 || indexPos == 3 || indexPos == 4 || indexPos == 5 || indexPos == 6 || indexPos == 7 || indexPos == 8 || indexPos == 9) {
            return true;
        }
        else {
            return false;
        }
    }

If I hardcode in things like

isDigit(1)

it evaluates as true, but if I plug in variables, it returns false. Mainly, this returns false, even when all index positions of userGuess are digits 0-9:

isDigit(userGuess.charAt(i)) // returns false even when index pos i is [0-9]

I'm utterly confused and stumped as to why this happens. For context, here's the whole if and for loop situation for the validation:

numGuess++;
System.out.print("Guess " + numGuess + ": ");
userGuess = kbd.nextLine();
System.out.println("DEBUG: userGuess.length() : " + userGuess.length());

// validate that the input is a valid input (a 4 digit natural number, incl 0000)
if(userGuess.length() < 4 || userGuess.length() >= 5){
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
}
else if(userGuess.length() == 4) {
   for(int i = 0;  i <= 3; i++) {
     if(isDigit(userGuess.charAt(i)) == true) {
        validateCount++;
     }
}

I also have, what I assume to be the same issue, on validating if userGuess.length() == 4. If I output userGuess.legnth() on the console, it provides the correct number, and when == 4, this if loop doesn't run, even though the condition is met:

if (userGuess.length() < 4 || userGuess.length() >= 5) {
   System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
} else if (userGuess.length() == 4) { // avoid out of bounds errors for inputs less than 4 digits
   for (int i = 0; i <= 3; i++) { // userGuess will never have an index above 3, as it is a 4 digit number
if (isDigit(userGuess.charAt(i)) == true && userGuess.length() == 4) { // verify that the userInput is a 4 digit integer
    validateCount++;
}


问:
LSTM for sentiment analysis
I saw this tensorflow model which is used for telling if text is positive or negative, and I don't fully understand it. I know that LSTM saves the words and predict the next words based on the previous words, but how does this help network to distinguish emotions of the text?</p>
```<code>def tensorflow_based_model():
    inputs = Input(name='inputs',shape=[max_len])
    layer = Embedding(2000,50,input_length=max_len)(inputs)
    layer = LSTM(64)(layer)
    layer = Dense(256,name='FC1')(layer)
    layer = Activation('relu')(layer)
    layer = Dropout(0.5)(layer)
    layer = Dense(1,name='out_layer')(layer)
    layer = Activation('sigmoid')(layer)
    model = Model(inputs=inputs,outputs=layer)
    return model
</code>```

答:
Altough LSTM can be used in the text generation, the main use of LSTM (or any recurrent neural network layer) is to understand sequences. You can find more information in this blog posts:

The Unreasonable Effectiveness of Recurrent Neural Networks

Understanding LSTM Networks

In the case of sentiment analysis, Instead of helping to generate new word, LSTM helps us understand what was said. It basicaly reads over the string and keeps some important information about the previously said words.

Title: LSTM for sentiment analysis

Body:
I saw this tensorflow model which is used for telling if text is positive or negative, and I don't fully understand it. I know that LSTM saves the words and predict the next words based on the previous words, but how does this help network to distinguish emotions of the text?

def tensorflow_based_model():
    inputs = Input(name='inputs',shape=[max_len])
    layer = Embedding(2000,50,input_length=max_len)(inputs)
    layer = LSTM(64)(layer)
    layer = Dense(256,name='FC1')(layer)
    layer = Activation('relu')(layer)
    layer = Dropout(0.5)(layer)
    layer = Dense(1,name='out_layer')(layer)
    layer = Activation('sigmoid')(layer)
    model = Model(inputs=inputs,outputs=layer)
    return model


问:
track tag in html is always showing : unsafe attempt to load url.. What is wrong?
I am trying to use track tag to put a subtitle to my video. First of all the captions button is available and once I click it disappears and the inspect shows me an error appearing on the right.

This is my simple code:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <video controls >
        <source src="photos/c.mp4" type="video/mp4">
        <track src="c.vtt>" kind="subtitles" srclang="en" label="english">
        </video>
    </body>
</html>
</code>```

答: Apparently it's because Chrome and Edge prohibit HTML files accessing VTT files from a local drive, and I have yet to find a simple and easy fix for this issue. It works perfectly fine on Internet Explorer though.</p>

Body:
I am trying to use track tag to put a subtitle to my video. First of all the captions button is available and once I click it disappears and the inspect shows me an error appearing on the right.

This is my simple code:

<!DOCTYPE html>

        <meta charset="UTF-8">

        <video controls >
        <source src="photos/c.mp4" type="video/mp4">
        <track src="c.vtt>" kind="subtitles" srclang="en" label="english">
        </video>


问:
How to hot-reload properties in Java EE and Spring Boot?
Many in-house solutions come to mind. Like having the properties in a database and poll it every N secs. Then also check the timestamp modification for a .properties file and reload it.

But I was looking in Java EE standards and spring boot docs and I can't seem to find some best way of doing it.

I need my application to read a properties file(or env. variables or DB parameters), then be able to re-read them. What is the best practice being used in production?

A correct answer will at least solve one scenario (Spring Boot or Java EE) and provide a conceptual clue on how to make it work on the other

答:
For spring boot, there's a really good article on this topic here, but for multiple property files it doesn't work perfectly.
In my case I had 2 property files, one non sensitive and one containing the passwords. I proceeded with the following:

```<code><dependency>
    <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>1.10</version>
</dependency>
</code>```

Extend the spring's PropertySource so that you can add the reloadable version to the environment.

```<code>public class ReloadablePropertySource extends PropertySource {

    private final PropertiesConfiguration propertiesConfiguration;

    public ReloadablePropertySource(String name, String path, ConfigurationListener listener) {
        super(StringUtils.hasText(name) ? name : path);
        try {
            this.propertiesConfiguration = getConfiguration(path, listener);
        } catch (Exception e) {
            throw new MissingRequiredPropertiesException();
        }
    }

    @Override
    public Object getProperty(String s) {
        return propertiesConfiguration.getProperty(s);
    }

    private PropertiesConfiguration getConfiguration(String path, ConfigurationListener listener) throws ConfigurationException {
        PropertiesConfiguration configuration = new PropertiesConfiguration(path);
        FileChangedReloadingStrategy reloadingStrategy = new FileChangedReloadingStrategy();
        reloadingStrategy.setRefreshDelay(5000);
        configuration.setReloadingStrategy(reloadingStrategy);
        configuration.addConfigurationListener(listener);
        return configuration;
    }
}
</code>```

Now add all of your properties files (now reloadable) inside the spring's env

```<code>@Configuration
public class ReloadablePropertySourceConfig {

    private final ConfigurableEnvironment env;

    @Value("${spring.config.location}")
    private String appConfigPath;

    @Value("${spring.config.additional-location}")
    private String vaultConfigPath;

    public ReloadablePropertySourceConfig(ConfigurableEnvironment env) {
        this.env = env;
    }

    @Bean
    @ConditionalOnProperty(name = "spring.config.location")
    public ReloadablePropertySource getAppConfigReloadablePropertySource(){
        ReloadablePropertySource rps = new ReloadablePropertySource("dynamicNonSensitive", appConfigPath, new PropertiesChangeListener());
        MutablePropertySources sources = env.getPropertySources();
        sources.addFirst(rps);
        return rps;
    }

    @Bean
    @ConditionalOnProperty(name = "spring.config.additional-location")
    public ReloadablePropertySource getVaultReloadablePropertySource(){
        ReloadablePropertySource rps = new ReloadablePropertySource("dynamicVault", vaultConfigPath, new PropertiesChangeListener());
        MutablePropertySources sources = env.getPropertySources();
        sources.addFirst(rps);
        return rps;
    }

    private static class PropertiesChangeListener implements ConfigurationListener{

        @Override
        public void configurationChanged(ConfigurationEvent event) {
            if (!event.isBeforeUpdate()){
                System.out.println("config refreshed!");
            }
        }
    }
}
</code>```

From the article

We've added the new property source as the first item because we want it to override any existing property with the same key

In our case, we have 2 "reloadable" property sources and both will be looked up first.

Finally create one more class from which we can access the env's properties

```<code>@Component
public class ConfigProperties {

    private final Environment environment;

    public ConfigProperties(Environment environment) {
        this.environment = environment;
    }

    public String getProperty(String name){
        return environment.getProperty(name);
    }
}
</code>```

Now you can autowire ConfigProperties and always get the latest property in the files without requiring to restart the application.

```<code>@RestController
@Slf4j
public class TestController {

    @Autowired
    private ConfigProperties env;

    @GetMapping("/refresh")
    public String test2() {
        log.info("hit");
        String updatedProperty = env.getProperty("test.property");
        String password = env.getProperty("db.password");
        return updatedProperty + "\n" + password;
    }

}
</code>```

where test.property is coming from 1st file and db.password is coming from another.

Body:
For spring boot, there's a really good article on this topic here, but for multiple property files it doesn't work perfectly.
In my case I had 2 property files, one non sensitive and one containing the passwords. I proceeded with the following:

<dependency>
    <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>1.10</version>
</dependency>

Extend the spring's PropertySource so that you can add the reloadable version to the environment.

public class ReloadablePropertySource extends PropertySource {

    private final PropertiesConfiguration propertiesConfiguration;

    public ReloadablePropertySource(String name, String path, ConfigurationListener listener) {
        super(StringUtils.hasText(name) ? name : path);
        try {
            this.propertiesConfiguration = getConfiguration(path, listener);
        } catch (Exception e) {
            throw new MissingRequiredPropertiesException();
        }
    }

    @Override
    public Object getProperty(String s) {
        return propertiesConfiguration.getProperty(s);
    }

    private PropertiesConfiguration getConfiguration(String path, ConfigurationListener listener) throws ConfigurationException {
        PropertiesConfiguration configuration = new PropertiesConfiguration(path);
        FileChangedReloadingStrategy reloadingStrategy = new FileChangedReloadingStrategy();
        reloadingStrategy.setRefreshDelay(5000);
        configuration.setReloadingStrategy(reloadingStrategy);
        configuration.addConfigurationListener(listener);
        return configuration;
    }
}

Now add all of your properties files (now reloadable) inside the spring's env

@Configuration
public class ReloadablePropertySourceConfig {

    private final ConfigurableEnvironment env;

    @Value("${spring.config.location}")
    private String appConfigPath;

    @Value("${spring.config.additional-location}")
    private String vaultConfigPath;

    public ReloadablePropertySourceConfig(ConfigurableEnvironment env) {
        this.env = env;
    }

    @Bean
    @ConditionalOnProperty(name = "spring.config.location")
    public ReloadablePropertySource getAppConfigReloadablePropertySource(){
        ReloadablePropertySource rps = new ReloadablePropertySource("dynamicNonSensitive", appConfigPath, new PropertiesChangeListener());
        MutablePropertySources sources = env.getPropertySources();
        sources.addFirst(rps);
        return rps;
    }

    @Bean
    @ConditionalOnProperty(name = "spring.config.additional-location")
    public ReloadablePropertySource getVaultReloadablePropertySource(){
        ReloadablePropertySource rps = new ReloadablePropertySource("dynamicVault", vaultConfigPath, new PropertiesChangeListener());
        MutablePropertySources sources = env.getPropertySources();
        sources.addFirst(rps);
        return rps;
    }

    private static class PropertiesChangeListener implements ConfigurationListener{

        @Override
        public void configurationChanged(ConfigurationEvent event) {
            if (!event.isBeforeUpdate()){
                System.out.println("config refreshed!");
            }
        }
    }
}

From the article

We've added the new property source as the first item because we want it to override any existing property with the same key

In our case, we have 2 "reloadable" property sources and both will be looked up first.

Finally create one more class from which we can access the env's properties

@Component
public class ConfigProperties {

    private final Environment environment;

    public ConfigProperties(Environment environment) {
        this.environment = environment;
    }

    public String getProperty(String name){
        return environment.getProperty(name);
    }
}

Now you can autowire ConfigProperties and always get the latest property in the files without requiring to restart the application.

@RestController
@Slf4j
public class TestController {

    @Autowired
    private ConfigProperties env;

    @GetMapping("/refresh")
    public String test2() {
        log.info("hit");
        String updatedProperty = env.getProperty("test.property");
        String password = env.getProperty("db.password");
        return updatedProperty + "\n" + password;
    }

}

where test.property is coming from 1st file and db.password is coming from another.


问:
How to install aws-cli on alpine?
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

```<code>  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages
</code>```

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

```<code>~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'
</code>```

Thanks!

答:
The method published on the official awscliv2 install page for general Linux works fine on Alpine.

```<code>RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" && \
    unzip ./awscliv2.zip && \
    rm -f ./awscliv2.zip && \
    ./aws/install -i /usr/local/aws -b /bin && \
    rm -rf ./aws
</code>```

Just clean up your zip and leftover install files.

https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

Title: How to install aws-cli on alpine?

Body:
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'

Thanks!

Body:
The method published on the official awscliv2 install page for general Linux works fine on Alpine.

RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" && \
    unzip ./awscliv2.zip && \
    rm -f ./awscliv2.zip && \
    ./aws/install -i /usr/local/aws -b /bin && \
    rm -rf ./aws

Just clean up your zip and leftover install files.

https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html


问:
Excel - Count days for each month from start and end date range
I am trying to write an excel formula which can be dragged across a row of cells to give the number of days in each month between two specified dates. Can any one help with Forumla or Macro please.

Example under attached image B4:C4 has total 5 days vacation, 3 in Aug 2021 and 2 days in Sep 2021.

答:
If C4 is end date and B4 is start date so just  D4=C4-B4+1

Then if F3 it is start of month (e.g. 01.08.2021) and in F4 we want to receive number of days, so it will be
=MAX(0;(IF((EDATE(F3;1)-1)<C4;EDATE(F3;1)-1;C4))+1-(IF(F3>B4;F3;B4)))

The last between beginnig of month and beginning of the period is taken as start point and the first between end of period and end of the month taken as the end point.

If the period is totally outside the given month then the result is negative and it is changed to 0 by function MAX.


问:
Is it possible to recover certificate thumbprint (sha1 fingerprint) from private key material?
Is it possible to recover certificate thumbprint (sha1 fingerprint) only from private key that will match original certificate thumbprint?

I can not find any information about how thumbprints are generated.

Private key material:
I have a .PFX file with single certificate and it's private key. From .PFX I export only private key:

openssl rsa -inform p12 -in cert.pfx -outform der -out cert.key.der

答:
It is not possible to get a certificate fingerprint from the private key only. The private key matches only the public key in the certificate. There can actually be multiple certificates using the same public and private key, all having different certificate fingerprints. This is not uncommon - certificate renewals often use the same key pair as the previous (expired) certificate.

What would be possible is to get the public key fingerprint, but not the certificate fingerprint.


问:
How to wait until navigator.notification.prompt() input has been given
I am using a Cordova app to embed a React app. In a certain point, the user connects to the camera and a notification appears when a QR code is detected. I want that the code execution waits until user has entered his/her answer "Yes/No", but I can't get it to work. Notification prompt message works as expected though.

I need it to pause somehow, as in an async function (like  prompt would, for instance). How could I pause the code execution until the user has chosen Yes/No in screen? I guess with some async/await but don't see where... I have tried unsuccessfully so far:

```<code>let test = null;
let input2 = null;
notification = navigator.notification.prompt("Do you know this QR code?",
     async function(input) {
     input2 = input;
     test = await NotificationFunction(input, Camera_content);
     console.log(test)
     console.log('input2')
     return [test, input2]
     });

let test2= await notification
console.log(test2)
console.log(notification)
console.log(await test)
</code>```

Thanks a lot in advance!

答:
Maybe you can use something like this:

const promise = new Promise((resolve, reject) => {
  navigator.notification.prompt(
    'Do you know this QR code?',
    async function (input) {
      test = await NotificationFunction(input, Camera_content);
      resolve([test, input]);
    },
  );
});

const [test, input] = await promise
```

Also maybe this can help https://javascript.info/promisify

Body:
I am using a Cordova app to embed a React app. In a certain point, the user connects to the camera and a notification appears when a QR code is detected. I want that the code execution waits until user has entered his/her answer "Yes/No", but I can't get it to work. Notification prompt message works as expected though.

I need it to pause somehow, as in an async function (like  prompt would, for instance). How could I pause the code execution until the user has chosen Yes/No in screen? I guess with some async/await but don't see where... I have tried unsuccessfully so far:

let test = null;
let input2 = null;
notification = navigator.notification.prompt("Do you know this QR code?",
     async function(input) {
     input2 = input;
     test = await NotificationFunction(input, Camera_content);
     console.log(test)
     console.log('input2')
     return [test, input2]
     });

let test2= await notification
console.log(test2)
console.log(notification)
console.log(await test)

Thanks a lot in advance!

Body:
Maybe you can use something like this:

const promise = new Promise((resolve, reject) => {
  navigator.notification.prompt(
    'Do you know this QR code?',
    async function (input) {
      test = await NotificationFunction(input, Camera_content);
      resolve([test, input]);
    },
  );
});

const [test, input] = await promise

Also maybe this can help https://javascript.info/promisify


问:
django.core.exceptions.FieldError: Cannot resolve keyword 'date' into field. Join on 'date' not permitted
```<code># Here is my models
</code>```

This is my CustmerBuySell model DB designed.

```<code>class CustomerBuySell(models.Model):
    customer = models.ForeignKey(CustomerAdd, on_delete=models.CASCADE)
    customer_buy_sell_debit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    customer_buy_sell_credit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    description = models.CharField(max_length=250, blank=True)
    date = models.DateField()
    sms = models.BooleanField(default=False)
    picture = models.ImageField(upload_to='customer_buy_sell_pics', default='images.png')

    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)

    def __str__(self):
        return self.customer.customer_name

    class Meta:
        verbose_name = "Customer BuySell"
        verbose_name_plural = "Customer BuySell"

# Here, is my View.
</code>```

This is the class-based APIView, which I have used. And try to use the aggregate query in this view.

```<code>class DailyCustomerBuySellAPIView(APIView):

    def get(self, request):
        customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by(
            'date__date').annotate(available=Count('date__date'))
        serializer = CustomerBuySellSerializer(customer_buy_sell, many=True)
        return Response({"customer_buy_sell": serializer.data})

# And, finally here are my Serializers
</code>```

I have no idea what's the problem! Please help me.

```<code>class CustomerBuySellSerializer(serializers.ModelSerializer):
    # customer = CustomerAddSerializer()

    class Meta:
        model = CustomerBuySell
        fields = '__all__'

    def to_representation(self, instance):
        representation = super(CustomerBuySellSerializer, self).to_representation(instance)

        if instance.customer is not None:
            customer_name = instance.customer.customer_name
            previous_due = instance.customer.previous_due
            representation['custo`enter code here`mer_name'] = customer_name
            representation['previous_due'] = previous_due
            return representation
</code>```

答:
There are many problems with your approach. Let me mention each of them one by one:

First of all remove date__date from your APIVIew

Before:

```<code> customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by(
            'date__date').annotate(available=Count('date__date'))
</code>```

Instead, write it as:

```<code>from django.db.models.functions import Extract

 customer_buy_sell = CustomerBuySell.objects.annotate(day=Extract('date','day')).values('day').order_by('day')
</code>```

if you need a count of the days then you can try

```<code>customer_buy_sell_count = customer_buy_sell.count()
</code>```

Another thing that you are doing wrong is you pass a dict to serializer as you are already using values that return a dictionary of days and not object of CustomerBuySell so you do not need to pass it to serializer otherwise you have to do it according to your need.

In CustomerBuySellSerializer you are using a model serializer with __all__ while you are passing an extra fields day that is not part of it.

So in short there are so many syntax issues with your Django and Django Rest Framework.Great way to fix such issues is to set with an experience programmer so that he can improve the flow of the code. Later on you can focus on logic.

Body:
# Here is my models

This is my CustmerBuySell model DB designed.

class CustomerBuySell(models.Model):
    customer = models.ForeignKey(CustomerAdd, on_delete=models.CASCADE)
    customer_buy_sell_debit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    customer_buy_sell_credit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    description = models.CharField(max_length=250, blank=True)
    date = models.DateField()
    sms = models.BooleanField(default=False)
    picture = models.ImageField(upload_to='customer_buy_sell_pics', default='images.png')

    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)

    def __str__(self):
        return self.customer.customer_name

    class Meta:
        verbose_name = "Customer BuySell"
        verbose_name_plural = "Customer BuySell"

# Here, is my View.

This is the class-based APIView, which I have used. And try to use the aggregate query in this view.

class DailyCustomerBuySellAPIView(APIView):

    def get(self, request):
        customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by(
            'date__date').annotate(available=Count('date__date'))
        serializer = CustomerBuySellSerializer(customer_buy_sell, many=True)
        return Response({"customer_buy_sell": serializer.data})

# And, finally here are my Serializers

I have no idea what's the problem! Please help me.

class CustomerBuySellSerializer(serializers.ModelSerializer):
    # customer = CustomerAddSerializer()

    class Meta:
        model = CustomerBuySell
        fields = '__all__'

    def to_representation(self, instance):
        representation = super(CustomerBuySellSerializer, self).to_representation(instance)

        if instance.customer is not None:
            customer_name = instance.customer.customer_name
            previous_due = instance.customer.previous_due
            representation['custo`enter code here`mer_name'] = customer_name
            representation['previous_due'] = previous_due
            return representation

Body:
There are many problems with your approach. Let me mention each of them one by one:

First of all remove date__date from your APIVIew

Before:

 customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by(
            'date__date').annotate(available=Count('date__date'))

Instead, write it as:

from django.db.models.functions import Extract

 customer_buy_sell = CustomerBuySell.objects.annotate(day=Extract('date','day')).values('day').order_by('day')

if you need a count of the days then you can try

customer_buy_sell_count = customer_buy_sell.count()

Another thing that you are doing wrong is you pass a dict to serializer as you are already using values that return a dictionary of days and not object of CustomerBuySell so you do not need to pass it to serializer otherwise you have to do it according to your need.

In CustomerBuySellSerializer you are using a model serializer with __all__ while you are passing an extra fields day that is not part of it.

So in short there are so many syntax issues with your Django and Django Rest Framework.Great way to fix such issues is to set with an experience programmer so that he can improve the flow of the code. Later on you can focus on logic.


问:
How to name subsets of a dataframe inside a loop
I'm having trouble naming the subsets I create inside a loop. I want to give each one the five first letters of the condition (or even just the iteration number) as a name but I haven't figured out how to.

Here's my code

```<code>list_mun=list(ensud21.NOM_MUN.unique())
for mun in list_mun:
    name=ensud21[ensud21['NOM_MUN']== mun]
</code>```

list_mun is a list with the unique values that a column of my dataframe can take. Inside the for loop I wrote name where I want what I explained before. I am unable to give each dataframe a different name. Thankyou!

答:
You shouldn't try to set variable names dynamically. Use a container, a dictionary is perfect here:

```<code>list_mun=list(ensud21.NOM_MUN.unique())

out_dic = {}
for mun in list_mun:
    # here we set "mun" as key
    out_dict[mun] = ensud21[ensud21['NOM_MUN']== mun]
</code>```

Then subsets with:

```<code>out_dic[the_mun_you_want]
</code>```

Body:
I'm having trouble naming the subsets I create inside a loop. I want to give each one the five first letters of the condition (or even just the iteration number) as a name but I haven't figured out how to.

Here's my code

list_mun=list(ensud21.NOM_MUN.unique())
for mun in list_mun:
    name=ensud21[ensud21['NOM_MUN']== mun]

list_mun is a list with the unique values that a column of my dataframe can take. Inside the for loop I wrote name where I want what I explained before. I am unable to give each dataframe a different name. Thankyou!

Body:
You shouldn't try to set variable names dynamically. Use a container, a dictionary is perfect here:

list_mun=list(ensud21.NOM_MUN.unique())

out_dic = {}
for mun in list_mun:
    # here we set "mun" as key
    out_dict[mun] = ensud21[ensud21['NOM_MUN']== mun]

Then subsets with:

out_dic[the_mun_you_want]


问:
Why is this variadic function ambiguous?
This is related to my earlier post. I'd like to know why one attempted solution didn't work.

```<code>template <typename... T>             /* A */
size_t num_args ();

template <>
size_t num_args <> ()
{
    return 0;
}

template <typename H, typename... T> /* B */
size_t num_args ()
{
    return 1 + num_args <T...> ();
}
</code>```

If I try to call, say, num_args<int,float>() then the error is that the function call is ambiguous:

A with T={int,float}

B with H=int, T={float}

I don't understand how this is ambiguous -- A is a declaration and B is a definition of the function declared by A. Right?

I'm trying to make this example work and the responses to my earlier question seem to claim that it can never work.

If that's the case, what's the point of variadic free functions? What can they do?

答:
I don't understand how this is ambiguous -- A is a declaration and B
  is a definition of the function declared by A. Right?

No. A is a declaration of a function template, and B is a declaration (and definition) of another function template.

The compiler has no way to decide between the two: they both have no arguments, and the template arguments are a match for both.

The one in the middle is an explicit total specialization of the function template declared in A.

If you tried to make B another specialization of A:

```<code>template <typename H, typename... T> /* B */
size_t num_args<H, T...>()
{
    return 1 + num_args <T...> ();
}
</code>```

... you'd end up with a partial specialization of a function template, which is not allowed.

You can do this with the usual trick of using a class template with partial specializations and a function template that calls into the class template:

```<code>template <typename... T>
class Num_Args;

template <>
struct Num_Args <>
{
    static constexpr size_t calculate() {
        return 0;
    }
};

template <typename H, typename... T>
struct Num_Args <H, T...>
{
    static constexpr size_t calculate() {
        return 1 + Num_Args<T...>::calculate();
    }
};

template <typename... T> /* B */
constexpr size_t num_args ()
{
    return Num_Args<T...>::calculate();
}
</code>```

Body:
This is related to my earlier post. I'd like to know why one attempted solution didn't work.

template <typename... T>             /* A */
size_t num_args ();

template <>
size_t num_args <> ()
{
    return 0;
}

template <typename H, typename... T> /* B */
size_t num_args ()
{
    return 1 + num_args <T...> ();
}

If I try to call, say, num_args<int,float>() then the error is that the function call is ambiguous:

A with T={int,float}

B with H=int, T={float}

I don't understand how this is ambiguous -- A is a declaration and B is a definition of the function declared by A. Right?

I'm trying to make this example work and the responses to my earlier question seem to claim that it can never work.

If that's the case, what's the point of variadic free functions? What can they do?

Body:
I don't understand how this is ambiguous -- A is a declaration and B
  is a definition of the function declared by A. Right?

No. A is a declaration of a function template, and B is a declaration (and definition) of another function template.

The compiler has no way to decide between the two: they both have no arguments, and the template arguments are a match for both.

The one in the middle is an explicit total specialization of the function template declared in A.

If you tried to make B another specialization of A:

template <typename H, typename... T> /* B */
size_t num_args<H, T...>()
{
    return 1 + num_args <T...> ();
}

... you'd end up with a partial specialization of a function template, which is not allowed.

You can do this with the usual trick of using a class template with partial specializations and a function template that calls into the class template:

template <typename... T>
class Num_Args;

template <>
struct Num_Args <>
{
    static constexpr size_t calculate() {
        return 0;
    }
};

template <typename H, typename... T>
struct Num_Args <H, T...>
{
    static constexpr size_t calculate() {
        return 1 + Num_Args<T...>::calculate();
    }
};

template <typename... T> /* B */
constexpr size_t num_args ()
{
    return Num_Args<T...>::calculate();
}


问:
Pine script error "Cannot use a mutable variable as an argument of the security function."
Hi i was trying to uptdate a scrit and i got the is message "Cannot use a mutable variable as an argument of the security function." and i dont know how to fix it. can someone help me?

the error is on line 43, "ha_close = security(ha_t, timeframe.period, nAMA)"

thanks

```<code>//@version=4
strategy("Heikin/Kaufman Strategy ",shorttitle="HAS/KAU",overlay=true,max_bars_back=500,default_qty_value = 100,initial_capital = 100,default_qty_type = strategy.cash, commission_value=0.1)
res1 = input(title="Heikin Ashi EMA Time Frame", type=input.resolution, defval="D")
test = input(0,"Heikin Ashi EMA Shift")
sloma = input(20,"Slow EMA Period")

Length = input(6, minval=1)
xPrice = close
xvnoise = abs(xPrice - xPrice[1])
nAMA = 0.0
nfastend = input(0.56,  minval = 0.05, step = 0.01)
nslowend = input(0.28,  minval = 0.05, step = 0.01)
nsignal = abs(xPrice - xPrice[Length])
nnoise = sum(xvnoise, Length)
nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))
plot(nAMA, color=color.blue, title="KAMA")

//Heikin Ashi Open/Close Price
ha_t = heikinashi(syminfo.tickerid)
ha_close = security(ha_t, timeframe.period, nAMA)
mha_close = security(ha_t, res1, hlc3)

//Moving Average
fma = ema(mha_close[test],1)
sma = ema(ha_close,sloma)
plot(fma,title="MA",color=color.black,linewidth=2)
plot(sma,title="SMA",color=color.red,linewidth=2)

//Strategy
golong =  crossover(fma,sma)
goshort =   crossunder(fma,sma)

strategy.entry("Buy",strategy.long,when = golong)
strategy.entry("Sell",strategy.short,when = goshort)
</code>```

答:
You should move all your calculations related to the variable you want to use as expression in the security() call in a function and call that function in the security() call.

```<code>//@version=4
strategy("Heikin/Kaufman Strategy ",shorttitle="HAS/KAU",overlay=true,max_bars_back=500,default_qty_value = 100,initial_capital = 100,default_qty_type = strategy.cash, commission_value=0.1)
res1 = input(title="Heikin Ashi EMA Time Frame", type=input.resolution, defval="D")
test = input(0,"Heikin Ashi EMA Shift")
sloma = input(20,"Slow EMA Period")

Length = input(6, minval=1)
nfastend = input(0.56,  minval = 0.05, step = 0.01)
nslowend = input(0.28,  minval = 0.05, step = 0.01)

f_get_nAMA() =>
    nAMA = 0.0
    xPrice = close
    xvnoise = abs(xPrice - xPrice[1])
    nsignal = abs(xPrice - xPrice[Length])
    nnoise = sum(xvnoise, Length)
    nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
    nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
    nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))

plot(f_get_nAMA(), color=color.blue, title="KAMA")

//Heikin Ashi Open/Close Price
ha_t = heikinashi(syminfo.tickerid)
ha_close = security(ha_t, timeframe.period, f_get_nAMA())
mha_close = security(ha_t, res1, hlc3)

//Moving Average
fma = ema(mha_close[test],1)
sma = ema(ha_close,sloma)
plot(fma,title="MA",color=color.black,linewidth=2)
plot(sma,title="SMA",color=color.red,linewidth=2)

//Strategy
golong =  crossover(fma,sma)
goshort =   crossunder(fma,sma)

strategy.entry("Buy",strategy.long,when = golong)
strategy.entry("Sell",strategy.short,when = goshort)
</code>```

Body:
Hi i was trying to uptdate a scrit and i got the is message "Cannot use a mutable variable as an argument of the security function." and i dont know how to fix it. can someone help me?

the error is on line 43, "ha_close = security(ha_t, timeframe.period, nAMA)"

thanks

//@version=4
strategy("Heikin/Kaufman Strategy ",shorttitle="HAS/KAU",overlay=true,max_bars_back=500,default_qty_value = 100,initial_capital = 100,default_qty_type = strategy.cash, commission_value=0.1)
res1 = input(title="Heikin Ashi EMA Time Frame", type=input.resolution, defval="D")
test = input(0,"Heikin Ashi EMA Shift")
sloma = input(20,"Slow EMA Period")

Length = input(6, minval=1)
xPrice = close
xvnoise = abs(xPrice - xPrice[1])
nAMA = 0.0
nfastend = input(0.56,  minval = 0.05, step = 0.01)
nslowend = input(0.28,  minval = 0.05, step = 0.01)
nsignal = abs(xPrice - xPrice[Length])
nnoise = sum(xvnoise, Length)
nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))
plot(nAMA, color=color.blue, title="KAMA")

//Heikin Ashi Open/Close Price
ha_t = heikinashi(syminfo.tickerid)
ha_close = security(ha_t, timeframe.period, nAMA)
mha_close = security(ha_t, res1, hlc3)

//Moving Average
fma = ema(mha_close[test],1)
sma = ema(ha_close,sloma)
plot(fma,title="MA",color=color.black,linewidth=2)
plot(sma,title="SMA",color=color.red,linewidth=2)

//Strategy
golong =  crossover(fma,sma)
goshort =   crossunder(fma,sma)

strategy.entry("Buy",strategy.long,when = golong)
strategy.entry("Sell",strategy.short,when = goshort)

Body:
You should move all your calculations related to the variable you want to use as expression in the security() call in a function and call that function in the security() call.

//@version=4
strategy("Heikin/Kaufman Strategy ",shorttitle="HAS/KAU",overlay=true,max_bars_back=500,default_qty_value = 100,initial_capital = 100,default_qty_type = strategy.cash, commission_value=0.1)
res1 = input(title="Heikin Ashi EMA Time Frame", type=input.resolution, defval="D")
test = input(0,"Heikin Ashi EMA Shift")
sloma = input(20,"Slow EMA Period")

Length = input(6, minval=1)
nfastend = input(0.56,  minval = 0.05, step = 0.01)
nslowend = input(0.28,  minval = 0.05, step = 0.01)

f_get_nAMA() =>
    nAMA = 0.0
    xPrice = close
    xvnoise = abs(xPrice - xPrice[1])
    nsignal = abs(xPrice - xPrice[Length])
    nnoise = sum(xvnoise, Length)
    nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
    nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
    nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))

plot(f_get_nAMA(), color=color.blue, title="KAMA")

//Heikin Ashi Open/Close Price
ha_t = heikinashi(syminfo.tickerid)
ha_close = security(ha_t, timeframe.period, f_get_nAMA())
mha_close = security(ha_t, res1, hlc3)

//Moving Average
fma = ema(mha_close[test],1)
sma = ema(ha_close,sloma)
plot(fma,title="MA",color=color.black,linewidth=2)
plot(sma,title="SMA",color=color.red,linewidth=2)

//Strategy
golong =  crossover(fma,sma)
goshort =   crossunder(fma,sma)

strategy.entry("Buy",strategy.long,when = golong)
strategy.entry("Sell",strategy.short,when = goshort)


问:
React leaflet draw on image
I am trying to use the drawing function of react-leaflet Where not drawing a map, but drawing on a picture
Right now I have to use the function  inside   do you have any suggestions? Or if it can't be done</p>
```<code><Map center={center} zoom={ZOOM_LEVEL} ref={mapRef} >
            < Image />
          <FeatureGroup>
            <EditControl
              position="topright"
              onCreated={_onCreate}
              onEdited={_onEdited}
              onDeleted={_onDeleted}
              draw={{
                rectangle: false,
                polyline: false,
                circle: false,
                circlemarker: false,
                marker: false,
              }}
            />
          </FeatureGroup>
          </Map>
</code>```

答:
you have to use MapContainer and inside it you have to use ImageOverlay and to ImageOverlay you have to give the image url or a base64 image.</p>
```<code> <MapContainer
      // ref={mapRef}
      className="markercluster-map"
      center={[-500, 550]}
      zoom={-2}
      minZoom={-18}
      maxZoom={18}
      style={{ height: "70vh", width: "70%" }}
      crs={CRS.Simple}
    >
      <ImageOverlay
        url={imageUrl}
        bounds={bounds}
        opacity={0.8}
        zIndex={10}
        scale={1}
        onClick={handleClick}
      >
        <FeatureGroup
          ref={(featureGroupRef) => {
            onFeatureGroupReady(featureGroupRef);
          }}
        >
          <EditControl onEdited={onEdited} onCreated={onCreated} />
        </FeatureGroup>
      </ImageOverlay>
    </MapContainer>
</code>```

Title: React leaflet draw on image

Body:
I am trying to use the drawing function of react-leaflet Where not drawing a map, but drawing on a picture
Right now I have to use the function  inside   do you have any suggestions? Or if it can't be done

<Map center={center} zoom={ZOOM_LEVEL} ref={mapRef} >
            < Image />
          <FeatureGroup>
            <EditControl
              position="topright"
              onCreated={_onCreate}
              onEdited={_onEdited}
              onDeleted={_onDeleted}
              draw={{
                rectangle: false,
                polyline: false,
                circle: false,
                circlemarker: false,
                marker: false,
              }}
            />
          </FeatureGroup>
          </Map>

Body:
you have to use MapContainer and inside it you have to use ImageOverlay and to ImageOverlay you have to give the image url or a base64 image.

 <MapContainer
      // ref={mapRef}
      className="markercluster-map"
      center={[-500, 550]}
      zoom={-2}
      minZoom={-18}
      maxZoom={18}
      style={{ height: "70vh", width: "70%" }}
      crs={CRS.Simple}
    >
      <ImageOverlay
        url={imageUrl}
        bounds={bounds}
        opacity={0.8}
        zIndex={10}
        scale={1}
        onClick={handleClick}
      >
        <FeatureGroup
          ref={(featureGroupRef) => {
            onFeatureGroupReady(featureGroupRef);
          }}
        >
          <EditControl onEdited={onEdited} onCreated={onCreated} />
        </FeatureGroup>
      </ImageOverlay>
    </MapContainer>


问:
Amazon Connect error using Lex as customer input
I am trying to create a demo call centre using AWS connect.

Part of my contact flow makes use of the "Get Customer Input", as I want to use an Amazon lex bot. I have created to divert to a specific working queue. For example, if the user says "sales" they should be directed to the sales queue.

I have tested the Lex bot within the Lex console and it works as intended.

However when testing the Lex integration within AWS connect it will always follow the "error" path on the block after a user says something on the phone.

Here is the CloudWatch log showing the Error result of the module.

```<code>{
   "Results": "Error",
   "ContactFlowName": "Inbound Flow",
   "ContactFlowModuleType": "GetUserInput",
   "Timestamp": "2022-02-12T18:06:10.940Z"
}
</code>```

Here is the contact flow:

Here is the settings for the "Get Customer Input Block":

Here is a test of the Lex bot in the Lex dashboard:

Any help would be greatly appreciated.

答: Turns out the solution was if you're using LexV2 make sure you set the proper Language Attribute as well. Easiest way is using the set Voice block in your Contact Flow, on the very bottom of the block you can enable "set language attribute".</p>

Body:
I am trying to create a demo call centre using AWS connect.

Part of my contact flow makes use of the "Get Customer Input", as I want to use an Amazon lex bot. I have created to divert to a specific working queue. For example, if the user says "sales" they should be directed to the sales queue.

I have tested the Lex bot within the Lex console and it works as intended.

However when testing the Lex integration within AWS connect it will always follow the "error" path on the block after a user says something on the phone.

Here is the CloudWatch log showing the Error result of the module.

{
   "Results": "Error",
   "ContactFlowName": "Inbound Flow",
   "ContactFlowModuleType": "GetUserInput",
   "Timestamp": "2022-02-12T18:06:10.940Z"
}

Here is the contact flow:

Here is the settings for the "Get Customer Input Block":

Here is a test of the Lex bot in the Lex dashboard:

Any help would be greatly appreciated.


问:
Can't find Oracle Database Driver in Eclipse JAVA Program
I am trying to connect to an oracle database in eclipse. I have ojdbc14.jar in a lib folder in the same project and i added it to the build path of my project, so it also resides in the Referenced Libraries directory, but yet i still get an output to the console of "Could not find the database driver"

Myself and another student employee have been trying to get this figured out for the past day and a half, and no one else in our department is experienced in Java and JSP so i thought StackOverflow would be our best bet =)

```<code>try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            System.out.println("Attempting to load the driver...");
            Class.forName(driverName);
            System.out.print("Loaded the driver");

            // Create a connection to the database
            String serverName = " ;) ";
            String portNumber = " ;) ";
            String sid = " ;) ";
            String url = "jdbc:oracle:thin:@" + serverName + ":"
                    + portNumber + ":" + sid;
            String username = "kenne13";
            String password = "**********";
            connection = DriverManager.getConnection(url, username, password);
            if (connection != null) {
                return true;
            }

        } catch (ClassNotFoundException e) {
            // Could not find the database driver
            System.out.println("Could not find the database driver");
            connected = false;
        } catch (SQLException e) {
            // Could not connect to the database
            System.out.println("Could not connect to the database");
            connected = false;
        }
</code>```

Here is the output in the console:

```<code>    Aug 18, 2011 10:07:50 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 382 ms
    Attempting to load the driver...
    Could not find the database driver
</code>```

Here is a screen capture of the code, the error, and my project directories.

答:
In a related post:
Cannot find Oracle jdbc driver

the problem was solved adding the oracle library in the run path. Have you tried to configure too? (Run/Run Configurations Select your configuration/classpath tab)

Body:
I am trying to connect to an oracle database in eclipse. I have ojdbc14.jar in a lib folder in the same project and i added it to the build path of my project, so it also resides in the Referenced Libraries directory, but yet i still get an output to the console of "Could not find the database driver"

Myself and another student employee have been trying to get this figured out for the past day and a half, and no one else in our department is experienced in Java and JSP so i thought StackOverflow would be our best bet =)

try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            System.out.println("Attempting to load the driver...");
            Class.forName(driverName);
            System.out.print("Loaded the driver");

            // Create a connection to the database
            String serverName = " ;) ";
            String portNumber = " ;) ";
            String sid = " ;) ";
            String url = "jdbc:oracle:thin:@" + serverName + ":"
                    + portNumber + ":" + sid;
            String username = "kenne13";
            String password = "**********";
            connection = DriverManager.getConnection(url, username, password);
            if (connection != null) {
                return true;
            }

        } catch (ClassNotFoundException e) {
            // Could not find the database driver
            System.out.println("Could not find the database driver");
            connected = false;
        } catch (SQLException e) {
            // Could not connect to the database
            System.out.println("Could not connect to the database");
            connected = false;
        }

Here is the output in the console:

    Aug 18, 2011 10:07:50 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 382 ms
    Attempting to load the driver...
    Could not find the database driver

Here is a screen capture of the code, the error, and my project directories.