问:
Camel: Unresolved dependency exception for Camel Component
I am creating a Maven based Camel Component. I have added relevant dependencies in POM.xml but still I get below exception:

Unresolved dependency: (&(component=FileFormatConversion)(objectClass=org.apache.camel.spi.ComponentResolver))

I was able to build & run the Maven project. My component jar is however present in the component Folder:

Component Folder

Can anyone advise if there is some issue with my POM or the reason behind this exception. Here is my POM.

```<code><?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>FileFormatConversion</groupId>
<artifactId>FileFormatConversion</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>
<name>${project.groupId}.${project.artifactId}</name>

<properties>
    <camel.version>2.18.0</camel.version>
    <import.packages>*;version="0";resolution:=optional</import.packages>
    <private.packages>!*</private.packages>
    <symbolic.name>${project.groupId}</symbolic.name>
    <embed-dep>*;scope=compile;type=!pom;inline=true</embed-dep>
    <unpack-bundle>false</unpack-bundle>
    <maven.test.skip>true</maven.test.skip>
    <maven.test.failure.ignore>true</maven.test.failure.ignore>
</properties>

<dependencies>
    <!-- Check for the latest version of this artifact in central maven repository -->
    <dependency>
        <groupId>com.sap.cloud.adk</groupId>
        <artifactId>com.sap.cloud.adk.build.archive</artifactId>
        <version>1.24.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-core</artifactId>
        <version>${camel.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.camel/camel-component -->
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-component</artifactId>
        <version>1.4.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/in.jlibs/jlibs-xsd -->
    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-xsd</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-xml</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-visitor</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-core</artifactId>
        <version>2.2.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache/xerces -->
    <dependency>
        <groupId>org.apache</groupId>
        <artifactId>xerces</artifactId>
        <version>2.9.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/xerces/xercesImpl -->
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
    </dependency>
    <!-- testing -->
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-test</artifactId>
        <version>${camel.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.6.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>
    <plugins>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <extensions>true</extensions>
            <version>4.2.0</version>
            <inherited>true</inherited>

            <configuration>
                <excludeDependencies>true</excludeDependencies>

                <instructions>
                    <Include-Resource>src/main/resources/,lib/</Include-Resource>
                    <Bundle-SymbolicName>${symbolic.name}</Bundle-SymbolicName>
                    <Bundle-Classpath>.,jax-qname.jar,jaxmexs-0.5.jar,xsd-2.2.3.jar,jlibs-core-2.2.1.jar,jlibs-visitor-2.2.1.jar,jlibs-xml-2.2.1.jar,
                        jlibs-xsd-2.2.1.jar,xercesImpl-2.11.0.jar,xml-apis-1.4.01.jar,FileFormatConversion-1.0.0.jar
                    </Bundle-Classpath>

                    <Import-Package>${import.packages}</Import-Package>

                </instructions>
            </configuration>

        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <testFailureIgnore>true</testFailureIgnore>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.1.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/libs</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                        <excludeTransitive>true</excludeTransitive>

                        <!-- Specify the artifacts to be excluded in the dependencies -->
                        <excludeArtifactIds></excludeArtifactIds>

                        <!-- Specify the group ids to be excluded in the dependencies -->
                        <excludeGroupIds>com.sap.cloud.adk,org.apache.camel,org.slf4j,log4j,in.jlibs,xerces,org.apache</excludeGroupIds>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>com.sap.cloud.adk</groupId>
            <artifactId>com.sap.cloud.adk.build.archive</artifactId>
            <version>1.24.0</version>
        </plugin>
    </plugins>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>com.sap.cloud.adk</groupId>
                <artifactId>com.sap.cloud.adk.build.archive</artifactId>
                <executions>
                    <execution>
                        <id>build-adapter</id>
                        <phase>install</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                        <configuration>
                            <adapterProjectDirectory>${project.basedir}</adapterProjectDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
</code>```

答:
I resolved the issue myself. The Problem was in below Statement:

${import.packages}

Body:
I am creating a Maven based Camel Component. I have added relevant dependencies in POM.xml but still I get below exception:

Unresolved dependency: (&(component=FileFormatConversion)(objectClass=org.apache.camel.spi.ComponentResolver))

I was able to build & run the Maven project. My component jar is however present in the component Folder:

Component Folder

Can anyone advise if there is some issue with my POM or the reason behind this exception. Here is my POM.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>FileFormatConversion</groupId>
<artifactId>FileFormatConversion</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>
<name>${project.groupId}.${project.artifactId}</name>

<properties>
    <camel.version>2.18.0</camel.version>
    <import.packages>*;version="0";resolution:=optional</import.packages>
    <private.packages>!*</private.packages>
    <symbolic.name>${project.groupId}</symbolic.name>
    <embed-dep>*;scope=compile;type=!pom;inline=true</embed-dep>
    <unpack-bundle>false</unpack-bundle>
    <maven.test.skip>true</maven.test.skip>
    <maven.test.failure.ignore>true</maven.test.failure.ignore>
</properties>

<dependencies>

    <dependency>
        <groupId>com.sap.cloud.adk</groupId>
        <artifactId>com.sap.cloud.adk.build.archive</artifactId>
        <version>1.24.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-core</artifactId>
        <version>${camel.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-component</artifactId>
        <version>1.4.0</version>
    </dependency>

    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-xsd</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-xml</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-visitor</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>in.jlibs</groupId>
        <artifactId>jlibs-core</artifactId>
        <version>2.2.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache</groupId>
        <artifactId>xerces</artifactId>
        <version>2.9.0</version>
    </dependency>

    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-test</artifactId>
        <version>${camel.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.6.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <defaultGoal>install</defaultGoal>
    <plugins>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <extensions>true</extensions>
            <version>4.2.0</version>
            <inherited>true</inherited>

            <configuration>
                <excludeDependencies>true</excludeDependencies>

                <instructions>
                    <Include-Resource>src/main/resources/,lib/</Include-Resource>
                    <Bundle-SymbolicName>${symbolic.name}</Bundle-SymbolicName>
                    <Bundle-Classpath>.,jax-qname.jar,jaxmexs-0.5.jar,xsd-2.2.3.jar,jlibs-core-2.2.1.jar,jlibs-visitor-2.2.1.jar,jlibs-xml-2.2.1.jar,
                        jlibs-xsd-2.2.1.jar,xercesImpl-2.11.0.jar,xml-apis-1.4.01.jar,FileFormatConversion-1.0.0.jar
                    </Bundle-Classpath>

                    <Import-Package>${import.packages}</Import-Package>

                </instructions>
            </configuration>

        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <testFailureIgnore>true</testFailureIgnore>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.1.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/libs</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                        <excludeTransitive>true</excludeTransitive>

                        <excludeArtifactIds></excludeArtifactIds>

                        <excludeGroupIds>com.sap.cloud.adk,org.apache.camel,org.slf4j,log4j,in.jlibs,xerces,org.apache</excludeGroupIds>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>com.sap.cloud.adk</groupId>
            <artifactId>com.sap.cloud.adk.build.archive</artifactId>
            <version>1.24.0</version>
        </plugin>
    </plugins>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>com.sap.cloud.adk</groupId>
                <artifactId>com.sap.cloud.adk.build.archive</artifactId>
                <executions>
                    <execution>
                        <id>build-adapter</id>
                        <phase>install</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                        <configuration>
                            <adapterProjectDirectory>${project.basedir}</adapterProjectDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>


来源: stackexchange

问:
How to get UTC timestamp in Ruby?
How to get UTC timestamp in Ruby?</p>

答:
if you need a human-readable timestamp (like rails migration has) ex. "20190527141340"

```<code>Time.now.utc.to_formatted_s(:number)  # using Rails

Time.now.utc.strftime("%Y%m%d%H%M%S") # using Ruby
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get UTC timestamp in Ruby?

Body: How to get UTC timestamp in Ruby?

Body:
if you need a human-readable timestamp (like rails migration has) ex. "20190527141340"

Time.now.utc.to_formatted_s(:number)  # using Rails

Time.now.utc.strftime("%Y%m%d%H%M%S") # using Ruby

ContentLicense: CC BY-SA 4.0


问:
Laravel get object attribute if object id is known
How do I get the value from a object if the ID is known?

So, I got the house id, in the house model there is an user_id for every house like:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use stdClass;
use App\Service\ChangesetService;

class HouseProfile extends Model
{
    protected $guarded = ['id', 'user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
</code>```

Every user got an address (string)

I need the address and I got the house id and I'm working in a blade file in Laravel 5.5

答:
If I understand correctly:</p>

```<code>@if($house->user)
 {{ $house->user->address }}
@endif
</code>```

Body:
How do I get the value from a object if the ID is known?

So, I got the house id, in the house model there is an user_id for every house like:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use stdClass;
use App\Service\ChangesetService;

class HouseProfile extends Model
{
    protected $guarded = ['id', 'user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Every user got an address (string)

I need the address and I got the house id and I'm working in a blade file in Laravel 5.5

Body:
If I understand correctly:

@if($house->user)
 {{ $house->user->address }}
@endif


问:
Ways to circumvent the same-origin policy

The same origin policy

I wanted to make a community wiki regarding HTML/JS same-origin policies to hopefully help anyone searching for this topic. This is one of the most searched-for topics on SO and there is no consolidated wiki for it so here I go :)

The same origin policy prevents a
  document or script loaded from one
  origin from getting or setting
  properties of a document from another
  origin. This policy dates all the way
  back to Netscape Navigator 2.0.

What are some of your favorite ways to go around same-origin policies?

Please keep examples verbose and preferably also link your sources.

答:
Well, I used curl in PHP to circumvent this. I have a webservice running in port 82.

```<code><?php

$curl = curl_init();
$timeout = 30;
$ret = "";
$url="http://localhost:82/put_val?val=".$_GET["val"];
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl, CURLOPT_MAXREDIRS, 20);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$text = curl_exec($curl);
echo $text;

?>
</code>```

Here is the javascript that makes the call to the PHP file

```<code>function getdata(obj1, obj2) {

    var xmlhttp;

    if (window.XMLHttpRequest)
            xmlhttp=new XMLHttpRequest();
    else
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","phpURLFile.php?eqp="+obj1+"&val="+obj2,true);
    xmlhttp.send();
}
</code>```

My HTML runs on WAMP in port 80. So there we go, same origin policy has been circumvented :-)

ContentLicense: CC BY-SA 2.5

Body:
Well, I used curl in PHP to circumvent this. I have a webservice running in port 82.

<?php

$curl = curl_init();
$timeout = 30;
$ret = "";
$url="http://localhost:82/put_val?val=".$_GET["val"];
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl, CURLOPT_MAXREDIRS, 20);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$text = curl_exec($curl);
echo $text;

?>

Here is the javascript that makes the call to the PHP file

function getdata(obj1, obj2) {

    var xmlhttp;

    if (window.XMLHttpRequest)
            xmlhttp=new XMLHttpRequest();
    else
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","phpURLFile.php?eqp="+obj1+"&val="+obj2,true);
    xmlhttp.send();
}

My HTML runs on WAMP in port 80. So there we go, same origin policy has been circumvented :-)


