问:
How can I write "/*" in a kotlin comment?
How can I write /* in a kotlin comment in a span code?

For example:

```<code>/**
 * Defines the route `/route/*`
 */
fun defineRoute() {
    /* ... */
}
</code>```

Right now, according to Kotlin, /route/* is the beginning of a nested comment (so the whole file is commented). I'm using /route/{*} for now but it's not a decent solution.

答:
You can also just close the nested comment:

```<code>/**
 * Defines the route `/route/*`
 */*/
fun defineRoute() {
    /* ... */
}
</code>```

This has the benefit of breaking once they fix the Kotlin parser, to be reminded to remove these.

Body:
How can I write /* in a kotlin comment in a span code?

For example:

/**
 * Defines the route `/route/*`
 */
fun defineRoute() {
    /* ... */
}

Right now, according to Kotlin, /route/* is the beginning of a nested comment (so the whole file is commented). I'm using /route/{*} for now but it's not a decent solution.

Body:
You can also just close the nested comment:

/**
 * Defines the route `/route/*`
 */*/
fun defineRoute() {
    /* ... */
}

This has the benefit of breaking once they fix the Kotlin parser, to be reminded to remove these.


来源: stackexchange

问:
Search and Print by Two Conditions using AWK
I have this file:

```<code>         - - - Results from analysis of weight - - -
 Akaike Information Criterion   307019.66 (assuming 2 parameters).
 Bayesian Information Criterion 307036.93

                 Approximate stratum variance decomposition
 Stratum     Degrees-Freedom   Variance      Component Coefficients
 id                 39892.82    490.360         0.7     0.6     1.0
 damid                  0.00    0.00000         0.0     0.0     1.0
 Residual Variance   1546.46    320.979         0.0     0.0     1.0

 Model_Term                             Gamma         Sigma   Sigma/SE   % C
 id                     NRM_V 17633  0.18969       13.480       4.22   0 P
 damid                  NRM_V 17633  0.07644       13.845       2.90   0 P
 ide(damid)             IDV_V 17633  0.00000       32.0979      1.00   0 S
 Residual               SCA_V 12459  1.0000        320.979     27.81   0 P
</code>```

And I Would Like to print the Value of Sigma on id, note there are two id on the file, so I used the condition based on NRM_V too.

I tried this code:

```<code>tac myfile | awk '(/id/ && /NRM_V/){print $5}'
</code>```

but the results printed were:

```<code>13.480
13.845
</code>```

and I need just the first one

答:
The problem is that /id/ also matches damid. You could use the following to print the Sigma value only if the first field is id and the second field is NRM_V:

```<code>awk '$1=="id" && $2=="NRM_V"{ print $5 }' myfile
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this file:

         - - - Results from analysis of weight - - -
 Akaike Information Criterion   307019.66 (assuming 2 parameters).
 Bayesian Information Criterion 307036.93

                 Approximate stratum variance decomposition
 Stratum     Degrees-Freedom   Variance      Component Coefficients
 id                 39892.82    490.360         0.7     0.6     1.0
 damid                  0.00    0.00000         0.0     0.0     1.0
 Residual Variance   1546.46    320.979         0.0     0.0     1.0

 Model_Term                             Gamma         Sigma   Sigma/SE   % C
 id                     NRM_V 17633  0.18969       13.480       4.22   0 P
 damid                  NRM_V 17633  0.07644       13.845       2.90   0 P
 ide(damid)             IDV_V 17633  0.00000       32.0979      1.00   0 S
 Residual               SCA_V 12459  1.0000        320.979     27.81   0 P

And I Would Like to print the Value of Sigma on id, note there are two id on the file, so I used the condition based on NRM_V too.

I tried this code:

tac myfile | awk '(/id/ && /NRM_V/){print $5}'

but the results printed were:

13.480
13.845

and I need just the first one

Body:
The problem is that /id/ also matches damid. You could use the following to print the Sigma value only if the first field is id and the second field is NRM_V:

awk '$1=="id" && $2=="NRM_V"{ print $5 }' myfile


问:
What is the following C++ code used for -> "#define idiv(a, b) (((a) + (b) / 2) / (b))"?
I'm working with the code that frequently uses some nontrivial optimizations.
What is the

#define idiv(a, b) (((a) + (b) / 2) / (b))
```

<p>used for? Why not simply</p>

<pre class="lang-c prettyprint-override"><code>#define idiv(a, b) ((a)/(b) + 0.5)
</code>```

Is it integer division overflow protection or something else?

答:
This code is C macro what is consider a very bad practice in C++.
In C++ you should use templates (some says that this is smarter macros).

template<typename T>
constexpr T idiv(T a, T b) {
    return (a + b / 2) / b;
}
```

Still this code doesn't do what author has expected. Plan was to round result to closest integer value, but it fails if one arguments has negative value.

See this and note failure for a: 4 b: -2

And there is also integer overflow issue (see last test case).

Body:
I'm working with the code that frequently uses some nontrivial optimizations.
What is the

#define idiv(a, b) (((a) + (b) / 2) / (b))

used for? Why not simply

#define idiv(a, b) ((a)/(b) + 0.5)

Is it integer division overflow protection or something else?

Body:
This code is C macro what is consider a very bad practice in C++.
In C++ you should use templates (some says that this is smarter macros).

template<typename T>
constexpr T idiv(T a, T b) {
    return (a + b / 2) / b;
}

Still this code doesn't do what author has expected. Plan was to round result to closest integer value, but it fails if one arguments has negative value.

See this and note failure for a: 4 b: -2

And there is also integer overflow issue (see last test case).


问:
how can I extract text contents from GUI apps  in linux?
I want to  extract text contents from GUI apps,here are 2 examples::

example 1:

Suppose I opened  firefox, and input url : www.google.com

how can I extract the string "www.google.com" from firefox using my own app ?

example 2:

open calculator(using gcalctool),then input 1+1

How can I extract the string "1+1" of calculator from my own program?

in brief ,what I want is to find out whether there is a way to extract the text contents from any widget of an GUI application

Thanks

答:
I believe firefox and gcalctool are for examples only and you just want to know in general how to pass output of one application to other application.

There are many ways to do that on Linux, like:

piping

```<code>application1 | application2
</code>```

btw here is the Firefox command line manual if you want to start firefox on Ubuntu with a URL. eg:

```<code>firefox "$url"
</code>```

where $url is a variable whose value can be www.mozilla.org

ContentLicense: CC BY-SA 3.0

Body:
I believe firefox and gcalctool are for examples only and you just want to know in general how to pass output of one application to other application.

There are many ways to do that on Linux, like:

piping

application1 | application2

btw here is the Firefox command line manual if you want to start firefox on Ubuntu with a URL. eg:

firefox "$url"

where $url is a variable whose value can be www.mozilla.org


问:
Get current line number from bufferedReader
I have different text files I would like to read, and I am using BufferedReader for it like this:

```<code>int theMax = 0;
    int theTypes = 0;
    int []theSlices = {};
    /*
        INPUT1:
        17 4
        2 5 6 8

        INPUT2:
        100 10
        4 14 15 18 29 32 36 82 95 95

    */

    try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    ;
</code>```

My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.

Example for INPUT1:
theMax = 17
theTypes = 4
theSlices = 2 5 6 8

答:
First of all, as far as I know (and having read the official Java documentation for it here - https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html), the BufferedReader class does not in itself give you a mechanism (e.g. a getCurrentLine() method) to determine the current line.

However, there is absolutely nothing stopping you from keeping track of current line number yourself through, say, a counter variable.

Therefore, the relevant section of your code would look like:

```<code>        int currentLine = 0;
        while ((line = bufferedReader.readLine()) != null) {
            currentLine++;

            String[] numbers = line.split(" ");

            /* NOTE: this can be numbers.length >= 2 if you don't care to enforce
            having exactly 2 numbers as the first line
            */
            if(currentLine == 1 && numbers.length == 2) {
                    theMax = Integer.valueOf(numbers[0]);
                    theTypes = Integer.valueOf(numbers[1]);
            } else {
                for(int index = 0; index < numbers.length; index++) {
                        theSlices[index] = Integer.valueOf(numbers[index]);
                }
            }
        }
        // do something with read values
</code>```

I would also like to mention that your code could be improved here and there, for example:

You can replace your try with a try-with-resources, such that your readers are managed/closed automatically even if an exception occurs.

If you decide not to use try-with-resources, then you'll need to move your reader.close() method call in a finally block, because if an exception actually occurs you are never closing your resource.

These 2 lines

```<code>        FileReader reader = ;
        BufferedReader bufferedReader = new BufferedReader(reader);
</code>```

can be simplified into:

```<code>        BufferedReader bufferedReader = new BufferedReader(new FileReader("INPUT1.in"));
</code>```

and then you only need to manage the bufferedReader instance if sticking to try instead of try-with-resources.

Hope this helps.

PS: not saying that my code snippet above is perfect, I'm sure it can be written more cleanly

Body:
I have different text files I would like to read, and I am using BufferedReader for it like this:

int theMax = 0;
    int theTypes = 0;
    int []theSlices = {};
    /*
        INPUT1:
        17 4
        2 5 6 8

        INPUT2:
        100 10
        4 14 15 18 29 32 36 82 95 95

    */

    try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    ;

My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.

Example for INPUT1:
theMax = 17
theTypes = 4
theSlices = 2 5 6 8

Body:
First of all, as far as I know (and having read the official Java documentation for it here - https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html), the BufferedReader class does not in itself give you a mechanism (e.g. a getCurrentLine() method) to determine the current line.