问:
What does the Ellipsis object do?
While idly surfing the namespace I noticed an odd looking object called Ellipsis, it does not seem to be or do anything special, but it's a globally available builtin.

After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.

Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?

```<code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code>```

答:
This is equivalent.

```<code>l=[..., 1,2,3]
l=[Ellipsis, 1,2,3]
</code>```

... is a constant defined inside built-in constants.

Ellipsis

The same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.

Title: What does the Ellipsis object do?

Body:
While idly surfing the namespace I noticed an odd looking object called Ellipsis, it does not seem to be or do anything special, but it's a globally available builtin.

After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.

Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?

D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis

Body:
This is equivalent.

l=[..., 1,2,3]
l=[Ellipsis, 1,2,3]

... is a constant defined inside built-in constants.

Ellipsis

The same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.


问:
is there a way to prevent a form to show multiple times in #c?
so I have this program, and I want to prevent it from opening multiple times but can seem to get the hang of it =/

```<code>    private void button1_Click(object sender, EventArgs e)
    {

        if (forge.Checked)
        {
            successfully_injected openForm = new successfully_injected();
            openForm.Show();
            this.Close();
        }
        else if (!forge.Checked)
        {
            select_option openForm = new select_option();
            openForm.Show();
        }

    }
</code>```

I only want to be able to click the button once and then it stops showing more windows, but the result I get right now is that I can click it and it will just keep opening windows every time I click so yeh =/

答:
You should define your main form as a Singleton. This way there is only 1 instance that is usable throughout the entire application, thus also preventing multiple forms showing up.

A good example of this can be found in another question that's similar to yours here.

Body:
so I have this program, and I want to prevent it from opening multiple times but can seem to get the hang of it =/

    private void button1_Click(object sender, EventArgs e)
    {

        if (forge.Checked)
        {
            successfully_injected openForm = new successfully_injected();
            openForm.Show();
            this.Close();
        }
        else if (!forge.Checked)
        {
            select_option openForm = new select_option();
            openForm.Show();
        }

    }

I only want to be able to click the button once and then it stops showing more windows, but the result I get right now is that I can click it and it will just keep opening windows every time I click so yeh =/


问:
hreflang tags in DNN
I want to have hreflang tags in the source code of a website, created in DNN

I have a website that is multilingual. In order to get a correct mapping for each language a correct hreflang should be present in the head (https://support.google.com/webmasters/answer/189077?hl=en). As you can/have to appoint localized versions of the DNN to a language, I expect that the appropriate hreflang tags are placed. But in the code there is nothing.

I can not imagine that I am the first one encountering the problem. So...how did you solve it? Code or setting?

答:
Tycho,

I agree, there should be a hreflang tag, as it could be easily automated. At the moment I only see the possibility to add a page setting (Advanced :: S.E.O. :: Page header tags).

Maybe opening an issue or delivering a pull request could solve the problem - but it seems you have already done this.

Happy DNNing!

Michael

Title: hreflang tags in DNN


问:
Cannot filter Docker service names with underscore
I'd like to only show Docker services matching a certain name. As I read in the docs I can use the --filter option for that. However the result on the command is empty.

```<code>root@vm-001:~# docker service ls | grep mariadb
dou04akhbm85  develop_mariadb_demo  replicated  1/1  myimage  *:30061->3306/tcp

root@vm-001:~# docker service ls --filter name=mariadb
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
</code>```

When I run docker service ls --filter name=develop_mariadb the result is correct.

答:
The filter syntax for a name matches when a service begins with the same value. So you can run any of the following:

```<code>docker service ls --filter name=develop_mariadb
docker service ls --filter name=develop_maria
docker service ls --filter name=develop_
docker service ls --filter name=develop
docker service ls --filter name=dev
</code>```

However, the name=mariadb will not work since the service name does not begin with that string.

You can see more from this in the following issue: https://github.com/moby/moby/issues/37054

Body:
I'd like to only show Docker services matching a certain name. As I read in the docs I can use the --filter option for that. However the result on the command is empty.

root@vm-001:~# docker service ls | grep mariadb
dou04akhbm85  develop_mariadb_demo  replicated  1/1  myimage  *:30061->3306/tcp

root@vm-001:~# docker service ls --filter name=mariadb
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS

When I run docker service ls --filter name=develop_mariadb the result is correct.

Body:
The filter syntax for a name matches when a service begins with the same value. So you can run any of the following:

docker service ls --filter name=develop_mariadb
docker service ls --filter name=develop_maria
docker service ls --filter name=develop_
docker service ls --filter name=develop
docker service ls --filter name=dev

However, the name=mariadb will not work since the service name does not begin with that string.

You can see more from this in the following issue: https://github.com/moby/moby/issues/37054


问:
Catch multiple exceptions at once?
It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecessary repetitive code, for example:

```<code>try
{
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
    WebId = Guid.Empty;
}
catch (OverflowException)
{
    WebId = Guid.Empty;
}
</code>```

I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once?

The given example is rather simple, as it's only a GUID. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.

答:
I want to suggest shortest answer (one more functional style):

```<code>        Catch<FormatException, OverflowException>(() =>
            {
                WebId = new Guid(queryString["web"]);
            },
            exception =>
            {
                WebId = Guid.Empty;
            });
</code>```

For this you need to create several "Catch" method overloads, similar to System.Action:

```<code>    [DebuggerNonUserCode]
    public static void Catch<TException1, TException2>(Action tryBlock,
        Action<Exception> catchBlock)
    {
        CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));
    }

    [DebuggerNonUserCode]
    public static void Catch<TException1, TException2, TException3>(Action tryBlock,
        Action<Exception> catchBlock)
    {
        CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));
    }
</code>```

and so on as many as you wish. But you need to do it once and you can use it in all your projects (or, if you created a nuget package we could use it too).

And CatchMany implementation:

```<code>    [DebuggerNonUserCode]
    public static void CatchMany(Action tryBlock, Action<Exception> catchBlock,
        params Type[] exceptionTypes)
    {
        try
        {
            tryBlock();
        }
        catch (Exception exception)
        {
            if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);
            else throw;
        }
    }
</code>```

p.s. I haven't put null checks for code simplicity, consider to add parameter validations.

p.s.2
If you want to return a value from the catch, it's necessary to do same Catch methods, but with returns and Func instead of Action in parameters.

OwnerDisplayName: Michael Stum

Title: Catch multiple exceptions at once?

Body:
It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecessary repetitive code, for example:

try
{
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
    WebId = Guid.Empty;
}
catch (OverflowException)
{
    WebId = Guid.Empty;
}

I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once?

The given example is rather simple, as it's only a GUID. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.

LastEditorDisplayName: Michael Stum

Body:
I want to suggest shortest answer (one more functional style):

        Catch<FormatException, OverflowException>(() =>
            {
                WebId = new Guid(queryString["web"]);
            },
            exception =>
            {
                WebId = Guid.Empty;
            });

For this you need to create several "Catch" method overloads, similar to System.Action:

    [DebuggerNonUserCode]
    public static void Catch<TException1, TException2>(Action tryBlock,
        Action<Exception> catchBlock)
    {
        CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));
    }

    [DebuggerNonUserCode]
    public static void Catch<TException1, TException2, TException3>(Action tryBlock,
        Action<Exception> catchBlock)
    {
        CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));
    }

and so on as many as you wish. But you need to do it once and you can use it in all your projects (or, if you created a nuget package we could use it too).

And CatchMany implementation:

    [DebuggerNonUserCode]
    public static void CatchMany(Action tryBlock, Action<Exception> catchBlock,
        params Type[] exceptionTypes)
    {
        try
        {
            tryBlock();
        }
        catch (Exception exception)
        {
            if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);
            else throw;
        }
    }

p.s. I haven't put null checks for code simplicity, consider to add parameter validations.

p.s.2
If you want to return a value from the catch, it's necessary to do same Catch methods, but with returns and Func instead of Action in parameters.


问:
Programming In SQLITE
In college I learned PL/SQL, which I used to insert/update data into table programmatically.

So is there any way to do it in SQLITE?

I have one table book which has two columns: readPages and currentPage. readPage contains info about how many pages I've read today and currentPage shows total read pages till today.

Currently I have data for only readPages so I want to calculate currentPage for past days, e.g.

```<code>readPages:   19  10  43  20  35   # I have data for 5 days
currentPage: 19  29  72  92  127  # I want to calculate it
</code>```

So this can be easy with programming, but how to do with sqlite as it is not like plsql.

答:
The order of the rows can be determined by id or by date.

The problem with the column date is that its format: 'DD-MM' is not comparable.

Better change it to something like: 'YYYY-MM-DD'.

Since your version of SQLite does not allow you to use window functions, you can do what you need with this:

```<code>update findYourWhy
set currentPage = coalesce(
  (select sum(f.readPage) from findYourWhy f where f.id <= findYourWhy.id),
  0
);
</code>```

If you change the format of the date column, you can also do it with this:

```<code>update findYourWhy
set currentPage = coalesce(
  (select sum(f.readPage) from findYourWhy f where f.date <= findYourWhy.date),
  0
);
</code>```

See the demo.

```<code>CREATE TABLE findYourWhy (
    id  INTEGER,
    date    TEXT,
    currentPage INTEGER,
    readPage    INTEGER,
    PRIMARY KEY(id)
);
INSERT INTO findYourWhy (id,date,currentPage,readPage) VALUES
 (1,'06-05',null,36),
 (2,'07-05',null,9),
 (3,'08-05',null,12),
 (4,'09-05',null,5),
 (5,'10-05',null,12),
 (6,'11-05',null,13),
 (7,'12-05',null,2),
 (8,'13-05',null,12),
 (9,'14-05',null,3),
 (10,'15-05',null,5),
 (11,'16-05',null,6),
 (12,'17-05',null,7),
 (13,'18-05',null,7);
</code>```

Results:

```<code>| id  | date  | currentPage | readPage |
| --- | ----- | ----------- | -------- |
| 1   | 06-05 | 36          | 36       |
| 2   | 07-05 | 45          | 9        |
| 3   | 08-05 | 57          | 12       |
| 4   | 09-05 | 62          | 5        |
| 5   | 10-05 | 74          | 12       |
| 6   | 11-05 | 87          | 13       |
| 7   | 12-05 | 89          | 2        |
| 8   | 13-05 | 101         | 12       |
| 9   | 14-05 | 104         | 3        |
| 10  | 15-05 | 109         | 5        |
| 11  | 16-05 | 115         | 6        |
| 12  | 17-05 | 122         | 7        |
| 13  | 18-05 | 129         | 7        |
</code>```

Title: Programming In SQLITE

Body:
In college I learned PL/SQL, which I used to insert/update data into table programmatically.

So is there any way to do it in SQLITE?

I have one table book which has two columns: readPages and currentPage. readPage contains info about how many pages I've read today and currentPage shows total read pages till today.

Currently I have data for only readPages so I want to calculate currentPage for past days, e.g.

readPages:   19  10  43  20  35   # I have data for 5 days
currentPage: 19  29  72  92  127  # I want to calculate it

So this can be easy with programming, but how to do with sqlite as it is not like plsql.

Body:
The order of the rows can be determined by id or by date.

The problem with the column date is that its format: 'DD-MM' is not comparable.

Better change it to something like: 'YYYY-MM-DD'.

Since your version of SQLite does not allow you to use window functions, you can do what you need with this:

update findYourWhy
set currentPage = coalesce(
  (select sum(f.readPage) from findYourWhy f where f.id <= findYourWhy.id),
  0
);

If you change the format of the date column, you can also do it with this:

update findYourWhy
set currentPage = coalesce(
  (select sum(f.readPage) from findYourWhy f where f.date <= findYourWhy.date),
  0
);

See the demo.

CREATE TABLE findYourWhy (
    id  INTEGER,
    date    TEXT,
    currentPage INTEGER,
    readPage    INTEGER,
    PRIMARY KEY(id)
);
INSERT INTO findYourWhy (id,date,currentPage,readPage) VALUES
 (1,'06-05',null,36),
 (2,'07-05',null,9),
 (3,'08-05',null,12),
 (4,'09-05',null,5),
 (5,'10-05',null,12),
 (6,'11-05',null,13),
 (7,'12-05',null,2),
 (8,'13-05',null,12),
 (9,'14-05',null,3),
 (10,'15-05',null,5),
 (11,'16-05',null,6),
 (12,'17-05',null,7),
 (13,'18-05',null,7);

Results:

| id  | date  | currentPage | readPage |
| --- | ----- | ----------- | -------- |
| 1   | 06-05 | 36          | 36       |
| 2   | 07-05 | 45          | 9        |
| 3   | 08-05 | 57          | 12       |
| 4   | 09-05 | 62          | 5        |
| 5   | 10-05 | 74          | 12       |
| 6   | 11-05 | 87          | 13       |
| 7   | 12-05 | 89          | 2        |
| 8   | 13-05 | 101         | 12       |
| 9   | 14-05 | 104         | 3        |
| 10  | 15-05 | 109         | 5        |
| 11  | 16-05 | 115         | 6        |
| 12  | 17-05 | 122         | 7        |
| 13  | 18-05 | 129         | 7        |


问:
why comparing 2 equal strings(printing on screen) with strcmp function give wrong answer?
I tried to compare 2 IP Addresses stored in 2 character arrays. I get the first IP Add char array from socket and the second IP Add char array from text file. When I use strcmp function, I got a non-zero value(which means 2 strings are not equal) although when I tried to printf on the screen , they are equal.
Any idea about my prob?</p>

答:
Probably the problem is a special character like '\n', '\r', ... in your char array (from text file). Try to delete them ;-)

How to remove a carriage return from a string in C?


问:
Cordova build android Failed !!! Requirements check failed for JDK 8 ('1.8.*')! Detected version: 9.0.1 In Windows 10
My machine runs on Windows 10 64bit OS. I have properly configured the path for JAVA and Andoird, When I run "Cordova requirements" it runs without any error. After that, If I try to run Corodva build I am getting the below-mentioned error

Running command: node c:\workspace\myapp\hooks\after_prepare\010_add_platform_class.js c:\workspace\myapp

Checking Java JDK and Android SDK versions

ANDROID_SDK_ROOT=C:\Users\Admin\AppData\Local\Android\Sdk (recommended setting)

ANDROID_HOME=C:\Users\Admin\AppData\Local\Android\Sdk (DEPRECATED)

Requirements check failed for JDK 8 ('1.8.*')! Detected version: 9.0.1

Check your ANDROID_SDK_ROOT / JAVA_HOME / PATH environment variables.

$ ionic info

Ionic:

ionic (Ionic CLI) : 4.12.0 (C:\Users\Admin\AppData\Roaming\npm\node_modules\ionic)

   Ionic Framework   : ionic1 1.3.4

   @ionic/v1-toolkit : 1.0.22

Cordova:

cordova (Cordova CLI) : 9.0.0 (cordova-lib@9.0.1)

   Cordova Platforms     : android 8.0.0

   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 2.4.1, (and 5 other plugins)