However, there is absolutely nothing stopping you from keeping track of current line number yourself through, say, a counter variable.

Therefore, the relevant section of your code would look like:

        int currentLine = 0;
        while ((line = bufferedReader.readLine()) != null) {
            currentLine++;

            String[] numbers = line.split(" ");

            /* NOTE: this can be numbers.length >= 2 if you don't care to enforce
            having exactly 2 numbers as the first line
            */
            if(currentLine == 1 && numbers.length == 2) {
                    theMax = Integer.valueOf(numbers[0]);
                    theTypes = Integer.valueOf(numbers[1]);
            } else {
                for(int index = 0; index < numbers.length; index++) {
                        theSlices[index] = Integer.valueOf(numbers[index]);
                }
            }
        }
        // do something with read values

I would also like to mention that your code could be improved here and there, for example:

You can replace your try with a try-with-resources, such that your readers are managed/closed automatically even if an exception occurs.

If you decide not to use try-with-resources, then you'll need to move your reader.close() method call in a finally block, because if an exception actually occurs you are never closing your resource.

These 2 lines

        FileReader reader = ;
        BufferedReader bufferedReader = new BufferedReader(reader);

can be simplified into:

        BufferedReader bufferedReader = new BufferedReader(new FileReader("INPUT1.in"));

and then you only need to manage the bufferedReader instance if sticking to try instead of try-with-resources.

Hope this helps.

PS: not saying that my code snippet above is perfect, I'm sure it can be written more cleanly


问:
Gradle buildConfigField BuildConfig cannot resolve symbol
I am using Gradle to build my Android application. I am trying to use some flags based on the build type (release or debug).

My Gradle file looks like this:

```<code>android {
    buildTypes {
        debug {
            buildConfigField 'boolean', 'PREPROD', 'true'
            buildConfigField 'boolean', 'STAGING', 'false'
        }

        release {
            buildConfigField 'boolean', 'PREPROD', 'false'
            buildConfigField 'boolean', 'STAGING', 'false'
        }
    }
}
</code>```

And if I try to call BuildConfig.PREPROD or BuildConfig.STAGING I get a "Cannot resolve symbol" error.
The Gradle sync was successful, so I don't know if I forgot some steps in order to be able to use this feature?

The generated BuildConfig.java file is the following (in build/source/buildConfig/debug/com.example.myapp):

```<code>package com.example.myapp;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String PACKAGE_NAME = "com.example.myapp";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 400;
  public static final String VERSION_NAME = "";
}
</code>```

答: In my case, I did a stupid mistake by COPYING AND PASTING THE SAME VARIANT. I just renamed the other variant and it worked.

Body:
I am using Gradle to build my Android application. I am trying to use some flags based on the build type (release or debug).

My Gradle file looks like this:

android {
    buildTypes {
        debug {
            buildConfigField 'boolean', 'PREPROD', 'true'
            buildConfigField 'boolean', 'STAGING', 'false'
        }

        release {
            buildConfigField 'boolean', 'PREPROD', 'false'
            buildConfigField 'boolean', 'STAGING', 'false'
        }
    }
}

And if I try to call BuildConfig.PREPROD or BuildConfig.STAGING I get a "Cannot resolve symbol" error.
The Gradle sync was successful, so I don't know if I forgot some steps in order to be able to use this feature?

The generated BuildConfig.java file is the following (in build/source/buildConfig/debug/com.example.myapp):

package com.example.myapp;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String PACKAGE_NAME = "com.example.myapp";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 400;
  public static final String VERSION_NAME = "";
}


问:
fetch google finance data
can anyone provide me an example on how I can fetch the real-time stocks of google finance</p>

答:
The link in the earlier answer was broken when I tried it, so here is another example. You have to do a bit of processing but otherwise it's pretty easy.
http://www.google.com/finance/info?client=ig&q=goog,msft</p>

ContentLicense: CC BY-SA 2.5

Title: fetch google finance data


问:
Assigning K,V pairs to a JSON object in NodeJS
I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.

I am using SNMP to get the k, v pairs, where the key is the OID. I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.

The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data.

let pair = {
    key: "abc...",
    value: "xyz..."
}
```

<p>I have defined the JSON object as an empty structure.</p>

<pre class="lang-js prettyprint-override"><code>let jsonObject = {
    ipaddress: "",
    network: {
        uptime: "",
        throughput: "",
        devices: ""
    }
}
</code>```

And I iterate through my keys (pairs is the name of an array containing the k,v objects)

for (let i = 0; i < pairs.length; i++) {
    if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
    if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
    if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}
```

<p>I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.</p>

<p>EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.</p>

<p>EDIT 2: This seems like an odd situation, I know.
For example, I want to take the K,V input:</p>

```Key            Value
1.2.3.4.5.6    "10.0.0.1"
2.3.4.5.6.7    "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8    "1.1.1.1"
```

<p>And convert it to a dissimilarly named JSON object</p>

<pre class="lang-js prettyprint-override"><code>{
    uptime: "3 Days 14 Hours 32 Minutes",
    networking: {
        ip: "10.0.0.1",
        dns: "1.1.1.1"
    }
}
</code>```

Potentially using some form of mapping, instead of using ~200 if statements

答:
You can use Array.prototype.forEach for iterating and assigning the object.

const jsonObject = {
     name: '',
     properties: {
           email: '',
           address: '',
           town: ''
     }
 };

const pairs = [{key: 'name',    value: 'thatsimplekid'},
               {key: 'email',   value: 'aaa@domain.com'},
               {key: 'town',    value: 'myTown'},
               {key: 'address', value:'123 main st' }];

pairs.forEach( ({key, value}) =>
                   jsonObject.hasOwnProperty(key) ?
                             jsonObject[key] = value :
                             jsonObject.properties[key] = value);