System:

Android SDK Tools : 26.1.1 (C:\Users\Admin\AppData\Local\Android\Sdk)

   NodeJS            : v10.15.3 (C:\Program Files\nodejs\node.exe)

   npm               : 6.4.1

   OS                : Windows 10

$ cordova requirements

Requirements check results for android:

Java JDK: installed 9.0.1

Android SDK: installed true

Android target: installed android-28,android-27,android-26,android-25,android-24,android-23,android-22,android-21,android-19,android-18,android-17,android-16

Gradle: installed C:\Program Files\Android\Android Studio\gradle\gradle-5.1.1\bin\gradle

答: I had to install the exact version of JDK 1.8 to resolve the issue.</p>


问:
Objective C SHA512 hash of two NSData
Here is a Java code, which computes SHA512 hash of a byte array with salt:

```<code>private static String DIGEST_ALGORITHM = "SHA-512";

    public static byte[] getHash(final byte[] data, final byte[] salt) throws NoSuchAlgorithmException
{
    final MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    md.reset();
    if (salt != null)
    {
        md.update(salt);
    }
    return md.digest(data);
</code>```

In Objective C, I use this algorithm for compute the hash of an NSData:

```<code>@implementation NSData (CommonDigest)

- (NSData *) SHA512Hash {
unsigned char hash[CC_SHA512_DIGEST_LENGTH];
(void) CC_SHA512( [self bytes], (CC_LONG)[self length], hash );
return ( [NSData dataWithBytes: hash length: CC_SHA512_DIGEST_LENGTH] );
}
</code>```

This works perfectly, computes the same hash, as the Java code, if I use the same single data (i.e. the salt is nil in the Java code). The problem is that, if I want to computes hash of two NSData, i.e. there is a salt (the second parameter in the Java code is not nil). You can see that in the Java code, if the salt is not null, it performs an update, and then call the digest method. Somewhere I read that, this operation is equal with merging the two byte array (the data and salt arrays with System.arraycopy), and call the digest on the result array.
However, if I do this in Objective C (with NSMutableData appendData method), I don't get the same result. How can I fix this?
I can see in the CommonDigest class, there are similar methods, but I don't know, how can I use these...I think of these methods:

```<code>extern int CC_SHA512_Init(CC_SHA512_CTX *c);
extern int CC_SHA512_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len);
extern int CC_SHA512_Final(unsigned char *md, CC_SHA512_CTX *c);
extern unsigned char *CC_SHA512(const void *data, CC_LONG len, unsigned char *md);
</code>```

So I would like to create a method like this:

```<code>@implementation NSData (CommonDigest)

- (NSData *)SHA512HashWithSalt:(NSData *)salt {...}
</code>```

答:
I haven’t run this code and compared it with a Java implementation but it should work:</p>

```<code>@implementation NSData (CommonDigest)

- (NSData *)SHA512HashWithSalt:(NSData *)salt {
    unsigned char hash[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512_CTX context;
    CC_SHA512_Init(&context);
    if ([salt length]) {
        CC_SHA512_Update(&context, [salt bytes], (CC_LONG)[salt length]);
    }
    CC_SHA512_Update(&context, [self bytes], (CC_LONG)[self length]);
    CC_SHA512_Final(hash, &context);
    return [NSData dataWithBytes:hash length:CC_SHA512_DIGEST_LENGTH];
}

@end
</code>```

Title: Objective C SHA512 hash of two NSData

Body:
Here is a Java code, which computes SHA512 hash of a byte array with salt:

private static String DIGEST_ALGORITHM = "SHA-512";

    public static byte[] getHash(final byte[] data, final byte[] salt) throws NoSuchAlgorithmException
{
    final MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    md.reset();
    if (salt != null)
    {
        md.update(salt);
    }
    return md.digest(data);

In Objective C, I use this algorithm for compute the hash of an NSData:

@implementation NSData (CommonDigest)

- (NSData *) SHA512Hash {
unsigned char hash[CC_SHA512_DIGEST_LENGTH];
(void) CC_SHA512( [self bytes], (CC_LONG)[self length], hash );
return ( [NSData dataWithBytes: hash length: CC_SHA512_DIGEST_LENGTH] );
}

This works perfectly, computes the same hash, as the Java code, if I use the same single data (i.e. the salt is nil in the Java code). The problem is that, if I want to computes hash of two NSData, i.e. there is a salt (the second parameter in the Java code is not nil). You can see that in the Java code, if the salt is not null, it performs an update, and then call the digest method. Somewhere I read that, this operation is equal with merging the two byte array (the data and salt arrays with System.arraycopy), and call the digest on the result array.
However, if I do this in Objective C (with NSMutableData appendData method), I don't get the same result. How can I fix this?
I can see in the CommonDigest class, there are similar methods, but I don't know, how can I use these...I think of these methods:

extern int CC_SHA512_Init(CC_SHA512_CTX *c);
extern int CC_SHA512_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len);
extern int CC_SHA512_Final(unsigned char *md, CC_SHA512_CTX *c);
extern unsigned char *CC_SHA512(const void *data, CC_LONG len, unsigned char *md);

So I would like to create a method like this:

@implementation NSData (CommonDigest)

- (NSData *)SHA512HashWithSalt:(NSData *)salt {...}

Body:
I haven’t run this code and compared it with a Java implementation but it should work:

@implementation NSData (CommonDigest)

- (NSData *)SHA512HashWithSalt:(NSData *)salt {
    unsigned char hash[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512_CTX context;
    CC_SHA512_Init(&context);
    if ([salt length]) {
        CC_SHA512_Update(&context, [salt bytes], (CC_LONG)[salt length]);
    }
    CC_SHA512_Update(&context, [self bytes], (CC_LONG)[self length]);
    CC_SHA512_Final(hash, &context);
    return [NSData dataWithBytes:hash length:CC_SHA512_DIGEST_LENGTH];
}

@end


问:
Efficient way of sorting eigenvalues and eigenvectors obtained from Eigen
I am using Eigen in order to solve the eigensystem for a symmetric matrix m, an example given as follows:

```<code>#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
using namespace std;
using namespace Eigen;
int main()
{
  Matrix3f m(3,3);
  EigenSolver<Matrix3f> es;
  m(0,0) = -0.386087;
  m(1,1) = -0.390147;
  m(2,2) = 0.776234;
  m(0,1) = 0.00813956;
  m(0,2) = 0.0781361;
  m(1,0) = 0.0781361;
  m(1,2) = 0.0986476;
  m(2,0) = 0.0781361;
  m(2,1) = 0.0986476;
  es.compute(m,true);
  cout << "matrix is: " << m << endl;
  cout << "The eigenvalues of A are: " << es.eigenvalues() << endl;
  cout << "The eigenvalues of A are: " << es.eigenvectors() << endl;
}
</code>```

and the output is:

```<code>matrix is:  -0.386087 0.00813956  0.0781361
0.00813956  -0.390147  0.0986476
 0.0781361  0.0986476   0.776234
The eigenvalues of A are: (-0.391002,0)
 (0.789765,0)
(-0.398762,0)
The eigenvalues of A are:   (0.976246,0) (-0.0666485,0)   (0.206158,0)
  (0.200429,0) (-0.0835865,0)  (-0.976136,0)
  (-0.08229,0)  (-0.994269,0)  (0.0682429,0)
</code>```

Questions:

Is this an efficient use of EigenSolver knowing that my matrix is symmetric?

How could I sort the eigenvalues and accordingly the eigenvectors? (to eventually extract the max eigenval and corresponding vec) Could one do a similar construct as is common in Python?

namely:

```<code>idx = eigenValues.argsort()[::-1]
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]
</code>```

答:
Is this an efficient use of EigenSolver knowing that my matrix is symmetric?

No, you should use the SelfAdjointEigenSolver in that case:
http://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html

How could I sort the eigenvalues and accordingly the eigenvectors? (to eventually extract the max eigenval and corresponding vec) Could one do a similar construct as is common in Python?

The SelfAdjointEigenSolver already sorts the eigenvalues (from lowest to highest), i.e. to get the highest Eigenvalue/vector, you need to take the last one.

Having the eigenvalues sorted is possible here, since all eigenvalues are guaranteed to be real-valued (which is not guaranteed for the unsymmetric EigenSolver).
Another advantage is that the eigenvectors are guaranteed to form a Ortho-Normal Basis (i.e., the corresponding matrix is unitary/orthogonal).

Body:
I am using Eigen in order to solve the eigensystem for a symmetric matrix m, an example given as follows:

#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
using namespace std;
using namespace Eigen;
int main()
{
  Matrix3f m(3,3);
  EigenSolver<Matrix3f> es;
  m(0,0) = -0.386087;
  m(1,1) = -0.390147;
  m(2,2) = 0.776234;
  m(0,1) = 0.00813956;
  m(0,2) = 0.0781361;
  m(1,0) = 0.0781361;
  m(1,2) = 0.0986476;
  m(2,0) = 0.0781361;
  m(2,1) = 0.0986476;
  es.compute(m,true);
  cout << "matrix is: " << m << endl;
  cout << "The eigenvalues of A are: " << es.eigenvalues() << endl;
  cout << "The eigenvalues of A are: " << es.eigenvectors() << endl;
}

and the output is:

matrix is:  -0.386087 0.00813956  0.0781361
0.00813956  -0.390147  0.0986476
 0.0781361  0.0986476   0.776234
The eigenvalues of A are: (-0.391002,0)
 (0.789765,0)
(-0.398762,0)
The eigenvalues of A are:   (0.976246,0) (-0.0666485,0)   (0.206158,0)
  (0.200429,0) (-0.0835865,0)  (-0.976136,0)
  (-0.08229,0)  (-0.994269,0)  (0.0682429,0)

Questions:

Is this an efficient use of EigenSolver knowing that my matrix is symmetric?

How could I sort the eigenvalues and accordingly the eigenvectors? (to eventually extract the max eigenval and corresponding vec) Could one do a similar construct as is common in Python?

namely:

idx = eigenValues.argsort()[::-1]
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]


问:
@ExceptionHandler method not getting invoked when exception occurred
I have a global exception handler as below :-

```<code>@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

@ExceptionHandler(value= {HttpMessageNotReadableException.class})
    public final ResponseEntity<ErrorDetails> validationException(HttpMessageNotReadableException ex, WebRequest request) {

        System.out.println("This was called.");
        if(ex.getCause() instanceof CsvRequiredFieldEmptyException){

            CsvRequiredFieldEmptyException csvExp = (CsvRequiredFieldEmptyException) ex.getCause();
            String exceptionDtls = csvExp.getMessage().concat(" ").concat(" at line number "+csvExp.getLineNumber()+ " in the csv filw.");
            ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(),exceptionDtls, request.getDescription(false));
            return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
    }
}
</code>```

I am invoking the rest API by using TestRestTemplate for integration testing.

```<code>ResponseEntity<?> response = restTemplate.exchange(ITestUtils.createURLWithPort(postUrlCsv,
                host,port ), HttpMethod.POST,listingDocEnt, String.class);

</code>```

```<code>@Test
    public void uploadListingCsvTest_Returns400BadReq_WhenCodeMissing() throws HttpMessageNotReadableException {

        // Step 1 : Create the Http entity object which contains the request body and headers.
        HttpEntity<ListingList> listingDocEnt = new HttpEntity<ListingList>(createTestDataForNewVehicleListingCodeMissing(),
                getHttpHeaderCsv());

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

        List<HttpMessageConverter<?>> csvMessgeonverter = new ArrayList<>();
        csvMessgeonverter.add(new CsvHttpMessageConverter<>());
        csvMessgeonverter.add(converter);
        TestRestTemplate restTemplate = new TestRestTemplate();
        restTemplate.getRestTemplate().setMessageConverters(csvMessgeonverter);

        ResponseEntity<?> response = restTemplate.exchange(ITestUtils.createURLWithPort(postUrlCsv,
                host,port ), HttpMethod.POST,listingDocEnt, String.class);

        // Check if the response is not null and the http status code is - 201 Created.
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST,response.getStatusCode());

    }
</code>```

My rest API has custom HttpMessageConverter which is as below which converts the input request csv to java object in the rest controller. This custom message converter has a method readInternal which throws an exception HttpMessageNotReadableException , but still the exception handler method 'validationException' is not getting invoked. The Junit simply breaks and fails.

```<code>public class CsvHttpMessageConverter<T, L extends ListParam<T>>
          extends AbstractHttpMessageConverter<L> {

    public CsvHttpMessageConverter () {
        super(new MediaType("text", "csv"));
    }

    @Override
    protected boolean supports (Class<?> clazz) {
        return ListParam.class.isAssignableFrom(clazz);
    }

    @Override
    protected L readInternal (Class<? extends L> clazz,HttpInputMessage inputMessage)
              throws IOException, HttpMessageNotReadableException {

        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        Class<T> t = toBeanType(clazz.getGenericSuperclass());
        strategy.setType(t);

        CSVReader csv = new CSVReader(new InputStreamReader(inputMessage.getBody()));
        CsvToBean<T> csvToBean = new CsvToBean<>();

        List<T> beanList = null;

        try {
            beanList = csvToBean.parse(strategy, csv);

        } catch(Exception exception){
            throw new HttpMessageNotReadableException("Exception while parsing the CSV file.",exception.getCause());
        }

        try {
            L l = clazz.newInstance();
            l.setList(beanList);
            return l;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void writeInternal (L l, HttpOutputMessage outputMessage)
              throws IOException, HttpMessageNotWritableException {

        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(toBeanType(l.getClass().getGenericSuperclass()));

        OutputStreamWriter outputStream = new OutputStreamWriter(outputMessage.getBody());
        StatefulBeanToCsv<T> beanToCsv =
                  new StatefulBeanToCsvBuilder(outputStream)
                            .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                            .withMappingStrategy(strategy)
                            .build();

            try {
                beanToCsv.write(l.getList());
            } catch (CsvDataTypeMismatchException e) {
                throw new HttpMessageNotWritableException("Exception while parsing the CSV file.",e);
            } catch (CsvRequiredFieldEmptyException e) {
                throw new HttpMessageNotWritableException("Exception while parsing the CSV file.",e);
            }
            outputStream.close();

    }

    @SuppressWarnings("unchecked")
    private Class<T> toBeanType (Type type) {
        return (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
    }
</code>```

Is there a way that when invoking a spring rest API using TestRestTemplate we can invoke the exception handler method when there is an exception?

答:
I think the problem here is that the HttpMessageNotReadableException is not thrown by the Controller, but instead by the spring infrastructure BEFORE the controller is invoked.

But a @ControllerAdvice does only handle exceptions that are thrown by the Controller.

In spring's DispatcherServlet there is also an ErrorHandler that is invoked in such cases. Maybe this is a solution for you?

Here are some infos about this:
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc#going-deeper

Body:
I have a global exception handler as below :-

@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

@ExceptionHandler(value= {HttpMessageNotReadableException.class})
    public final ResponseEntity<ErrorDetails> validationException(HttpMessageNotReadableException ex, WebRequest request) {

        System.out.println("This was called.");
        if(ex.getCause() instanceof CsvRequiredFieldEmptyException){

            CsvRequiredFieldEmptyException csvExp = (CsvRequiredFieldEmptyException) ex.getCause();
            String exceptionDtls = csvExp.getMessage().concat(" ").concat(" at line number "+csvExp.getLineNumber()+ " in the csv filw.");
            ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(),exceptionDtls, request.getDescription(false));
            return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
    }
}

I am invoking the rest API by using TestRestTemplate for integration testing.

ResponseEntity<?> response = restTemplate.exchange(ITestUtils.createURLWithPort(postUrlCsv,
                host,port ), HttpMethod.POST,listingDocEnt, String.class);

@Test
    public void uploadListingCsvTest_Returns400BadReq_WhenCodeMissing() throws HttpMessageNotReadableException {

        // Step 1 : Create the Http entity object which contains the request body and headers.
        HttpEntity<ListingList> listingDocEnt = new HttpEntity<ListingList>(createTestDataForNewVehicleListingCodeMissing(),
                getHttpHeaderCsv());

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

        List<HttpMessageConverter<?>> csvMessgeonverter = new ArrayList<>();
        csvMessgeonverter.add(new CsvHttpMessageConverter<>());
        csvMessgeonverter.add(converter);
        TestRestTemplate restTemplate = new TestRestTemplate();
        restTemplate.getRestTemplate().setMessageConverters(csvMessgeonverter);

        ResponseEntity<?> response = restTemplate.exchange(ITestUtils.createURLWithPort(postUrlCsv,
                host,port ), HttpMethod.POST,listingDocEnt, String.class);

        // Check if the response is not null and the http status code is - 201 Created.
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST,response.getStatusCode());

    }

My rest API has custom HttpMessageConverter which is as below which converts the input request csv to java object in the rest controller. This custom message converter has a method readInternal which throws an exception HttpMessageNotReadableException , but still the exception handler method 'validationException' is not getting invoked. The Junit simply breaks and fails.