console.log(jsonObject);```

Body:
I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.

I am using SNMP to get the k, v pairs, where the key is the OID. I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.

The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data.

let pair = {
    key: "abc...",
    value: "xyz..."
}

I have defined the JSON object as an empty structure.

let jsonObject = {
    ipaddress: "",
    network: {
        uptime: "",
        throughput: "",
        devices: ""
    }
}

And I iterate through my keys (pairs is the name of an array containing the k,v objects)

for (let i = 0; i < pairs.length; i++) {
    if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
    if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
    if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}

I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.

EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.

EDIT 2: This seems like an odd situation, I know.
For example, I want to take the K,V input:

Key            Value
1.2.3.4.5.6    "10.0.0.1"
2.3.4.5.6.7    "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8    "1.1.1.1"

And convert it to a dissimilarly named JSON object

{
    uptime: "3 Days 14 Hours 32 Minutes",
    networking: {
        ip: "10.0.0.1",
        dns: "1.1.1.1"
    }
}

Potentially using some form of mapping, instead of using ~200 if statements


问:
Keycloak jetty adapter cannot be installed in Apache Karaf
I use Apache Karaf 4.2.8. I installed keycloak osgi features. I could configure authentication for karaf shell with keycloak using keycloak-jaas feature.

Now I want to configure authentication for my services under /cxf context.

I configured pax-web context so login-method is KEYCLOAK.

But I have to install keycloak-jetty-adapter as well, so it could be integrated. But when I try to install that feature I receive an error.

```<code>trun()> feature:install keycloak-jetty9-adapter
</code>```

org.apache.felix.resolver.reason.ReasonException: Unable to resolve
  root: missing requirement [root] osgi.identity;
  osgi.identity=keycloak-jetty9-adapter; type=karaf.feature;
  version="[8.0.1,8.0.1]";
  filter:="(&(osgi.identity=keycloak-jetty9-adapter)(type=karaf.feature)(version>=8.0.1)(version<=8.0.1))" [caused by: Unable to resolve keycloak-jetty9-adapter/8.0.1: missing
  requirement [keycloak-jetty9-adapter/8.0.1] osgi.identity;
  osgi.identity=jetty; type=karaf.feature; version="[9.2.0,9.3.0)"] at
  org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1343)
  at
  org.apache.felix.resolver.ResolverImpl.doResolve(ResolverImpl.java:392)
  at
  org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:378)
  at
  org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:332)
  at
  org.apache.karaf.features.internal.region.SubsystemResolver.resolve(SubsystemResolver.java:257)
  at
  org.apache.karaf.features.internal.service.Deployer.deploy(Deployer.java:388)
  at
  org.apache.karaf.features.internal.service.FeaturesServiceImpl.doProvision(FeaturesServiceImpl.java:1058)
  at
  org.apache.karaf.features.internal.service.FeaturesServiceImpl.lambda$doProvisionInThread$13(FeaturesServiceImpl.java:994)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at java.lang.Thread.run(Thread.java:748) Caused by:
  org.apache.felix.resolver.reason.ReasonException: Unable to resolve
  keycloak-jetty9-adapter/8.0.1: missing requirement
  [keycloak-jetty9-adapter/8.0.1] osgi.identity; osgi.identity=jetty;
  type=karaf.feature; version="[9.2.0,9.3.0)" at
  org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1343)
  ... 12 more Error executing command: Unable to resolve root: missing
  requirement [root] osgi.identity;
  osgi.identity=keycloak-jetty9-adapter; type=karaf.feature;
  version="[8.0.1,8.0.1]";
  filter:="(&(osgi.identity=keycloak-jetty9-adapter)(type=karaf.feature)(version>=8.0.1)(version<=8.0.1))" [caused by: Unable to resolve keycloak-jetty9-adapter/8.0.1: missing
  requirement [keycloak-jetty9-adapter/8.0.1] osgi.identity;
  osgi.identity=jetty; type=karaf.feature; version="[9.2.0,9.3.0)"]

If not to install that adapter, then I cannot reach my service (I receive 403 Forbidden) as it is protected via pax-web but authentication is impossible.

It seems that jetty within karaf is embedded and does not contain all features, which does not allow me to install jetty adapter.

答:
According to the release notes for Apache Karaf 4.2.8, Karaf is using Jetty 9.4.22, which seems to be outside of your range in the error message version="[9.2.0,9.3.0)"

You'll either need to upgrade Keycloak to one that support Jetty 9.4.x
or downgrade Karaf to one that supports the same version of Jetty that Keycloak uses.

Body:
I use Apache Karaf 4.2.8. I installed keycloak osgi features. I could configure authentication for karaf shell with keycloak using keycloak-jaas feature.

Now I want to configure authentication for my services under /cxf context.

I configured pax-web context so login-method is KEYCLOAK.

But I have to install keycloak-jetty-adapter as well, so it could be integrated. But when I try to install that feature I receive an error.

trun()> feature:install keycloak-jetty9-adapter

org.apache.felix.resolver.reason.ReasonException: Unable to resolve
  root: missing requirement [root] osgi.identity;
  osgi.identity=keycloak-jetty9-adapter; type=karaf.feature;
  version="[8.0.1,8.0.1]";
  filter:="(&(osgi.identity=keycloak-jetty9-adapter)(type=karaf.feature)(version>=8.0.1)(version<=8.0.1))" [caused by: Unable to resolve keycloak-jetty9-adapter/8.0.1: missing
  requirement [keycloak-jetty9-adapter/8.0.1] osgi.identity;
  osgi.identity=jetty; type=karaf.feature; version="[9.2.0,9.3.0)"] at
  org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1343)
  at
  org.apache.felix.resolver.ResolverImpl.doResolve(ResolverImpl.java:392)
  at
  org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:378)
  at
  org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:332)
  at
  org.apache.karaf.features.internal.region.SubsystemResolver.resolve(SubsystemResolver.java:257)
  at
  org.apache.karaf.features.internal.service.Deployer.deploy(Deployer.java:388)
  at
  org.apache.karaf.features.internal.service.FeaturesServiceImpl.doProvision(FeaturesServiceImpl.java:1058)
  at
  org.apache.karaf.features.internal.service.FeaturesServiceImpl.lambda$doProvisionInThread$13(FeaturesServiceImpl.java:994)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at java.lang.Thread.run(Thread.java:748) Caused by:
  org.apache.felix.resolver.reason.ReasonException: Unable to resolve
  keycloak-jetty9-adapter/8.0.1: missing requirement
  [keycloak-jetty9-adapter/8.0.1] osgi.identity; osgi.identity=jetty;
  type=karaf.feature; version="[9.2.0,9.3.0)" at
  org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1343)
  ... 12 more Error executing command: Unable to resolve root: missing
  requirement [root] osgi.identity;
  osgi.identity=keycloak-jetty9-adapter; type=karaf.feature;
  version="[8.0.1,8.0.1]";
  filter:="(&(osgi.identity=keycloak-jetty9-adapter)(type=karaf.feature)(version>=8.0.1)(version<=8.0.1))" [caused by: Unable to resolve keycloak-jetty9-adapter/8.0.1: missing
  requirement [keycloak-jetty9-adapter/8.0.1] osgi.identity;
  osgi.identity=jetty; type=karaf.feature; version="[9.2.0,9.3.0)"]

If not to install that adapter, then I cannot reach my service (I receive 403 Forbidden) as it is protected via pax-web but authentication is impossible.

It seems that jetty within karaf is embedded and does not contain all features, which does not allow me to install jetty adapter.


问:
Why must a variable be declared in a for loop initialization?

int v = 0;

for (v; v<2; v++) {
    ...

}
```

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?

答:
If v is declared prior to the loop, you should leave the first part of the for statement empty:

```<code>int v = 0;

for (; v < 2; v++) {
    ...
}
</code>```

There's no meaning to just writing v;.

Body:
int v = 0;

for (v; v<2; v++) {
    ...

}

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?

Body:
If v is declared prior to the loop, you should leave the first part of the for statement empty:

int v = 0;

for (; v < 2; v++) {
    ...
}

There's no meaning to just writing v;.


问:
pandas copy value from one column to another if condition is met
I have a dataframe:

```<code>df =
col1  col2  col3
1      2     3
1      4     6
3      7     2
</code>```

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

```<code>new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2
</code>```

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?

答:
```<code>df['col1'] = df.apply(lambda x: x['col3'] if x['col1'] < x['col2'] else x['col1'], axis=1)
</code>```

Body:
I have a dataframe:

df =
col1  col2  col3
1      2     3
1      4     6
3      7     2

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?


问:
Divide 2 columns into 4 based on odd and even
I want to divide 2 columns into 4 based on odd and even. I have a table

```<code>INSERT INTO @tab
VALUES ('test', 'desc'), ('test1', 'desc1'), ('test2', 'desc2'),
       ('test3', 'desc3'), ('test4', 'desc4')
</code>```

I tried the following query:-

```<code>SELECT
    CASE
       WHEN A.RNK  % 2 = 1
          THEN Heading
    END AS Headingodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN Heading
    END AS Headingeven,
    CASE
       WHEN A.RNK  % 2 = 1
          THEN A.[Description]
    END AS Descriptionodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN A.[Description]
    END AS Descriptioneven
FROM
    (SELECT
         Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
     FROM
         @tab) A
</code>```

Results I am getting from the query is:-

But I want the result in following format:-

```<code>DECLARE @tab1 TABLE(Headingodd VARCHAR(100), Headingeven VARCHAR(100), Descriptionodd VARCHAR(100), Descriptioneven VARCHAR(100))

INSERT INTO @tab1
VALUES ('test', 'test1', 'desc', 'desc1'),
       ('test2', 'test3', 'desc2', 'desc3'),
       ('test4', null, 'desc4', null)

SELECT * FROM @tab1
</code>```

答:
The other answers just seem so complicated.  This is really just aggregation and arithmetic:

```<code>select min(case when rnk % 2 = 1 then heading end) as heading_odd,
       min(case when rnk % 2 = 0 then heading end) as heading_even,
       min(case when rnk % 2 = 1 then description end) as description_odd,
       min(case when rnk % 2 = 0 then description end) as description_even
from (select t.*, row_number() over (order by id) as rnk
      from tab t
     ) t
group by (rnk - 1) / 2
order by min(rnk);
</code>```

Here is a db<>fiddle.

Note:  You don't even need rnk if you know that the id is sequential with no gaps.

Body:
I want to divide 2 columns into 4 based on odd and even. I have a table

INSERT INTO @tab
VALUES ('test', 'desc'), ('test1', 'desc1'), ('test2', 'desc2'),
       ('test3', 'desc3'), ('test4', 'desc4')

I tried the following query:-

SELECT
    CASE
       WHEN A.RNK  % 2 = 1
          THEN Heading
    END AS Headingodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN Heading
    END AS Headingeven,
    CASE
       WHEN A.RNK  % 2 = 1
          THEN A.[Description]
    END AS Descriptionodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN A.[Description]
    END AS Descriptioneven
FROM
    (SELECT
         Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
     FROM
         @tab) A

Results I am getting from the query is:-

But I want the result in following format:-

DECLARE @tab1 TABLE(Headingodd VARCHAR(100), Headingeven VARCHAR(100), Descriptionodd VARCHAR(100), Descriptioneven VARCHAR(100))

INSERT INTO @tab1
VALUES ('test', 'test1', 'desc', 'desc1'),
       ('test2', 'test3', 'desc2', 'desc3'),
       ('test4', null, 'desc4', null)

SELECT * FROM @tab1

Body:
The other answers just seem so complicated.  This is really just aggregation and arithmetic:

select min(case when rnk % 2 = 1 then heading end) as heading_odd,
       min(case when rnk % 2 = 0 then heading end) as heading_even,
       min(case when rnk % 2 = 1 then description end) as description_odd,
       min(case when rnk % 2 = 0 then description end) as description_even
from (select t.*, row_number() over (order by id) as rnk
      from tab t
     ) t
group by (rnk - 1) / 2
order by min(rnk);

Here is a db<>fiddle.

Note:  You don't even need rnk if you know that the id is sequential with no gaps.


问:
builder for HashMap
Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

```<code>HashMap<String,Integer> m = Maps.BuildHashMap.
    put("a",1).
    put("b",2).
    build();
</code>```

答: There's ImmutableMap.builder() in Guava.

Title: builder for HashMap

Body:
Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

HashMap<String,Integer> m = Maps.BuildHashMap.
    put("a",1).
    put("b",2).
    build();


问:
how to hide id from the url and make it clean url my directory of .htaccess file is /home/evidhya/public_html/tutorials/.htaccess
I have following  url i would like to hide id and make it clean url

https://www.evidhya.com/tutorials/tutorials.php?qid=569/AJAX/Introduction

clean url should be like below url
https://www.evidhya.com/tutorials/AJAX/Introduction

I'm able to achieve using below htaccess code.
https://www.evidhya.com/tutorials/569/AJAX/Introduction
but i don't want 569 id in url