public class CsvHttpMessageConverter<T, L extends ListParam<T>>
          extends AbstractHttpMessageConverter<L> {

    public CsvHttpMessageConverter () {
        super(new MediaType("text", "csv"));
    }

    @Override
    protected boolean supports (Class<?> clazz) {
        return ListParam.class.isAssignableFrom(clazz);
    }

    @Override
    protected L readInternal (Class<? extends L> clazz,HttpInputMessage inputMessage)
              throws IOException, HttpMessageNotReadableException {

        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        Class<T> t = toBeanType(clazz.getGenericSuperclass());
        strategy.setType(t);

        CSVReader csv = new CSVReader(new InputStreamReader(inputMessage.getBody()));
        CsvToBean<T> csvToBean = new CsvToBean<>();

        List<T> beanList = null;

        try {
            beanList = csvToBean.parse(strategy, csv);

        } catch(Exception exception){
            throw new HttpMessageNotReadableException("Exception while parsing the CSV file.",exception.getCause());
        }

        try {
            L l = clazz.newInstance();
            l.setList(beanList);
            return l;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void writeInternal (L l, HttpOutputMessage outputMessage)
              throws IOException, HttpMessageNotWritableException {

        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(toBeanType(l.getClass().getGenericSuperclass()));

        OutputStreamWriter outputStream = new OutputStreamWriter(outputMessage.getBody());
        StatefulBeanToCsv<T> beanToCsv =
                  new StatefulBeanToCsvBuilder(outputStream)
                            .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                            .withMappingStrategy(strategy)
                            .build();

            try {
                beanToCsv.write(l.getList());
            } catch (CsvDataTypeMismatchException e) {
                throw new HttpMessageNotWritableException("Exception while parsing the CSV file.",e);
            } catch (CsvRequiredFieldEmptyException e) {
                throw new HttpMessageNotWritableException("Exception while parsing the CSV file.",e);
            }
            outputStream.close();

    }

    @SuppressWarnings("unchecked")
    private Class<T> toBeanType (Type type) {
        return (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
    }

Is there a way that when invoking a spring rest API using TestRestTemplate we can invoke the exception handler method when there is an exception?


问:
Pointers on how to use leaflet's polyline in reactjs & react-leaflet
I am very new to React and leaflet. I am trying to plot a set of latitudes and longitudes that is available in an object on a map in React using leaflet. Any pointers on how this can be done will be helpful.

I have gone through tutorials on react leaflet from https://react-leaflet.js.org. But I am unable to proceed. Any help is greatly appreciated. Thanks in advance.

Sample of the array of object data I have:

```<code>data=[
  {
    from_lat: "12.92415",
    from_long: "77.67229",
    id: "132512",
    to_lat: "12.92732",
    to_long: "77.63575",
  },
  {
    from_lat: "12.96691",
    from_long: "77.74935",
    id: "132513",
    to_lat: "12.92768",
    to_long: "77.62664",
  }
]
</code>```

答:
You can store the data in the state like this:

```<code>state = {
    ...
    data: [
      {
        from_lat: "12.92415",
        from_long: "77.67229",
        id: "132512",
        to_lat: "12.92732",
        to_long: "77.63575",
      },
      {
        from_lat: "12.96691",
        from_long: "77.74935",
        id: "132513",
        to_lat: "12.92768",
        to_long: "77.62664",
      }
    ]
  };
</code>```

and then iterate over data and return a Polyline instance like this:

```<code><Map
      style={{ height: "100vh" }}
      center={position}
      zoom={this.state.zoom}
    >
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      {this.state.data.map(({id, from_lat, from_long, to_lat, to_long}) => {
        return <Polyline key={id} positions={[
          [from_lat, from_long], [to_lat, to_long],
        ]} color={'red'} />
      })}
    </Map>
</code>```

Demo

Body:
I am very new to React and leaflet. I am trying to plot a set of latitudes and longitudes that is available in an object on a map in React using leaflet. Any pointers on how this can be done will be helpful.

I have gone through tutorials on react leaflet from https://react-leaflet.js.org. But I am unable to proceed. Any help is greatly appreciated. Thanks in advance.

Sample of the array of object data I have:

data=[
  {
    from_lat: "12.92415",
    from_long: "77.67229",
    id: "132512",
    to_lat: "12.92732",
    to_long: "77.63575",
  },
  {
    from_lat: "12.96691",
    from_long: "77.74935",
    id: "132513",
    to_lat: "12.92768",
    to_long: "77.62664",
  }
]

Body:
You can store the data in the state like this:

state = {
    ...
    data: [
      {
        from_lat: "12.92415",
        from_long: "77.67229",
        id: "132512",
        to_lat: "12.92732",
        to_long: "77.63575",
      },
      {
        from_lat: "12.96691",
        from_long: "77.74935",
        id: "132513",
        to_lat: "12.92768",
        to_long: "77.62664",
      }
    ]
  };

and then iterate over data and return a Polyline instance like this:

<Map
      style={{ height: "100vh" }}
      center={position}
      zoom={this.state.zoom}
    >
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      {this.state.data.map(({id, from_lat, from_long, to_lat, to_long}) => {
        return <Polyline key={id} positions={[
          [from_lat, from_long], [to_lat, to_long],
        ]} color={'red'} />
      })}
    </Map>

Demo


问:
Saving timestamp in mysql table using php
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

```<code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')
</code>```

答:
Use FROM_UNIXTIME().

Note: 1299762201428 looks more like a millisecond-timestamp (like Date()*1 in JavaScript), and you probably have to divide that by 1000.

Body:
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')


问:
Use Puppeteer to Generate a PDF on Client Side
I'm struggling to get Puppeteer to download a file within the browser. I currently have it saving the file locally on Cloud9, but I want to click a download PDF button and have it download in Chrome.

I've tried saving the page.pdf to a variable and that hasn't worked. I've also tried opening the locally saved file, but I can't get that to work either.

```<code>var express = require("express");
var puppeteer = require("puppeteer");

module.exports = function pdf(url, req) {(async () => {
      var browser = await puppeteer.launch();
      var page = await browser.newPage();
      await page.goto('https://node-and-mysql-mbegg.c9users.io/clients/'+req.params.id+'/reports/monthlyreport/'+req.params.marketplace+'/'+req.params.month, {waitUntil: 'networkidle2'});
      await page.pdf({path: 'public/temp/Performance Report -'+req.params.month+'.pdf', format: 'A4', landscape: true, printBackground: true});

      await browser.close();
    })();
}

///Print PDF route
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    pdf(url, req);
    res.contentType("application/pdf");
    res.send(pdf);;
});
</code>```

I know that the res.send(pdf) requires the page.pdf() to be saved to a variable and returned. I just didn't remove that from the route.

What happens when I save page.pdf() to a variable is I just get a blank file - not PDF - and it appears just to be a blank buffer or something. I don't know what I'm doing wrong to not get the file downloading in the chrome browser.

答:
```<code>///  Async/await
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", async function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    let pdfData = await pdf(url, req);
    res.contentType("application/pdf");
    res.send(pdfData);
});
///  promise
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", async function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    pdf(url, req).then((pdfData )=>{
        res.contentType("application/pdf");
        res.send(pdfData);
    });
});
</code>```

You were neither awaiting for the process to finish. You were also send the function, and not its result.

Body:
I'm struggling to get Puppeteer to download a file within the browser. I currently have it saving the file locally on Cloud9, but I want to click a download PDF button and have it download in Chrome.

I've tried saving the page.pdf to a variable and that hasn't worked. I've also tried opening the locally saved file, but I can't get that to work either.

var express = require("express");
var puppeteer = require("puppeteer");

module.exports = function pdf(url, req) {(async () => {
      var browser = await puppeteer.launch();
      var page = await browser.newPage();
      await page.goto('https://node-and-mysql-mbegg.c9users.io/clients/'+req.params.id+'/reports/monthlyreport/'+req.params.marketplace+'/'+req.params.month, {waitUntil: 'networkidle2'});
      await page.pdf({path: 'public/temp/Performance Report -'+req.params.month+'.pdf', format: 'A4', landscape: true, printBackground: true});

      await browser.close();
    })();
}

///Print PDF route
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    pdf(url, req);
    res.contentType("application/pdf");
    res.send(pdf);;
});

I know that the res.send(pdf) requires the page.pdf() to be saved to a variable and returned. I just didn't remove that from the route.

What happens when I save page.pdf() to a variable is I just get a blank file - not PDF - and it appears just to be a blank buffer or something. I don't know what I'm doing wrong to not get the file downloading in the chrome browser.

Body:
///  Async/await
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", async function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    let pdfData = await pdf(url, req);
    res.contentType("application/pdf");
    res.send(pdfData);
});
///  promise
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", async function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    pdf(url, req).then((pdfData )=>{
        res.contentType("application/pdf");
        res.send(pdfData);
    });
});

You were neither awaiting for the process to finish. You were also send the function, and not its result.


问:
How to reset a filter list search box?
I created a search box to filter a list following this W3Schools guideline:

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i
 -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}