```<code>RewriteEngine On
#RewriteBase /KSTA-Webinar/
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
#RewriteRule ^(\d+)/?$ tutorials.php?qid=$1/$2/$1/$3 [L,QSA]
RewriteRule ^([\w.-]+)/?$ get_data.php?qid=$1 [L,QSA]

RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} ^title=([^/]+)/([^/]+)/([^/]+)/(.+)$
RewriteRule ^tutorials\.php$ /%1/%2/%4? [R=301]

RewriteRule ^tutorials/([\w+%]{2,50})$ /tutorials.php?qid=$1 [QSA,L]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/$ tutorials.php?qid=$1&user=$2&date=$3

RewriteRule ^([^/]+)/([^/]+)/(.+)$ tutorials.php?qid=$1/$2/$1/$3 [L]
</code>```

答:
Well, it seems the id is needed to determine the resulting url.
I would do this:

```<code>RewriteEngine on
RewriteRule (\d+)/(\w+)/(\w+) tutorials.php?qid=$1/$2/$3 [L]
</code>```

and place this rule in tutorials/.htaccess.

And when someone goes to https://www.evidhya.com/tutorials/569/AJAX/Introduction it should load https://www.evidhya.com/tutorials/tutorials.php?qid=569/AJAX/Introduction

Body:
I have following  url i would like to hide id and make it clean url

https://www.evidhya.com/tutorials/tutorials.php?qid=569/AJAX/Introduction

clean url should be like below url
https://www.evidhya.com/tutorials/AJAX/Introduction

I'm able to achieve using below htaccess code.
https://www.evidhya.com/tutorials/569/AJAX/Introduction
but i don't want 569 id in url

RewriteEngine On
#RewriteBase /KSTA-Webinar/
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
#RewriteRule ^(\d+)/?$ tutorials.php?qid=$1/$2/$1/$3 [L,QSA]
RewriteRule ^([\w.-]+)/?$ get_data.php?qid=$1 [L,QSA]

RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} ^title=([^/]+)/([^/]+)/([^/]+)/(.+)$
RewriteRule ^tutorials\.php$ /%1/%2/%4? [R=301]

RewriteRule ^tutorials/([\w+%]{2,50})$ /tutorials.php?qid=$1 [QSA,L]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/$ tutorials.php?qid=$1&user=$2&date=$3

RewriteRule ^([^/]+)/([^/]+)/(.+)$ tutorials.php?qid=$1/$2/$1/$3 [L]

Body:
Well, it seems the id is needed to determine the resulting url.
I would do this:

RewriteEngine on
RewriteRule (\d+)/(\w+)/(\w+) tutorials.php?qid=$1/$2/$3 [L]

and place this rule in tutorials/.htaccess.

And when someone goes to https://www.evidhya.com/tutorials/569/AJAX/Introduction it should load https://www.evidhya.com/tutorials/tutorials.php?qid=569/AJAX/Introduction


问:
How can I tell emacs not to break long lines?
How can I set Emacs to not automatically break long lines?

I find it easier to visualize indentation without its breaking long lines, to instead use horizontal scrolling when needed.

答:
Have you tried to remove "fill-mode" ?</p>

```<code>M-x auto-fill-mode
</code>```

Body:
Have you tried to remove "fill-mode" ?

M-x auto-fill-mode


问:
MDN String.prototype.repeat polyfill - How can 'this' have value null?
In the MDN doc for String.prototype.repeat the polyfill has this line of code:

```<code>if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null)
      throw new TypeError('can\'t convert ' + this + ' to object');
</code>```

How is it possible for this to be null?

答:
Like this:

String.prototype.repeat.call()
```

Body:
In the MDN doc for String.prototype.repeat the polyfill has this line of code:

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null)
      throw new TypeError('can\'t convert ' + this + ' to object');

How is it possible for this to be null?


问:
Avoiding [weak self] for simple operations?
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

```<code>final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}
</code>```

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?

答:
the life cycle of the ViewController can potentially be extended until dataTask completes

So the question is whether that would be coherent. It might even be a good thing. If it would, then fine, and there’s no need for weak self, as there is no retain cycle because the
url session is shared.

But when the url session is an instance
 property and has a real delegate, things are much more complicated and
 you really can get a retain cycle, because the session retains its delegate which might be retaining the session.

Body:
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?


问:
AWS EC2 Launchtemplate vs Launchconfiguration
I’m wondering when one should use which one.

It seems Launchtemplates are more advanced because they allow for versioning but on the other side you cannot set EBS settings etc.

Is Launchtemplate a better version of Launchconfiguration or do they serve different purposes so meaning if you don’t want versioning stick with Launchconfigs with no harm for the future.

Thanks A

答:
Apart from the versioning features of the launch template "I didn't need to use this because I rely on git"

The use case I needed to use LT over LC is basically I needed to mix the instance types for kubernets nodes for the same autoscaling group.

Basically I need to have a minimum number of nodes running within EKS as worker nodes (3 nodes) so this was (either on-demand or reserved) in our case we used on-demant and for any extra workload we just fire spot instances with specificed bidding price ...etc.

That is one of use cases I am not sure if launch configuration would allow this but definitely LT allows mixed instances types within same LT


问:
Get Selected Row's Specific Col Value via script (Google Sheets)
I've been trying to get this one to work without success so far.
I need to get the TaskNumber on the first column of the row I'm on and bring it to the destination sheet, so that I can update it there.
I have the following, which I'm tweaking to achieve my goal, but I guess I've bumped into my limitation walls:

```<code>function jump() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var TaskNumberSheet = ss.getSheetByName('To-Do List');
  var TaskNoRow = TaskNumberSheet.getActiveCell();
  var TaskNoCol = TaskNoRow.getColumn() == 1
  var TaskNo = TaskNoCol.getValue;
  var sheet = ss.getSheetByName('Updates');
  //var Tasks = ss.getSheetByName("To Do List").getActiveRange(Tasks.getColum(1)).getValue();

  var values = sheet.getRange("B:B").getValues();
  var maxIndex = values.reduce(function(maxIndex, row, index) {
    return row[0] === "" ? maxIndex : index;
  }, 0);
  sheet.setActiveRange(sheet.getRange(maxIndex + 2,2)).setValue(TaskNo);
}
</code>```

Any help is appreciate.

Cheers,
A

答:
If I understood you correctly, you want to:

Get the value in column A from the currently active row (in sheet To-Do List).

Find the first empty cell in column B (in sheet Updates) (start looking at row #8).

Copy the value that was retrieved in step 1 to the cell retrieved in step 2.

Set the cell retrieved in step 2 as the active cell.

If that's the case, you can do the following:

function jump() {
  var ss = SpreadsheetApp.getActive();
  // Step 1:
  var TaskNumberSheet = ss.getSheetByName('To-Do List');
  var TaskNoRow = TaskNumberSheet.getActiveCell().getRow();
  var TaskNoCol = 1;
  var TaskNo = TaskNumberSheet.getRange(TaskNoRow, TaskNoCol).getValue();
  // Step 2:
  var sheet = ss.getSheetByName('Updates');
  var firstRow = 8;
  var column = 2;
  var numRows = sheet.getLastRow() - firstRow + 1;
  var values = sheet.getRange(firstRow, column, numRows).getValues().map(function(value) {
    return value[0]
  });
  var i = 0;
  for (i; i < values.length; i++) {
    if (values[i] === "") break;
  }
  var targetRange = sheet.getRange(i + firstRow, column);
  targetRange.setValue(TaskNo); // Step 3
  sheet.setActiveRange(targetRange); // Step 4
}
```

Body:
I've been trying to get this one to work without success so far.
I need to get the TaskNumber on the first column of the row I'm on and bring it to the destination sheet, so that I can update it there.
I have the following, which I'm tweaking to achieve my goal, but I guess I've bumped into my limitation walls:

function jump() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var TaskNumberSheet = ss.getSheetByName('To-Do List');
  var TaskNoRow = TaskNumberSheet.getActiveCell();
  var TaskNoCol = TaskNoRow.getColumn() == 1
  var TaskNo = TaskNoCol.getValue;
  var sheet = ss.getSheetByName('Updates');
  //var Tasks = ss.getSheetByName("To Do List").getActiveRange(Tasks.getColum(1)).getValue();

  var values = sheet.getRange("B:B").getValues();
  var maxIndex = values.reduce(function(maxIndex, row, index) {
    return row[0] === "" ? maxIndex : index;
  }, 0);
  sheet.setActiveRange(sheet.getRange(maxIndex + 2,2)).setValue(TaskNo);
}

Any help is appreciate.

Cheers,
A


问:
Issue with Azure B2C Reset Password user flow
I have recently developed an ASP.net MVC web application which uses Azure B2C to authenticate users.

I have been asked to enable the Reset Password User flow to enable users to reset via self-service.

I created the user flow within the portal (using the correct identity provider and setting Reset password using email address) and added the code from the microsoft example here however every time I click reset password, it just directs me back to the login screen and it never reaches the reset password page.

When I click the forgot password link the method below is called , it steps through the code fine, but then loads the login page.

Reset Password code

```<code>public void ResetPassword(string redirectUrl)
    {
        // Let the middleware know you are trying to use the reset password policy (see OnRedirectToIdentityProvider in Startup.Auth.cs)
        HttpContext.GetOwinContext().Set("Policy", Startup.PasswordResetPolicyId);

        // Set the page to redirect to after changing passwords
        var authenticationProperties = new AuthenticationProperties { RedirectUri = "/" };
        HttpContext.GetOwinContext().Authentication.Challenge(authenticationProperties);

        return;
    }
</code>```

The policy ID is correct in both azure and in the code as I step through and the values are all pulling through correctly (see below):

Policy ID string (as used above)

```<code>public static string PasswordResetPolicyId = ConfigurationManager.AppSettings["ida:ResetPasswordPolicyId"];
</code>```

In Web.config where the policy is defined

```<code><add key="ida:ResetPasswordPolicyId" value="B2C_1_UserApp_ResetPassword" />
</code>```

I have provided all the code samples I have added for the reset function to work, the rest of the code is all included in the Microsoft Web App example.

Has anyone else experienced something similar? As I said previously, when you click the forgot password link it does exactly as it should and goes to the correct controller/method, but then goes back to the login screen.

答:
Searching through my code, I found that the line

```<code>app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(PasswordResetPolicyId));
</code>```

was missing from ConfigureAuth. Once added this has fixed the issue.

```<code>public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {

                CookieManager = new SystemWebCookieManager()

            });
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
            /////////////////
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(PasswordResetPolicyId));
        }
</code>```

Body:
I have recently developed an ASP.net MVC web application which uses Azure B2C to authenticate users.

I have been asked to enable the Reset Password User flow to enable users to reset via self-service.

I created the user flow within the portal (using the correct identity provider and setting Reset password using email address) and added the code from the microsoft example here however every time I click reset password, it just directs me back to the login screen and it never reaches the reset password page.

When I click the forgot password link the method below is called , it steps through the code fine, but then loads the login page.

Reset Password code

public void ResetPassword(string redirectUrl)
    {
        // Let the middleware know you are trying to use the reset password policy (see OnRedirectToIdentityProvider in Startup.Auth.cs)
        HttpContext.GetOwinContext().Set("Policy", Startup.PasswordResetPolicyId);

        // Set the page to redirect to after changing passwords
        var authenticationProperties = new AuthenticationProperties { RedirectUri = "/" };
        HttpContext.GetOwinContext().Authentication.Challenge(authenticationProperties);

        return;
    }

The policy ID is correct in both azure and in the code as I step through and the values are all pulling through correctly (see below):

Policy ID string (as used above)

public static string PasswordResetPolicyId = ConfigurationManager.AppSettings["ida:ResetPasswordPolicyId"];

In Web.config where the policy is defined

<add key="ida:ResetPasswordPolicyId" value="B2C_1_UserApp_ResetPassword" />

I have provided all the code samples I have added for the reset function to work, the rest of the code is all included in the Microsoft Web App example.

Has anyone else experienced something similar? As I said previously, when you click the forgot password link it does exactly as it should and goes to the correct controller/method, but then goes back to the login screen.

Body:
Searching through my code, I found that the line

app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(PasswordResetPolicyId));

was missing from ConfigureAuth. Once added this has fixed the issue.

public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {

                CookieManager = new SystemWebCookieManager()

            });
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
            /////////////////
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(PasswordResetPolicyId));
        }


问:
Check if at least two elements in an array are greater than zero - JavaScript/Typescript
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

```<code>const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false

</code>```

答:
If you don't want to iterate over the entire array you can use a loop and break out of it early once your condition is satisfied. I think the answer that uses filter is more elegant, but if you're list is insanely large you might see a benefit from not iterating the entire thing.

I broke this function into it's basic parts and created a curried version.

The question is "are there 2 or more values greater than 0 in the array". But it can be boiled down to "are there X or more values that pass comparator"?

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const quantityCompare = compare => quantity => arr => {
  let count = 0;
  for (let i = 0; i < arr.length; i += 1) {
    if (compare(arr[i])) count += 1;
    if (count >= quantity) return true;
  }
  return false;
};

const twoElementsGreaterThanZero = quantityCompare(x => x > 0)(2);

console.log(twoElementsGreaterThanZero(a)); // true
console.log(twoElementsGreaterThanZero(b)); // false
console.log(twoElementsGreaterThanZero(c)); // false```
</div>
</div>
</p>

<p>One more for fun, you can use <code>Array.some</code> (an <code>Array.forEach</code> you can break out of) instead of the for loop:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const quantityCompare = compare => quantity => arr => {
  let count = 0;
  return arr.some(el => {
    if (compare(el)) count += 1;
    if (count >= quantity) return true;
  })
}

const twoElementsGreaterThanZero = quantityCompare(x => x > 0)(2);

console.log(twoElementsGreaterThanZero(a)); // true
console.log(twoElementsGreaterThanZero(b)); // false
console.log(twoElementsGreaterThanZero(c)); // false</code>```

Body:
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false

Body:
If you don't want to iterate over the entire array you can use a loop and break out of it early once your condition is satisfied. I think the answer that uses filter is more elegant, but if you're list is insanely large you might see a benefit from not iterating the entire thing.

I broke this function into it's basic parts and created a curried version.

The question is "are there 2 or more values greater than 0 in the array". But it can be boiled down to "are there X or more values that pass comparator"?

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const quantityCompare = compare => quantity => arr => {
  let count = 0;
  for (let i = 0; i < arr.length; i += 1) {
    if (compare(arr[i])) count += 1;
    if (count >= quantity) return true;
  }
  return false;
};

const twoElementsGreaterThanZero = quantityCompare(x => x > 0)(2);

console.log(twoElementsGreaterThanZero(a)); // true
console.log(twoElementsGreaterThanZero(b)); // false
console.log(twoElementsGreaterThanZero(c)); // false

One more for fun, you can use Array.some (an Array.forEach you can break out of) instead of the for loop:

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const quantityCompare = compare => quantity => arr => {
  let count = 0;
  return arr.some(el => {
    if (compare(el)) count += 1;
    if (count >= quantity) return true;
  })
}

const twoElementsGreaterThanZero = quantityCompare(x => x > 0)(2);

console.log(twoElementsGreaterThanZero(a)); // true
console.log(twoElementsGreaterThanZero(b)); // false
console.log(twoElementsGreaterThanZero(c)); // false


问:
Bootstrap progress bar custom border radius
I have the following snippet :

.progress-bar{
    border-top-right-radius: 40px !important;
    border-bottom-right-radius: 40px !important;
    -webkit-box-shadow: none !important;
   -moz-box-shadow: none !important;
   box-shadow: none !important;
}