#myUL li a:hover:not(.header) {
  background-color: #eee;
}</code>```

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

```
</div>
</div>
</p>

<p>I now need a button which would in one click:<br>- Reset the search box<br>- <strong>And</strong> display the full list again</p>

<p>I searched on stackoverflow and elsewhere on the internet but didn't find a solution.</p>

<p>As the code below shows, I added a reset button linked to a javascript function that was supposed to do the job. However the button only clears the search box, and although the search box appears as empty, I then need to click into the search box and push ‘delete’ once to restore the full list:</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>// CREATE A FILTER/SEARCH LIST
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

  // CLEAR SEARCH BOX
function clearInputFields(divElement) {
        var ele = document.getElementById(divElement);

        // IT WILL READ ALL THE ELEMENTS. <p>, <div>, <input> ETC.
        for (i = 0; i < ele.childNodes.length; i++) {

            // SINCE THE <input> FIELDS ARE INSIDE A <p> TAG,
            // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
            var child = ele.childNodes[i].firstChild;
            //console.log(child);

            // CHECK IF CHILD NOT NULL.
            // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
            // 'Whitespace' IS A TEXT OR NODE BETWEEN <div> AND <p> AND AFTER <p>.
            if (child) {
                switch (child.type) {
                    case 'text':
                        child.value = '';
                }
            }
        }
    }</code>```

* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>My Phonebook</h2>

<div id="searchbox">
<p><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<p/>
</div>

<ul id="myUL">
  <li>Adele</li>
  <li>Agnes</li>
  <li>Billy</li>
  <li>Bob</li>
  <li>Calvin</li>
  <li>Christina</li>
  <li>Cindy</li>
</ul>

<div id="title">
RESET
</div></code>```

Can someone please tell me what is wrong with my code or suggest a better one?

答:
You can notify the change has done by triggering keyup event using dispatchEvent()

```<code>child.dispatchEvent(new Event('keyup'));
</code>```

See Creating and triggering events.

function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