.progress{
    border-radius: 40px !important;
    background-color: white !important;
    -webkit-box-shadow: none !important;
   -moz-box-shadow: none !important;
   box-shadow: none !important;
    border: 2px solid #337AB7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%;"></div>
</div></code>```

I don't understand why I have the white space on the left, I would like to get rid of it.

答:
This is a rendering issue due to the border CSS on in the .progress class. It is resizing its children elements.

In this case, the height of the .progress-bar element is actually being reduced by 4px due to the 2px border (2px top + 2px bottom), and thus the curvature of the radius isn't quite the same.

Instead, you can use a box-shadow as it doesn't resize its children elements.

.progress-bar{
    border-top-right-radius: 40px !important;
    border-bottom-right-radius: 40px !important;
    -webkit-box-shadow: none !important;
   -moz-box-shadow: none !important;
   box-shadow: none !important;
}

.progress{
    border-radius: 40px !important;
    background-color: white !important;

    /* Changes below */
    -webkit-box-shadow: inset 0 0 0 2px #337AB7 !important;
   -moz-box-shadow: inset 0 0 0 2px #337AB7 !important;
   box-shadow: inset 0 0 0 2px #337AB7 !important;
    border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%;"></div>
</div></code>```

Body:
I have the following snippet :

.progress-bar{
    border-top-right-radius: 40px !important;
    border-bottom-right-radius: 40px !important;
    -webkit-box-shadow: none !important;
   -moz-box-shadow: none !important;
   box-shadow: none !important;
}

.progress{
    border-radius: 40px !important;
    background-color: white !important;
    -webkit-box-shadow: none !important;
   -moz-box-shadow: none !important;
   box-shadow: none !important;
    border: 2px solid #337AB7;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

I don't understand why I have the white space on the left, I would like to get rid of it.

Body:
This is a rendering issue due to the border CSS on in the .progress class. It is resizing its children elements.

In this case, the height of the .progress-bar element is actually being reduced by 4px due to the 2px border (2px top + 2px bottom), and thus the curvature of the radius isn't quite the same.

Instead, you can use a box-shadow as it doesn't resize its children elements.

.progress-bar{
    border-top-right-radius: 40px !important;
    border-bottom-right-radius: 40px !important;
    -webkit-box-shadow: none !important;
   -moz-box-shadow: none !important;
   box-shadow: none !important;
}

.progress{
    border-radius: 40px !important;
    background-color: white !important;

    /* Changes below */
    -webkit-box-shadow: inset 0 0 0 2px #337AB7 !important;
   -moz-box-shadow: inset 0 0 0 2px #337AB7 !important;
   box-shadow: inset 0 0 0 2px #337AB7 !important;
    border: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%;"></div>
</div>


问:
How to clear inputs after useReducer
I am using useReducer to control my 2 inputs:

```<code>const [noteInput, setNoteInput] = useReducer(
    (state, newState) => ({ ...state, ...newState }),
    {
      title: '',
      content: ''
    }
  );
</code>```

After onClick on button i want both inputs to be cleared. How can i do that after useReducer?

答:
You can update your state to empty using setState OR You can dispatch other actions for updating that state to the empty string.
 https://redux.js.org/basics/reducers#reducers</p>

Title: How to clear inputs after useReducer

Body:
I am using useReducer to control my 2 inputs:

const [noteInput, setNoteInput] = useReducer(
    (state, newState) => ({ ...state, ...newState }),
    {
      title: '',
      content: ''
    }
  );

After onClick on button i want both inputs to be cleared. How can i do that after useReducer?


问:
Converting string to IP Address in java(android)
When i convert string ("192.168.0.105") to InetAddress in java (android). I am getting "/192.168.0.105". An extra "/" is coming in InetAddress, which causes the socket not to be created.

How do i get rid of "/".

Regards,

Syed Mustehsan Ikram

答:
```<code>myString = myString.replace("/", "");
</code>```

Body: myString = myString.replace("/", "");


问:
How to create tables and perform queries in Flask without using models?
I'm trying to create a table in Amazon Redshift with Flask, since you can't use models to create tables, how can I create them with SQL directly?

for example .execute ("CREATE TABLE ..."

答:
If you want to execute raw SQL queries in a Flask app, use SQLAlchemy's execute() method

result = db.engine.execute("<sql here>")
```

I would question your assumptions that you cannot use models (presumably from sql-alchemy) to create tables. I am not a Redshift user, but it seems that once the SQL connection is there, most standard SQL features would be available, and you can use tools like SQLAlchemy and Alembic to work with models instead of raw SQL. It appears there is already a SQLAlchemy plugin to help with Redshift connections.

Body:
If you want to execute raw SQL queries in a Flask app, use SQLAlchemy's execute() method

result = db.engine.execute("<sql here>")

I would question your assumptions that you cannot use models (presumably from sql-alchemy) to create tables. I am not a Redshift user, but it seems that once the SQL connection is there, most standard SQL features would be available, and you can use tools like SQLAlchemy and Alembic to work with models instead of raw SQL. It appears there is already a SQLAlchemy plugin to help with Redshift connections.


答:
You can use call or apply to execute a function with another context. Most JavaScript functions are designed to be generic, which is to say that it will work with most variable types.

```<code>String.prototype.repeat.call(1, 2); // -> "11"
String.prototype.repeat.call({}, 2); // -> "[object Object][object Object]"
</code>```

Because of this, a simple check is put in place to make sure no-one tries executing it with the context of null or undefined

```<code>String.prototype.repeat.call(null, 2); // TypeError
</code>```

Title: MDN String.prototype.repeat polyfill - How can 'this' have value null?

Body:
You can use call or apply to execute a function with another context. Most JavaScript functions are designed to be generic, which is to say that it will work with most variable types.

String.prototype.repeat.call(1, 2); // -> "11"
String.prototype.repeat.call({}, 2); // -> "[object Object][object Object]"

Because of this, a simple check is put in place to make sure no-one tries executing it with the context of null or undefined

String.prototype.repeat.call(null, 2); // TypeError


问:
is there any way to use .indexOf to search a javascript array in mirth?
I am trying to find a string in a javascript array in the transformer of a mirth channel. Mirth throws an error when I try to use indexOf function. My understanding is that indexOf is something that browsers add in, rather than a native part of the javascript language itself. ( How do I check if an array includes an object in JavaScript? )

So is array.indexOf just not supported in Mirth? Is there any way to use .indexOf in Mirth? Maybe an alternate syntax? Or do I need to just loop thru the array to search?

答:
```<code>var arr = ['john',1,'Peter'];

if(arr.indexOf('john') > -1)
{
    //match. what to do?
    console.log("found");
}
else
{
    console.log("not found");//not found .. do something
}

</code>```


问:
Get list of all files (every file) in both internal and external storage with absolute path in Android
I'm working on an app which analyses the user's storage and give information like Total Images, Videos, Audios, Archives, Executables and other files. With MediaStore i can only get the Media files files but i want a list of every single file present on the device's storage (both internal and external) with their absolute path so that i can access them.</p>

答:
Try this:</p>

```<code>.....
List<File> files = getListFiles(new File("YOUR ROOT"));
....
private List<File> getListFiles(File parentDir) {
    ArrayList<File> inFiles = new ArrayList<File>();
    File[] files = parentDir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            inFiles.addAll(getListFiles(file));
        } else {
            if(file.getName().endsWith(".csv")){
                inFiles.add(file);
            }
        }
    }
    return inFiles;
}
</code>```

Body:
Try this:

.....
List<File> files = getListFiles(new File("YOUR ROOT"));
....
private List<File> getListFiles(File parentDir) {
    ArrayList<File> inFiles = new ArrayList<File>();
    File[] files = parentDir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            inFiles.addAll(getListFiles(file));
        } else {
            if(file.getName().endsWith(".csv")){
                inFiles.add(file);
            }
        }
    }
    return inFiles;
}


问:
dtN.filter for slow typers
When using dtN.filter slow typers get a refresh and then it show the filtered data but there is no possibility to type further as the input element is not focused.

<input *ngSwitchCase="'MasterData.Name'" pInputText type="text" [(ngModel)]="colFilter_2"
          (input)="dtN.filter($event.target.value, col.field, col.filterMatchMode);">

Is there a global setting of some sort to set the timeout of this so
that it does not fire right away but after x milliseconds?

Is there an option to see the input that fired the filter so that I
can set focus back to that input?

thanks in advance

Title: dtN.filter for slow typers

Body:
Just found the answer myself. There is a filterDelay option that you can set on the table not ons the specific filter. The default settign is 300milliseconds

<p-table [filterDelay]="900">


问:
Problem retrieving Dynamics CRM custom fields for integration in ADF
I am doing data integration from Dynamics CRM to Azure SQL Database using Azure Data Factory. I am unable to fetch the custom fields
created in Dynamics CRM for doing the mapping in integration. Please help me with the solution for the above.</p>

答:
We ran pretty hard into the limitations of the Dynamics connector of Azure Data Factory v2. The ADF Dynamics connector does not expand the fields and requires a way too big rewrite of our current logic. Either with an entity selection or FetchXML, same results.

We were using SSIS + Cozyroc that did expand a lot of fields automatically. So we are back to using SSIS + Cozyroc. And since running custom components on SSIS-IR is... challenging we are also back to running SSIS on-premise.


问:
Handle multiple Cameras using Flask and OpenCV
While Testing the live video streaming (laptop and USB webcam) through flask, I am not able to display the video streaming on the main page as well as while accessing the decorator. My main aim is to access multiple cameras through using flask mentioned below is the code I am working on

app.py

```<code>from flask import Flask, render_template, Response
import cv2

app = Flask(__name__)

def find_camera(id):
    cameras = ['0','1']
    print(cameras[id])
    return cameras[int(id)]
#  for cctv camera use rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' instead of camera
#  for webcam use zero(0)

def gen_frames(camera_id):

    cam = find_camera(camera_id)
    cap= cv2.VideoCapture(cam)

    while True:
        # for cap in caps:
        # # Capture frame-by-frame
        success, frame = cap.read()  # read the camera frame
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # concat frame one by one and show result

@app.route('/video_feed/<string:id>/', methods=["GET"])
def video_feed(id):

    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen_frames(id),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/', methods=["GET"])
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()
</code>```

HTML page

```<code><!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Multiple Live Streaming</title>
</head>
<body>
<div class="container">
    <div class="row">

        <div class="col-lg-7">
            <h3 class="mt-5">Multiple Live Streaming</h3>
            <img src="{{ url_for('video_feed', id='0') }}" width="100%">
        </div>

    </div>
</div>
</body>
</html>
</code>```

Being a beginner to this I need to know whether we need to use multithreading for handling multiple cameras at a time?

Any suggestions on this will be a great help.

答:
As suggested, it would be much better to use ip addresses and loop through them. It would make for much better clarity ion your code. Your flask code would in-turn look like this:

```<code>from flask import Flask, render_template, Response
import cv2

app = Flask(__name__)

# list of camera accesses
cameras = [
 "rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp",
 "rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp",
...
  ]

def find_camera(list_id):
    return cameras[int(list_id)]

def gen_frames(camera_id):
    cam = find_camera(camera_id)  # return the camera access link with credentials. Assume 0?
    # cam = cameras[int(id)]
    cap = cv2.VideoCapture(cam)  # capture the video from the live feed

    while True:

        # # Capture frame-by-frame. Return boolean(True=frame read correctly. )
        success, frame = cap.read()  # read the camera frame
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # concat frame one by one and show result

@app.route('/video_feed/<string:list_id>/', methods=["GET"])
def video_feed(list_id):
    return Response(gen_frames(list_id),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/', methods=["GET"])
def index():
    return render_template('index.html', camera_list=len(cameras), camera=cameras)

if __name__ == '__main__':
    app.run()
</code>```

Notice how I get the length of my list of camera addresses and the whole list in the index function. I'm using this because I want to assume the code will just keep adding/removing feeds to the template file if any camera credential is provided or removed.

Your template file would then look something like this:

```<code> {% for camera_number in range(0, camera_list) %}
            <div class="col-lg-5">
                <img src="{{ url_for('video_feed', list_id=camera_number) }}" width="100%"><br/>
            </div>
        {% endfor %}

</code>```

Here, you would get the length of the list of cameras its list as well from where you can pass to the URL. This should work. Do reach out if you need further clarification.

Body:
While Testing the live video streaming (laptop and USB webcam) through flask, I am not able to display the video streaming on the main page as well as while accessing the decorator. My main aim is to access multiple cameras through using flask mentioned below is the code I am working on

app.py

from flask import Flask, render_template, Response
import cv2

app = Flask(__name__)

def find_camera(id):
    cameras = ['0','1']
    print(cameras[id])
    return cameras[int(id)]
#  for cctv camera use rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' instead of camera
#  for webcam use zero(0)

def gen_frames(camera_id):

    cam = find_camera(camera_id)
    cap= cv2.VideoCapture(cam)

    while True:
        # for cap in caps:
        # # Capture frame-by-frame
        success, frame = cap.read()  # read the camera frame
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # concat frame one by one and show result

@app.route('/video_feed/<string:id>/', methods=["GET"])
def video_feed(id):

    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen_frames(id),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/', methods=["GET"])
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

HTML page

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Multiple Live Streaming</title>

Multiple Live Streaming

Being a beginner to this I need to know whether we need to use multithreading for handling multiple cameras at a time?

Any suggestions on this will be a great help.

Body:
As suggested, it would be much better to use ip addresses and loop through them. It would make for much better clarity ion your code. Your flask code would in-turn look like this:

from flask import Flask, render_template, Response
import cv2

app = Flask(__name__)

# list of camera accesses
cameras = [
 "rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp",
 "rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp",
...
  ]

def find_camera(list_id):
    return cameras[int(list_id)]

def gen_frames(camera_id):
    cam = find_camera(camera_id)  # return the camera access link with credentials. Assume 0?
    # cam = cameras[int(id)]
    cap = cv2.VideoCapture(cam)  # capture the video from the live feed

    while True:

        # # Capture frame-by-frame. Return boolean(True=frame read correctly. )
        success, frame = cap.read()  # read the camera frame
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # concat frame one by one and show result

@app.route('/video_feed/<string:list_id>/', methods=["GET"])
def video_feed(list_id):
    return Response(gen_frames(list_id),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/', methods=["GET"])
def index():
    return render_template('index.html', camera_list=len(cameras), camera=cameras)

if __name__ == '__main__':
    app.run()

Notice how I get the length of my list of camera addresses and the whole list in the index function. I'm using this because I want to assume the code will just keep adding/removing feeds to the template file if any camera credential is provided or removed.

Your template file would then look something like this:

 {% for camera_number in range(0, camera_list) %}
            <div class="col-lg-5">
                <img src="{{ url_for('video_feed', list_id=camera_number) }}" width="100%"><br/>
            </div>
        {% endfor %}

Here, you would get the length of the list of cameras its list as well from where you can pass to the URL. This should work. Do reach out if you need further clarification.


问:
is there a way to use JMS (java message service) on ESP32?
I'm trying to build an application in which I want to use the JMS (java message service). Unfortunately, I'm unable to find any libraries specifically for ESM32-WROOM online. So, can anyone help me with how can I build the JMS stack for ESM32-WROOM on my own if it's possible!. In my application, the ESP32-WROOM will get messages from the server every second.</p>

答:
As noted in your question, JMS is the Java Message Service so in order to use it you'd need to use Java which would require a Java Virtual Machine (i.e. JVM). The JVM is a sophisticated piece of software which is almost certainly not supported on ESP32.

Most JMS providers also support other protocols for IoT devices like ESP32. For example, ActiveMQ Artemis supports JMS as well as MQTT (among other protocols). MQTT is a protocol specifically created for small sensors and mobile devices. It is optimized for high-latency or unreliable networks which makes it a good fit for IoT devices. I recommend you use MQTT on your device if possible. Take a look at the ESP32 MQTT Library.


问:
Hamcrest matchers for a List<Set<String>>
I am trying to write a JUnit test for a method that returns

```<code>List<Set<String>> result = build(List<Account> accounts, List<Order> orders);
</code>```

I can check that I have the expected number of entries with

```<code>assertThat(result, hasSize(2));
</code>```

But I'm struggling to find clear documentation on how to write an assert that the list contains one entry with a set size of 2 and one entry with a set size of 4. If someone could point me to the relevant documentation that I need to read, I would be grateful

答:
I don't recall Hamcrest having anything for this particular setup.

I would just test one of the sets for size and then ensure the sum is 6

Using hamcrest-2.2.jar from hamcrest.org and JUnit4 this fails in the 3rd assertThat, since I deliberately created it to fail with an expected value of 5. The test reports no failure when set to 6:

```<code>import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Test;

import java.util.List;
import java.util.Set;

public class MyListTest {

  @Test
  public void listSize() {
    MyList tester = new MyList();
    List<Set<String>> result = tester.generate();

    // assert statements
    assertThat(result, hasSize(2));                                        // yours
    assertThat(result.get(0), anyOf(hasSize(2), hasSize(4)));              // is either 2 or 4
    assertThat((result.get(0).size() + result.get(1).size()), equalTo(5)); // sum must be 6. FAILS with 5 :)
  }
}
</code>```

Tested class:

```<code>import java.util.List;
import java.util.Set;

public class MyList {
  public List<Set<String>> generate() {
    Set<String> s1 = Set.of("Hello", "World");
    Set<String> s2 = Set.of("Testing", "One", "Two", "Three");
    return List.of(s1,s2);
  }
}
</code>```

Body:
I am trying to write a JUnit test for a method that returns

List<Set<String>> result = build(List<Account> accounts, List<Order> orders);

I can check that I have the expected number of entries with

assertThat(result, hasSize(2));

But I'm struggling to find clear documentation on how to write an assert that the list contains one entry with a set size of 2 and one entry with a set size of 4. If someone could point me to the relevant documentation that I need to read, I would be grateful

Body:
I don't recall Hamcrest having anything for this particular setup.

I would just test one of the sets for size and then ensure the sum is 6

Using hamcrest-2.2.jar from hamcrest.org and JUnit4 this fails in the 3rd assertThat, since I deliberately created it to fail with an expected value of 5. The test reports no failure when set to 6:

import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Test;

import java.util.List;
import java.util.Set;

public class MyListTest {

  @Test
  public void listSize() {
    MyList tester = new MyList();
    List<Set<String>> result = tester.generate();

    // assert statements
    assertThat(result, hasSize(2));                                        // yours
    assertThat(result.get(0), anyOf(hasSize(2), hasSize(4)));              // is either 2 or 4
    assertThat((result.get(0).size() + result.get(1).size()), equalTo(5)); // sum must be 6. FAILS with 5 :)
  }
}

Tested class:

import java.util.List;
import java.util.Set;

public class MyList {
  public List<Set<String>> generate() {
    Set<String> s1 = Set.of("Hello", "World");
    Set<String> s2 = Set.of("Testing", "One", "Two", "Three");
    return List.of(s1,s2);
  }
}


问:
MDN String.prototype.repeat polyfill - How can 'this' have value null?
In the MDN doc for String.prototype.repeat the polyfill has this line of code:

```<code>if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null)
      throw new TypeError('can\'t convert ' + this + ' to object');
</code>```

How is it possible for this to be null?

答:
```<code>const test = 'test'.repeat;
test();
</code>```

Body:
In the MDN doc for String.prototype.repeat the polyfill has this line of code:

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null)
      throw new TypeError('can\'t convert ' + this + ' to object');

How is it possible for this to be null?

Body:
const test = 'test'.repeat;
test();


问:
python DEAP library Multiple Processors
I want to solve a multi-objective optimization problem using DEAP, a python based framework. Due to time consuming processes, i need to use all of my CPU power to compute. So i used multiprocessing library as suggested in DEAP documentation an this example, but it results in PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed .
My total code is too long to write it down hear, but the following code is similar to my code and results in the same error.Can you please tell me where do i make mistake?
Thanks in advance

```<code>import multiprocessing
from deap import creator, base, tools, algorithms
import random
import matplotlib.pyplot as plt
def TEST(dec_var):
    return dec_var[0]**2+dec_var[1]**2,(dec_var[0]-2)**2+dec_var[1]**2
def feasible(dec_var):
    if all(i>0 for i in dec_var):
        return True
    return False

creator.create("FitnessMin", base.Fitness, weights=(-1.0,-1.0))
creator.create("Individual", list, fitness=creator.FitnessMin)
toolbox=base.Toolbox()

toolbox.register("uniform", random.uniform, 0.0, 7.0)
toolbox.register("individual",tools.initRepeat,creator.Individual,toolbox.uniform ,n=2)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1)
toolbox.register("select", tools.selNSGA2)
toolbox.register("evaluate", TEST)
toolbox.decorate("evaluate", tools.DeltaPenalty(feasible,(1000,1000)))

def main(seed=None):
    random.seed(seed)

    NGEN = 250
    MU = 100
    CXPB = 0.9

    stats_func1 = tools.Statistics(key=lambda ind: ind.fitness.values[0])
    stats_func2 = tools.Statistics(key=lambda ind: ind.fitness.values[1])
    stats = tools.MultiStatistics(func1=stats_func1, func2=stats_func2)
    stats.register("avg", numpy.mean, axis=0)
    stats.register("std", numpy.std, axis=0)
    stats.register("min", numpy.min, axis=0)
    stats.register("max", numpy.max, axis=0)

    logbook = tools.Logbook()
    logbook.header = "gen", "evals", "func1","func2"
    logbook.chapters["func1"].header = "min", "max"
    logbook.chapters["func2"].header = "min", "max"
    pop = toolbox.population(n=MU)

    invalid_ind = [ind for ind in pop if not ind.fitness.valid]
    fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
    for ind, fit in zip(invalid_ind, fitnesses):
        ind.fitness.values = fit

    pop = toolbox.select(pop, len(pop))
    record = stats.compile(pop)
    logbook.record(gen=0, evals=len(invalid_ind), **record)
    print(logbook.stream)

    for gen in range(1, NGEN):

        offspring = tools.selTournamentDCD(pop, len(pop))
        offspring = [toolbox.clone(ind) for ind in offspring]

        for ind1, ind2 in zip(offspring[::2], offspring[1::2]):
            if random.random() <= CXPB:
                toolbox.mate(ind1, ind2)

            toolbox.mutate(ind1)
            toolbox.mutate(ind2)
            del ind1.fitness.values, ind2.fitness.values

        invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            ind.fitness.values = fit

        pop = toolbox.select(pop + offspring, MU)
        record = stats.compile(pop)
        logbook.record(gen=gen, evals=len(invalid_ind), **record)
        print(logbook.stream)

    return pop, logbook
if __name__ == "__main__":
    pool = multiprocessing.Pool(processes=4)
    toolbox.register("map", pool.map)
    pop, stats = main()
    pool.close()
    print pop
</code>```

答:
This is noted on the documentation page you linked:

The pickling of lambda function is not yet available in Python.

You are using lambda functions in stats_func1 and stats_func2 – just move them to global functions and try again:

def stats_key_1(ind):
    return ind.fitness.values[0]

def stats_key_2(ind):
    return ind.fitness.values[1]

# ... snip ...

def main(seed=None):

    # ... snip ...

    stats_func1 = tools.Statistics(key=stats_key_1)
    stats_func2 = tools.Statistics(key=stats_key_1)
```

Title: python DEAP library Multiple Processors

Body:
I want to solve a multi-objective optimization problem using DEAP, a python based framework. Due to time consuming processes, i need to use all of my CPU power to compute. So i used multiprocessing library as suggested in DEAP documentation an this example, but it results in PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed .
My total code is too long to write it down hear, but the following code is similar to my code and results in the same error.Can you please tell me where do i make mistake?
Thanks in advance

import multiprocessing
from deap import creator, base, tools, algorithms
import random
import matplotlib.pyplot as plt
def TEST(dec_var):
    return dec_var[0]**2+dec_var[1]**2,(dec_var[0]-2)**2+dec_var[1]**2
def feasible(dec_var):
    if all(i>0 for i in dec_var):
        return True
    return False

creator.create("FitnessMin", base.Fitness, weights=(-1.0,-1.0))
creator.create("Individual", list, fitness=creator.FitnessMin)
toolbox=base.Toolbox()

toolbox.register("uniform", random.uniform, 0.0, 7.0)
toolbox.register("individual",tools.initRepeat,creator.Individual,toolbox.uniform ,n=2)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1)
toolbox.register("select", tools.selNSGA2)
toolbox.register("evaluate", TEST)
toolbox.decorate("evaluate", tools.DeltaPenalty(feasible,(1000,1000)))