// CLEAR SEARCH BOX
function clearInputFields(divElement) {
  var ele = document.getElementById(divElement);

  // IT WILL READ ALL THE ELEMENTS.
,
, <input> ETC.
  for (i = 0; i < ele.childNodes.length; i++) {

    // SINCE THE <input> FIELDS ARE INSIDE A
 TAG,
    // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
    var child = ele.childNodes[i].firstChild;
    //console.log(child);

    // CHECK IF CHILD NOT NULL.
    // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
    // 'Whitespace' IS A TEXT OR NODE BETWEEN
 AND
 AND AFTER
.
    if (child) {
      switch (child.type) {
        case 'text':
          child.value = '';
          child.dispatchEvent(new Event('keyup'));
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px;
  /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}</code>```

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

  RESET

```

Title: How to reset a filter list search box?

Body:
I created a search box to filter a list following this W3Schools guideline:

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i
 -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}
#myUL li a:hover:not(.header) {
  background-color: #eee;
}

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

I now need a button which would in one click:
- Reset the search box
- And display the full list again

I searched on stackoverflow and elsewhere on the internet but didn't find a solution.

As the code below shows, I added a reset button linked to a javascript function that was supposed to do the job. However the button only clears the search box, and although the search box appears as empty, I then need to click into the search box and push ‘delete’ once to restore the full list:

// CREATE A FILTER/SEARCH LIST
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

  // CLEAR SEARCH BOX
function clearInputFields(divElement) {
        var ele = document.getElementById(divElement);

        // IT WILL READ ALL THE ELEMENTS.
,
, <input> ETC.
        for (i = 0; i < ele.childNodes.length; i++) {

            // SINCE THE <input> FIELDS ARE INSIDE A
 TAG,
            // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
            var child = ele.childNodes[i].firstChild;
            //console.log(child);

            // CHECK IF CHILD NOT NULL.
            // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
            // 'Whitespace' IS A TEXT OR NODE BETWEEN
 AND
 AND AFTER
.
            if (child) {
                switch (child.type) {
                    case 'text':
                        child.value = '';
                }
            }
        }
    }

* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

RESET

Can someone please tell me what is wrong with my code or suggest a better one?

Body:
You can notify the change has done by triggering keyup event using dispatchEvent()

child.dispatchEvent(new Event('keyup'));

See Creating and triggering events.

function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

// CLEAR SEARCH BOX
function clearInputFields(divElement) {
  var ele = document.getElementById(divElement);

  // IT WILL READ ALL THE ELEMENTS. <p>, <div>, <input> ETC.
  for (i = 0; i < ele.childNodes.length; i++) {

    // SINCE THE <input> FIELDS ARE INSIDE A <p> TAG,
    // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
    var child = ele.childNodes[i].firstChild;
    //console.log(child);

    // CHECK IF CHILD NOT NULL.
    // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
    // 'Whitespace' IS A TEXT OR NODE BETWEEN <div> AND <p> AND AFTER <p>.
    if (child) {
      switch (child.type) {
        case 'text':
          child.value = '';
          child.dispatchEvent(new Event('keyup'));
      }
    }
  }
}

* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px;
  /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

<h2>My Phonebook</h2>

<div id="searchbox">
  <p><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
    <p/>
</div>

<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>
  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>
  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

<div id="title">
  <a href="#216" onclick="clearInputFields('searchbox');">RESET</a>
</div>


问:
Django specify decimal places for FloatRangeField
I have a model which has FloatRangeField

```<code>class Credit(models.Model):

    interest_range = FloatRangeField('Interest', null=True, blank=True)
</code>```

And I have a model form:

```<code>class CreditForm(forms.ModelForm):

    interest_range = InclusiveFloatRangeField()
</code>```

Now, I want to specify 2 fixed decimal places (Only in UI, database check is not important)

Seems models.FloatRangeField doesn't support decimal_places. And I cant't find any example in django documentation to specify decimal places for FloatRangeField with widgets.

django version: 2.2

答:
As far as I know you can pass a fields attribute to the forms.DecimalRangeField which overrides the default base_field:

```<code>interest_range = forms.DecimalRangeField(
    fields=[forms.DecimalField(decimal_places=2, max_digits=10, required=False),
            forms.DeciamlField(decimal_places=2, max_digits=10, required=False)])

</code>```

Body:
I have a model which has FloatRangeField

class Credit(models.Model):

    interest_range = FloatRangeField('Interest', null=True, blank=True)

And I have a model form:

class CreditForm(forms.ModelForm):

    interest_range = InclusiveFloatRangeField()

Now, I want to specify 2 fixed decimal places (Only in UI, database check is not important)

Seems models.FloatRangeField doesn't support decimal_places. And I cant't find any example in django documentation to specify decimal places for FloatRangeField with widgets.

django version: 2.2

Body:
As far as I know you can pass a fields attribute to the forms.DecimalRangeField which overrides the default base_field:

interest_range = forms.DecimalRangeField(
    fields=[forms.DecimalField(decimal_places=2, max_digits=10, required=False),
            forms.DeciamlField(decimal_places=2, max_digits=10, required=False)])


答:
If you want to move the numbers to the right, you'll need to traverse the array from right to left. Also, in 2048 you'll need to move all numbers to the right after each merge.

This will work:

function solution(x) {
  for (let i = 0; i < x.length; i++) {
    for (let j = x.length - 1; j >= 0; j--) {
      if (x[i][j - 1] == x[i][j]) {
        x[i][j] = x[i][j] * 2;

        // move all numbers on the left to the right by one
        if (j > 1) {
          for (let k = j - 1; k > 0; k--) {
            x[i][k] = x[i][k - 1];
          }
        }
        x[i][0] = 0;
      }
    }
  }
  return JSON.stringify(x)
}
console.log(solution([
  [0, 0, 2, 2],
  [4, 4, 8, 4],
  [64, 64, 8, 4],
  [16, 8, 64, 8]
]));
console.log(solution([
  [2, 2, 4, 8],
  [8, 8, 64, 64],
  [64, 8, 16, 8],
  [8, 8, 8, 8]
]))
console.log(solution([
  [64, 64, 64, 64],
  [8, 8, 8, 8],
  [4, 4, 4, 4],
  [2, 2, 2, 2]
]))
console.log(solution([
  [0, 0, 4, 4],
  [4, 8, 4, 8],
  [8, 8, 8, 8],
  [64, 8, 16, 8]
]))
console.log(solution([
  [2, 0, 4, 4],
  [4, 4, 4, 4],
  [8, 0, 0, 8],
  [0, 64, 64, 64]
]))```

Title: Do only one move to right in 2048 game

Body:
I have 4x4 matrix like in game 2048, and I need to print result of one move to right. For example we have matrix:

0 0 2 2
4 4 8 4
64 64 8 4
16 8 64 8

Result is:

0 0 0 4
0 8 8 4
0 128 8 4
16 8 64 8

My code:

function solution(x){
  for (let i = 0; i < x.length; i++){
   for (let j = 0; j < x.length; j++){
     if (x[i][j] == x[i][j+1]){
        x[i][j+1] = x[i][j+1] * 2;
        x[i][j] = 0;
      }
   }
  }
  return JSON.stringify(x)
}
console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))

In the second version I get wrong result on the first row [0,0,0,16], the correct result is [0, 4, 4, 8]


答:
Use datetime field type. It comes with many advantages like human readability (nobody reads timestamps) and MySQL functions.

To convert from a unix timestamp, you can use MySQL function FROM_UNIXTIME(1299762201428). To convert back you can use UNIX_TIMESTAMP: SELECT UNIX_TIMESTAMP(t_time) FROM table_name.

Of course, if you don't like MySQL function, you could always use PHP: 'INSERT INTO table_name SET t_time = ' . date('Y-m-d H:i:s', $unix_timestamp).

Title: Saving timestamp in mysql table using php


问:
Weighted average element-wise between two arrays
I have two arrays of number and I want to compute a weighted average element-wise between these array and store it in a new array.

The solution I use for now is :

```<code>array_1 = [0,1,2,3,4]
array_2 = [2,3,4,5,6]

weight_1 = 0.5
weight_2 = 0.5

array_3 = np.zeros(array_1.shape)

for i in range(0, len(array_1)) :
    array_3[i] = np.average(a=[array_1[i], array_2[i]], weights=[weight_1, weight_2])

print(array_3)
>> [1,2,3,4,5]
</code>```

The problem is that it is not really efficient. How can I do that more efficiently ?

答:
You can zip both iterators, and multiply each element with the corresponding weight

```<code>array_1 = [0,1,2,3,4]
array_2 = [2,3,4,5,6]

weight_1 = 0.5
weight_2 = 0.5

#Zip both iterators and multiply weight with corresponding item
result = [ item1 * weight_1 + item2 * weight_2 for item1, item2 in zip(array_1, array_2)]
print(result)
</code>```

The output will be

```<code>[1.0, 2.0, 3.0, 4.0, 5.0]
</code>```

Body:
I have two arrays of number and I want to compute a weighted average element-wise between these array and store it in a new array.

The solution I use for now is :

array_1 = [0,1,2,3,4]
array_2 = [2,3,4,5,6]

weight_1 = 0.5
weight_2 = 0.5

array_3 = np.zeros(array_1.shape)

for i in range(0, len(array_1)) :
    array_3[i] = np.average(a=[array_1[i], array_2[i]], weights=[weight_1, weight_2])

print(array_3)
>> [1,2,3,4,5]

The problem is that it is not really efficient. How can I do that more efficiently ?

Body:
You can zip both iterators, and multiply each element with the corresponding weight

array_1 = [0,1,2,3,4]
array_2 = [2,3,4,5,6]

weight_1 = 0.5
weight_2 = 0.5

#Zip both iterators and multiply weight with corresponding item
result = [ item1 * weight_1 + item2 * weight_2 for item1, item2 in zip(array_1, array_2)]
print(result)

The output will be

[1.0, 2.0, 3.0, 4.0, 5.0]


答:
Given that you're using NumPy, you can easily vectorize this by doing:

```<code>array_1 = np.array([0,1,2,3,4])
array_2 = np.array([2,3,4,5,6])

weight_1 = 0.5
weight_2 = 0.5

array_1*weight_1 + array_2*weight_2
# array([1., 2., 3., 4., 5.])
</code>```

 Can this be generalised for multiple arrays and weights?

For a more generalizable answer, the best way is to use  np.average, which accepts an array_like both for the arrays and the weights to be applied to each of these:

```<code>np.average([array_1, array_2], weights=[weight_1, weight_2], axis=0)
# array([1., 2., 3., 4., 5.])
</code>```

Title: Weighted average element-wise between two arrays

Body:
Given that you're using NumPy, you can easily vectorize this by doing:

array_1 = np.array([0,1,2,3,4])
array_2 = np.array([2,3,4,5,6])

weight_1 = 0.5
weight_2 = 0.5

array_1*weight_1 + array_2*weight_2
# array([1., 2., 3., 4., 5.])

 Can this be generalised for multiple arrays and weights?

For a more generalizable answer, the best way is to use  np.average, which accepts an array_like both for the arrays and the weights to be applied to each of these:

np.average([array_1, array_2], weights=[weight_1, weight_2], axis=0)
# array([1., 2., 3., 4., 5.])


问:
Store username in database while doing rest or soap api calls from application A to application B in Java Spring 4
I have two applications, in first application say A user login by username and password. I get logged in username by using spring authentication obejct in application A. Application A is making rest or soap api calls to application B. I am passing username from A to B  application by adding username in header of rest or soap calls. Application B is making database calls, doing CRUD on SQL database. I want to save that username in updated by, modified by fields. I used bean to store username but when multiple users are using application it's getting overwritten. How this can be achieved? Thank you

In the following interceptor userSync will save my current logged in username, usernameGetter will be used to get current logged in username from http request. userSync and usernameGetter are singleton beans.

```<code>public class RequestInterceptor extends HandlerInterceptorAdapter {

private DomainUserSynchronizer userSynchronizer;

@Autowired
UsernameGetter usernameGetter;

@Autowired
private UserSynchronizer userSync;

private static final Logger LOGGER = LoggerFactory.getLogger(RequestInterceptor.class);

@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
        throws Exception {

    LOGGER.info("Inside after completion");
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {

    // do nothing

}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    HttpSession session = request.getSession();

    // Enumeration e = (Enumeration) (session.getAttributeNames());

     //session.getAttribute("an");
     //session.getAttribute("MYSPEAK_SESSION_HASH");

    String username = usernameGetter.getUsernameFromSession(request);
    if(username!=null && !username.isEmpty()){
        LOGGER.info("Found username in request: "+ username);
        LOGGER.info("Setting username in userSynchronizer: "+ username);
        userSync.getCurrentUser().setName(username);
    }
    else{
        LOGGER.info(" Username not found in request: ");
        LOGGER.info("Setting default username in userSynchronizer: "+ userSync.getCurrentUser().getName());

    }

    return true;
}

public DomainUserSynchronizer getUserSynchronizer() {
    return userSynchronizer;
}

public void setUserSynchronizer(DomainUserSynchronizer userSynchronizer) {
    this.userSynchronizer = userSynchronizer;
}
}
</code>```

答:
I guess your issue is in the scope of the beans you've declared through Spring: https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html

I would recommend you to check that all calls go through a max level of Request scope.

Another point to tackle in your issue is to confirm/rollback the transaction per each call by rest/soap you do. It could be possible that you're overwritting the entity of database without committing it.

To avoid also the overrides in the updates I would suggest to add a logging table in which you keep track of all modifications and you can only do inserts on it (immutable/audit rows)

Body:
I have two applications, in first application say A user login by username and password. I get logged in username by using spring authentication obejct in application A. Application A is making rest or soap api calls to application B. I am passing username from A to B  application by adding username in header of rest or soap calls. Application B is making database calls, doing CRUD on SQL database. I want to save that username in updated by, modified by fields. I used bean to store username but when multiple users are using application it's getting overwritten. How this can be achieved? Thank you

In the following interceptor userSync will save my current logged in username, usernameGetter will be used to get current logged in username from http request. userSync and usernameGetter are singleton beans.

public class RequestInterceptor extends HandlerInterceptorAdapter {

private DomainUserSynchronizer userSynchronizer;

@Autowired
UsernameGetter usernameGetter;

@Autowired
private UserSynchronizer userSync;

private static final Logger LOGGER = LoggerFactory.getLogger(RequestInterceptor.class);

@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
        throws Exception {

    LOGGER.info("Inside after completion");
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {

    // do nothing

}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    HttpSession session = request.getSession();

    // Enumeration e = (Enumeration) (session.getAttributeNames());

     //session.getAttribute("an");
     //session.getAttribute("MYSPEAK_SESSION_HASH");

    String username = usernameGetter.getUsernameFromSession(request);
    if(username!=null && !username.isEmpty()){
        LOGGER.info("Found username in request: "+ username);
        LOGGER.info("Setting username in userSynchronizer: "+ username);
        userSync.getCurrentUser().setName(username);
    }
    else{
        LOGGER.info(" Username not found in request: ");
        LOGGER.info("Setting default username in userSynchronizer: "+ userSync.getCurrentUser().getName());

    }

    return true;
}

public DomainUserSynchronizer getUserSynchronizer() {
    return userSynchronizer;
}

public void setUserSynchronizer(DomainUserSynchronizer userSynchronizer) {
    this.userSynchronizer = userSynchronizer;
}
}