def main(seed=None):
    random.seed(seed)

    NGEN = 250
    MU = 100
    CXPB = 0.9

    stats_func1 = tools.Statistics(key=lambda ind: ind.fitness.values[0])
    stats_func2 = tools.Statistics(key=lambda ind: ind.fitness.values[1])
    stats = tools.MultiStatistics(func1=stats_func1, func2=stats_func2)
    stats.register("avg", numpy.mean, axis=0)
    stats.register("std", numpy.std, axis=0)
    stats.register("min", numpy.min, axis=0)
    stats.register("max", numpy.max, axis=0)

    logbook = tools.Logbook()
    logbook.header = "gen", "evals", "func1","func2"
    logbook.chapters["func1"].header = "min", "max"
    logbook.chapters["func2"].header = "min", "max"
    pop = toolbox.population(n=MU)

    invalid_ind = [ind for ind in pop if not ind.fitness.valid]
    fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
    for ind, fit in zip(invalid_ind, fitnesses):
        ind.fitness.values = fit

    pop = toolbox.select(pop, len(pop))
    record = stats.compile(pop)
    logbook.record(gen=0, evals=len(invalid_ind), **record)
    print(logbook.stream)

    for gen in range(1, NGEN):

        offspring = tools.selTournamentDCD(pop, len(pop))
        offspring = [toolbox.clone(ind) for ind in offspring]

        for ind1, ind2 in zip(offspring[::2], offspring[1::2]):
            if random.random() <= CXPB:
                toolbox.mate(ind1, ind2)

            toolbox.mutate(ind1)
            toolbox.mutate(ind2)
            del ind1.fitness.values, ind2.fitness.values

        invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            ind.fitness.values = fit

        pop = toolbox.select(pop + offspring, MU)
        record = stats.compile(pop)
        logbook.record(gen=gen, evals=len(invalid_ind), **record)
        print(logbook.stream)

    return pop, logbook
if __name__ == "__main__":
    pool = multiprocessing.Pool(processes=4)
    toolbox.register("map", pool.map)
    pop, stats = main()
    pool.close()
    print pop


问:
AEADBadTagException: Input too short - need tag. How to pass a tag?
I have a method to decrypt data:

```<code>private byte[] decrypt(byte[] sessionKey, byte[] initialisationVector, byte[] associatedData, byte[] cipherText, byte[] tag) {
    Key secret = new SecretKeySpec(sessionKey, "AES");

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, secret,
                new GCMParameterSpec((GCM_AUTHENTICATION_TAG_SIZE) * Byte.SIZE, initialisationVector));
    cipher.updateAAD(associatedData);

    return cipher.doFinal(concatByteArrays(cipherText, tag));
}
</code>```

concatByteArrays is a simple method with Bytebuffer.allocate.put methods.
UPD: input -

```<code>    byte[] TEST_AES_KEY = new byte[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    int INITIALISATION_VECTOR_LENGTH = 12;
    int GCM_AUTHENTICATION_TAG_SIZE = 16;
    byte[] initialisationVector = Arrays.copyOfRange(receivedPacket, 0, INITIALISATION_VECTOR_LENGTH - 1);
    byte[] tag = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE - 1);
    byte[] associatedData = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE, receivedPacket.length - 1);
    byte[] cipherText = new byte[]{};

byte[] plainText = decrypt(key, initialisationVector, associatedData, cipherText, tag);
</code>```

But get error:

```<code>javax.crypto.AEADBadTagException: Input too short - need tag
        at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterM
ode.java:524)
        at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:104
8)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:985)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
        at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
        at javax.crypto.Cipher.doFinal(Cipher.java:2164)
</code>```

I can't understand how I can pass tag.
I have a python code, which works:

```<code>decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend).decryptor()

decryptor.authenticate_additional_data(aad)

return decryptor.update(ciphertext) + decryptor.finalize()
</code>```

答:
Stupid mistake. I forgot that in arrays.copyof last parameter is exclusive and got wrong byte arrays from receivedPacket.</p>

```<code>    byte[] initialisationVector = Arrays.copyOfRange(receivedPacket, 0, INITIALISATION_VECTOR_LENGTH);
    byte[] tag = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE);
    byte[] associatedData = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE, receivedPacket.length);
</code>```

Body:
I have a method to decrypt data:

private byte[] decrypt(byte[] sessionKey, byte[] initialisationVector, byte[] associatedData, byte[] cipherText, byte[] tag) {
    Key secret = new SecretKeySpec(sessionKey, "AES");

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, secret,
                new GCMParameterSpec((GCM_AUTHENTICATION_TAG_SIZE) * Byte.SIZE, initialisationVector));
    cipher.updateAAD(associatedData);

    return cipher.doFinal(concatByteArrays(cipherText, tag));
}

concatByteArrays is a simple method with Bytebuffer.allocate.put methods.
UPD: input -

    byte[] TEST_AES_KEY = new byte[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    int INITIALISATION_VECTOR_LENGTH = 12;
    int GCM_AUTHENTICATION_TAG_SIZE = 16;
    byte[] initialisationVector = Arrays.copyOfRange(receivedPacket, 0, INITIALISATION_VECTOR_LENGTH - 1);
    byte[] tag = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE - 1);
    byte[] associatedData = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE, receivedPacket.length - 1);
    byte[] cipherText = new byte[]{};

byte[] plainText = decrypt(key, initialisationVector, associatedData, cipherText, tag);

But get error:

javax.crypto.AEADBadTagException: Input too short - need tag
        at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterM
ode.java:524)
        at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:104
8)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:985)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
        at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
        at javax.crypto.Cipher.doFinal(Cipher.java:2164)

I can't understand how I can pass tag.
I have a python code, which works:

decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend).decryptor()

decryptor.authenticate_additional_data(aad)

return decryptor.update(ciphertext) + decryptor.finalize()

Body:
Stupid mistake. I forgot that in arrays.copyof last parameter is exclusive and got wrong byte arrays from receivedPacket.

    byte[] initialisationVector = Arrays.copyOfRange(receivedPacket, 0, INITIALISATION_VECTOR_LENGTH);
    byte[] tag = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE);
    byte[] associatedData = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE, receivedPacket.length);


问:
Download file and converter to type doc or pdf
I have a URL that returns a .dat file, I would like to download it but converted to a .pdf or .doc extension, could someone help me?

I'm doing in typescript

URL: http://172.17.0.53:8060/leisarq/\originais\0000000\0000000000353.dat

答:
documento.service.ts :

```<code>  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download/", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }
</code>```

DocumentResource

```<code>    @RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    File file = new File(documentoDTO.getPathorigdoc());
    response.setContentType("pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento());
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}
</code>```

Body:
documento.service.ts :

  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download/", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }

DocumentResource

    @RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    File file = new File(documentoDTO.getPathorigdoc());
    response.setContentType("pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento());
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}