问:
HTTP Error 415 Unsupported Media Type on REST service operation with an XML parameter (Jersey + Jetty )
I developed a REST service with Jersey and Jetty. The service has two operations:

GET on resource test

POST on resource employee which consumes an Employee instance sent as an XML

When I'm calling the test operation everything works as expected, and I see on the service output the printed message. However, when I try to invoke the POST operation I get an HTTP Error 415.

To compile the project and generate the jar file I'm using maven and this is the pom.xml file content:

<?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test.app</groupId>
    <artifactId>Service</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
        <maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
        <maven-resources-plugin.version>3.0.1</maven-resources-plugin.version>
        <maven-clean-plugin.version>3.0.0</maven-clean-plugin.version>
        <maven-war-plugin.version>3.0.0</maven-war-plugin.version>
        <tomcat7-maven-plugin.version>2.1</tomcat7-maven-plugin.version>
        <maven-jaxb2-plugin.version>0.12.1</maven-jaxb2-plugin.version>
        <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>

        <jersey.version>2.26</jersey.version>
        <jetty.version>9.4.3.v20170317</jetty.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>packaging</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <silent>true</silent>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>${maven-shade-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>${project.artifactId}</finalName>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</project>
```

<p>And these are the code of the two classes used by the service: Service (service implementation) </p>

```package com.test.app;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import org.glassfish.jersey.servlet.ServletContainer;

    @Path("/api")
    public class Service {

        @GET
        @Path("test/")
        public Response test() {
            System.out.println("test invoked");
            return Response.ok().build();
        }

        @POST
        @Path("employee/")
        @Consumes(MediaType.APPLICATION_XML)
        @Produces(MediaType.APPLICATION_XML)
        public Response getEmployee(Employee employee) {
            employee.setEmployeeName(employee.getEmployeeName() + " Welcome");
            return Response.status(Status.OK).entity(employee).build();
        }

        public static void main(String[] args) throws Exception {
            ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
            context.setContextPath("/");

            int port = 46100;
            Server jettyServer = new Server(port);
            jettyServer.setHandler(context);
            //org.eclipse.jetty.util.log.Log.getRootLogger().setDebugEnabled(true);

            ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
            jerseyServlet.setInitOrder(0);

            // Tells the Jersey Servlet which REST service/class to load.
            jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", Service.class.getCanonicalName());

            try {
                jettyServer.start();
                jettyServer.join();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                jettyServer.destroy();
            }
        }
    }
```

<p>and Employee (Object passed in as a parameter to the function)</p>

```package com.test.app;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Employee")
public class Employee {

    String employeeName;

    @XmlElement
    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}
```

<p>To verify that the operation execution works as expected, I'm running the following curl command:</p>

```curl -v -XPOST localhost:46100/api/employee -H "Content-type: application/xml" -d "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Employee>
 <employeeName>Jack</employeeName>
</Employee>"
```

And the response that I get is an HTTP Error 415.

I suspect that I'm missing some dependency on the maven file required only at runtime that contains the conversion from the XML file to the actual Employee object.

答:
There's a missconfiguration of the maven-shade plugin. Replacing it by

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>${maven-shade-plugin.version}</version>
    <configuration>
        <createDependencyReducedPom>true</createDependencyReducedPom>
        <filters>
            <filter>
                <artifact>*:*</artifact>
                <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                </excludes>
            </filter>
        </filters>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
               </transformers>
           </configuration>
       </execution>
   </executions>
</plugin>
</code>```

solves the problem

Body:
I developed a REST service with Jersey and Jetty. The service has two operations:

GET on resource test

POST on resource employee which consumes an Employee instance sent as an XML

When I'm calling the test operation everything works as expected, and I see on the service output the printed message. However, when I try to invoke the POST operation I get an HTTP Error 415.

To compile the project and generate the jar file I'm using maven and this is the pom.xml file content:

<?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test.app</groupId>
    <artifactId>Service</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
        <maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
        <maven-resources-plugin.version>3.0.1</maven-resources-plugin.version>
        <maven-clean-plugin.version>3.0.0</maven-clean-plugin.version>
        <maven-war-plugin.version>3.0.0</maven-war-plugin.version>
        <tomcat7-maven-plugin.version>2.1</tomcat7-maven-plugin.version>
        <maven-jaxb2-plugin.version>0.12.1</maven-jaxb2-plugin.version>
        <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>

        <jersey.version>2.26</jersey.version>
        <jetty.version>9.4.3.v20170317</jetty.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>packaging</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <silent>true</silent>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>${maven-shade-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>${project.artifactId}</finalName>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</project>

And these are the code of the two classes used by the service: Service (service implementation)

package com.test.app;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import org.glassfish.jersey.servlet.ServletContainer;

    @Path("/api")
    public class Service {

        @GET
        @Path("test/")
        public Response test() {
            System.out.println("test invoked");
            return Response.ok().build();
        }

        @POST
        @Path("employee/")
        @Consumes(MediaType.APPLICATION_XML)
        @Produces(MediaType.APPLICATION_XML)
        public Response getEmployee(Employee employee) {
            employee.setEmployeeName(employee.getEmployeeName() + " Welcome");
            return Response.status(Status.OK).entity(employee).build();
        }

        public static void main(String[] args) throws Exception {
            ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
            context.setContextPath("/");

            int port = 46100;
            Server jettyServer = new Server(port);
            jettyServer.setHandler(context);
            //org.eclipse.jetty.util.log.Log.getRootLogger().setDebugEnabled(true);

            ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
            jerseyServlet.setInitOrder(0);

            // Tells the Jersey Servlet which REST service/class to load.
            jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", Service.class.getCanonicalName());

            try {
                jettyServer.start();
                jettyServer.join();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                jettyServer.destroy();
            }
        }
    }

and Employee (Object passed in as a parameter to the function)

package com.test.app;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Employee")
public class Employee {

    String employeeName;

    @XmlElement
    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}

To verify that the operation execution works as expected, I'm running the following curl command:

curl -v -XPOST localhost:46100/api/employee -H "Content-type: application/xml" -d "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Employee>
 <employeeName>Jack</employeeName>
</Employee>"

And the response that I get is an HTTP Error 415.

I suspect that I'm missing some dependency on the maven file required only at runtime that contains the conversion from the XML file to the actual Employee object.

Body:
There's a missconfiguration of the maven-shade plugin. Replacing it by

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>${maven-shade-plugin.version}</version>
    <configuration>
        <createDependencyReducedPom>true</createDependencyReducedPom>
        <filters>
            <filter>
                <artifact>*:*</artifact>
                <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                </excludes>
            </filter>
        </filters>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
               </transformers>
           </configuration>
       </execution>
   </executions>
</plugin>

solves the problem


来源: stackexchange

问:
How do i make onClick and href work together?
I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

```<code><li><a href="#someSectionOfThePage" onClick={someFunction}>GO TO SECTION</a></li>
</code>```

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.

答:
The href present in the a tag is not going to work because of the onClick event. After clicking the element, instead of redirecting you to the section of the page, it executes someFunction().  You may try adding
    location.href = "#someSectionOfThePage"
to someFunction() which will do the work of href.

ContentLicense: CC BY-SA 4.0

Body:
I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

GO TO SECTION

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.


问:
How can I serialize handling of a .net web service?
I'm planning on using a .net web service to batch process database records. The web service requests are coming in from a SQL Server stored procedure that's called by SQL Server Agent every minute. I only want one batch to be running at a time because the whole point here is to avoid over loading the server.

Is there a good way of serializing the requests or maybe rejecting requests if there's already one in progress?

I was thinking of having a web service instance write a flag into the database that subsequent web service instances can read when they start up. If its already set then a web service will return without doing anything. A safe guard could be that if its been ten minutes, say, since the flag was set then the web service instance that set the flag would be considered to have failed.

Any thoughts?

Cheers, Ian.

答:
You could use a static property on the web service to set when it's running, and other instances would check it (after appropriate locking) and fail gracefully, if so. That could take into account your time out, as well.

But is there not an easier way to do this? You seem to be talking about going back and forth from database to web service and back to database again, and for something you want running every minute. Something does not seem quite right. Is there a reason you can't use a Windows service, or even the Windows Task Scheduler?

ContentLicense: CC BY-SA 3.0


问:
What is the proper name given to MySQL's Linear Hash algorithm?
https://dev.mysql.com/doc/refman/5.7/en/partitioning-linear-hash.html

I can't seem to find an equivalent on Wikipedia.

Consistent Hashing was the closest I could find.

答:
It's called 'linear hashing': https://en.wikipedia.org/wiki/Linear_hashing

It has been used since the 80s to make hash tables that rehash incrementally as they grow.


问:
Angular - Manipulate filter condition dynamically
I have 3 arrays.

```<code>    var severityFilters = ["High", "Medium", "Low"]

 var ruleFilters = ["true", "false"]

var allResults = [

{
    "name": "Test1",
    "severity": "High",
    "clean": true
},

{
    "name": "Test2",
    "severity": "Low",
    "clean": false
},

{
    "name": "Test3",
    "severity": "Medium",
    "clean": false
},

{
    "name": "Test4",
    "severity": "High",
    "clean": true
}

]
</code>```

The severityFilters array and ruleFilters are created dynamically, when user checks and unchecks some filter checkboxes. Therefore, if no severityFilters checkboxes are checked, that array would be empty. If only High is checked, then severityFilters would have High in it. Same thing with ruleFilters checkboxes.

I would like to write a function to return some filtered results, based on the values in severityFilters and ruleFilters. The filterResults function is called upon a check of each filter checkbox.

```<code>var filteredResults = []

    filterResults (severityFilters, ruleFilters, allResults)
    {
       for (let i = 0; i < allResults.length; i++) {
            if (severityFilters.length > 0 && ruleFilters.length > 0)
            {
              if (ruleFilters.includes(this.allResults[i].clean.toString()) &&
severityFilters.includes(allResults[i].severity)
              )
              {
                this.filteredResults = [...this.filteredResults, ...allResults[i]];
              }
            }
    }
    }
</code>```

This function works considering both severityFilters and ruleFilters are specified.

How can I cover checking the filtration for the following scenarios:

ruleFilters may be empty

severityFilters may be empty.

One or more severityFilters are defined, but no ruleFilters exist and vice versa.

Without writing lengthy if conditions, is there a way to tweak the function, such that the results are filtered, no matter the length of severityFilters and ruleFilters array.

答:
You could check for length of the filter arrays before checking whether they includes the property values. If severityFilters is empty, !severityFilters.length will return true. So, it won't check the second includes condition because of ||. If severityFilters does have some value, then severityFilters.includes(o.severity) will be checked and only those objects with severity value in severityFilters will be filtered

const severityFilters = ["High"]
const ruleFilters = ["true", "false"]
var allResults=[{name:"Test1",severity:"High",clean:true},{name:"Test2",severity:"Low",clean:false},{name:"Test3",severity:"Medium",clean:false},{name:"Test4",severity:"High",clean:true}];

const output = allResults.filter(o =>
  (!severityFilters.length || severityFilters.includes(o.severity)) &&
  (!ruleFilters.length || ruleFilters.includes(o.clean.toString()))
)

console.log(output)```

Body:
I have 3 arrays.

    var severityFilters = ["High", "Medium", "Low"]

 var ruleFilters = ["true", "false"]

var allResults = [

{
    "name": "Test1",
    "severity": "High",
    "clean": true
},

{
    "name": "Test2",
    "severity": "Low",
    "clean": false
},

{
    "name": "Test3",
    "severity": "Medium",
    "clean": false
},

{
    "name": "Test4",
    "severity": "High",
    "clean": true
}

]

The severityFilters array and ruleFilters are created dynamically, when user checks and unchecks some filter checkboxes. Therefore, if no severityFilters checkboxes are checked, that array would be empty. If only High is checked, then severityFilters would have High in it. Same thing with ruleFilters checkboxes.

I would like to write a function to return some filtered results, based on the values in severityFilters and ruleFilters. The filterResults function is called upon a check of each filter checkbox.

var filteredResults = []

    filterResults (severityFilters, ruleFilters, allResults)
    {
       for (let i = 0; i < allResults.length; i++) {
            if (severityFilters.length > 0 && ruleFilters.length > 0)
            {
              if (ruleFilters.includes(this.allResults[i].clean.toString()) &&
severityFilters.includes(allResults[i].severity)
              )
              {
                this.filteredResults = [...this.filteredResults, ...allResults[i]];
              }
            }
    }
    }

This function works considering both severityFilters and ruleFilters are specified.

How can I cover checking the filtration for the following scenarios:

ruleFilters may be empty

severityFilters may be empty.

One or more severityFilters are defined, but no ruleFilters exist and vice versa.

Without writing lengthy if conditions, is there a way to tweak the function, such that the results are filtered, no matter the length of severityFilters and ruleFilters array.


问:
Merge sort using two recursive functions rather than one recursive and one iterative
I've tried to use divide and conquer to create a merge sort algorithm. It is made up of a mergesort recursive function which I'm confident is correct but within it it calls a merge function, which is also recursive but isn't working. So I was wondering if anyone could help me fix this so that it works. I've seen the other solutions for defining merge using while loops etc and I get the idea there but I want to see if the merge function can be written recursively instead. </p>

<p>At the moment the when I implement the code I just get an empty array which is frustrating. </p>

```<code>def mergesort(A):
    length_A = len(A)
    if length_A > 1:
        return merge(
            mergesort(A[0:length_A//2]),
            mergesort(A[length_A//2 + 1:length_A-1]))
    else:
        return A

def merge(x,y):
    length_x = len(x)
    length_y = len(y)
    if length_x == 0:
        return x
    if length_y == 0:
        return y

    if x[0] <= y[0]:
        return x[0] + merge(x[1:length_x -1],y[0:length_y -1])
    else:
        return y[0] + merge(x[0:length_x-1],y[1:length_y -1])

A = [10, 2, 5, 3, 7, 13, 1, 6]
a = mergesort(A)
print(a)
</code>```

答:
Two things:

In the merge, if one of the lists to be merged is empty, you don't want to return that list, you want to return the other because this is the one with the remaining values. In other words, this is backward:

```<code>if length_x == 0:
    return x

if length_y == 0:
    return y
</code>```

It should be:

```<code>if length_x == 0:
    return y

if length_y == 0:
    return x
</code>```

Also you are trying to concat ints and lists with this:

```<code># x[0] is a number
return x[0] + merge(x[1:length_x -1],y[0:length_y -1])
</code>```

Something like this might be a little better:

```<code>def mergesort(A):
    length_A = len(A)
    split = length_A // 2

    if length_A > 1:
        return merge(mergesort(A[0:split]), mergesort(A[split:]))
    else:
        return A

def merge(x,y):
    if len(x) == 0:
        return y

    if len(y) == 0:
        return x

    if x[0] <= y[0]:
        return [x[0]] + merge(x[1:], y)
    else:
        return [y[0]] + merge(x, y[1:])

A = [10,2,5,3,7,13,1,6]
a = mergesort(A)
print(a)
</code>```

result

```<code>[1, 2, 3, 5, 6, 7, 10, 13]
</code>```

Body:
I've tried to use divide and conquer to create a merge sort algorithm. It is made up of a mergesort recursive function which I'm confident is correct but within it it calls a merge function, which is also recursive but isn't working. So I was wondering if anyone could help me fix this so that it works. I've seen the other solutions for defining merge using while loops etc and I get the idea there but I want to see if the merge function can be written recursively instead.

At the moment the when I implement the code I just get an empty array which is frustrating.

def mergesort(A):
    length_A = len(A)
    if length_A > 1:
        return merge(
            mergesort(A[0:length_A//2]),
            mergesort(A[length_A//2 + 1:length_A-1]))
    else:
        return A

def merge(x,y):
    length_x = len(x)
    length_y = len(y)
    if length_x == 0:
        return x
    if length_y == 0:
        return y

    if x[0] <= y[0]:
        return x[0] + merge(x[1:length_x -1],y[0:length_y -1])
    else:
        return y[0] + merge(x[0:length_x-1],y[1:length_y -1])

A = [10, 2, 5, 3, 7, 13, 1, 6]
a = mergesort(A)
print(a)

Body:
Two things:

In the merge, if one of the lists to be merged is empty, you don't want to return that list, you want to return the other because this is the one with the remaining values. In other words, this is backward:

if length_x == 0:
    return x

if length_y == 0:
    return y

It should be:

if length_x == 0:
    return y

if length_y == 0:
    return x

Also you are trying to concat ints and lists with this:

# x[0] is a number
return x[0] + merge(x[1:length_x -1],y[0:length_y -1])

Something like this might be a little better:

def mergesort(A):
    length_A = len(A)
    split = length_A // 2

    if length_A > 1:
        return merge(mergesort(A[0:split]), mergesort(A[split:]))
    else:
        return A

def merge(x,y):
    if len(x) == 0:
        return y

    if len(y) == 0:
        return x

    if x[0] <= y[0]:
        return [x[0]] + merge(x[1:], y)
    else:
        return [y[0]] + merge(x, y[1:])

A = [10,2,5,3,7,13,1,6]
a = mergesort(A)
print(a)

result

[1, 2, 3, 5, 6, 7, 10, 13]


问:
PrimeNG TurboTable sort icon not visible with default sorting enabled
When default sorting is enabled on PrimeNG's TurboTable sort icon is not visible with initial load, column header is styled as it's used and data is sorted properly. Sort icon appears when i manually click on header to sort again.

html:

```<code><p-table [columns]="columns" [value]="users" sortField="name" sortOrder="1">
  <ng-template pTemplate="header" let-columns>
    <tr>
      <th *ngFor="let col of columns" [pSortableColumn]="col.field">
        {{col.header}}
        <p-sortIcon [field]="col.field"></p-sortIcon>
      </th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-user let-columns="columns">
    // body ...
  </ng-template>
</p-table>
</code>```

component:

```<code>    this.columns = [
      {field: 'name', header: 'Name'},
      {field: 'email', header: 'email'}
    ]

</code>```

Is there any way to show sort icon on default sorted column?

答:
If you bind the sortOrder property like this...

```<code>[sortOrder]="1"
</code>```

...the value will be treated as a number rather than a string. Sometimes it's difficult to know if the string will be coerced back into a number within the PrimeNG code.

I recommend using the [brackets] for all Angular template property bindings. Otherwise, the type will be treated as a string, which may lead to bugs.

This is especially problematic with booleans, so I always recommend this syntax:

```<code>[doSomething]="false"
</code>```

And if a string is actually needed, this syntax will do the trick:

```<code>[myProp]="'myString'"
</code>```

Body:
When default sorting is enabled on PrimeNG's TurboTable sort icon is not visible with initial load, column header is styled as it's used and data is sorted properly. Sort icon appears when i manually click on header to sort again.

html:

  <ng-template pTemplate="header" let-columns>

        {{col.header}}

  </ng-template>
  <ng-template pTemplate="body" let-user let-columns="columns">
    // body ...
  </ng-template>

component:

    this.columns = [
      {field: 'name', header: 'Name'},
      {field: 'email', header: 'email'}
    ]

Is there any way to show sort icon on default sorted column?

Body:
If you bind the sortOrder property like this...

[sortOrder]="1"

...the value will be treated as a number rather than a string. Sometimes it's difficult to know if the string will be coerced back into a number within the PrimeNG code.

I recommend using the [brackets] for all Angular template property bindings. Otherwise, the type will be treated as a string, which may lead to bugs.

This is especially problematic with booleans, so I always recommend this syntax:

[doSomething]="false"

And if a string is actually needed, this syntax will do the trick:

[myProp]="'myString'"


问:
How to implement debounce in Vue2?
I have a simple input box in a Vue template and I would like to use debounce more or less like this:

<input type="text" v-model="filterKey" debounce="500">
```
<p>However the <code>debounce</code> property has been deprecated in Vue 2. The recommendation only says: "use v-on:input + 3rd party debounce function".</p>
<p>How do you correctly implement it?</p>
<p>I've tried to implement it using <strong>lodash</strong>, <strong>v-on:input</strong> and <strong>v-model</strong>, but I am wondering if it is possible to do without the extra variable.</p>
<p><strong>In template:</strong></p>
<pre class="lang-html prettyprint-override"><code><input type="text" v-on:input="debounceInput" v-model="searchInput">
</code>```

In script:

data: function () {
  return {
    searchInput: '',
    filterKey: ''
  }
},

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}
```

The filterkey is then used later in computed props.

Title: How to implement debounce in Vue2?

Body:
I have a simple input box in a Vue template and I would like to use debounce more or less like this:

<input type="text" v-model="filterKey" debounce="500">

However the debounce property has been deprecated in Vue 2. The recommendation only says: "use v-on:input + 3rd party debounce function".

How do you correctly implement it?

I've tried to implement it using lodash, v-on:input and v-model, but I am wondering if it is possible to do without the extra variable.

In template:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

In script:

data: function () {
  return {
    searchInput: '',
    filterKey: ''
  }
},

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

The filterkey is then used later in computed props.

Body:
If you are using Vue you can also use v.model.lazy instead of debounce but remember v.model.lazy will not always work as Vue limits it for custom components.

For custom components you should use :value along with @change.native

<b-input :value="data" @change.native="data = $event.target.value" ></b-input>


问:
Searching XML through Java Codes
I have around 30 xml files with proper formatting  and huge amount of data. I want to search these xml files for specific data retrival. Can you suggest any site or blog which i can use as aguideline to solve my problem.

I need to search inside of each tag for the keyword provided by the user. And also sometime the specific tag name which will return the content inside the tag according to the user request.

example : a.xml, b.xml, c.xml

```<code>inside a.xml

<abc>
some content
</abc>
</code>```

User may search for abc the tag or some keyword inside the content. In both cases it should return the content or if more than one match then it should return the link for both by clicking which the user can see them one by one.

答:
Use a SAX parser (no need to go back and forth within the documents plus huge amount of data hence don't use a DOM parser).

See this link for a tutorial.

Title: Searching XML through Java Codes

Body:
I have around 30 xml files with proper formatting  and huge amount of data. I want to search these xml files for specific data retrival. Can you suggest any site or blog which i can use as aguideline to solve my problem.

I need to search inside of each tag for the keyword provided by the user. And also sometime the specific tag name which will return the content inside the tag according to the user request.

example : a.xml, b.xml, c.xml

inside a.xml

<abc>
some content
</abc>

User may search for abc the tag or some keyword inside the content. In both cases it should return the content or if more than one match then it should return the link for both by clicking which the user can see them one by one.


问:
How to avoid PyCharm console crash "WARNING: QApplication was not created in the main() thread" when plotting with matplotlib?
In PyCharm, when I try to plot something using its interactive console, such as:

```<code>In[2]: from matplotlib.pyplot import *
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[5]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[6]: show()
</code>```

It opens a window and crashes. I have to stop the console and start a new one.

It works fine when I run anything like that in an ipython console in my terminal, the error happens only in Pycharm, it seems.

On the other hand, if import matplotlib with import matplotlib.pyplot as plt it works fine:

```<code>In[2]: import matplotlib.pyplot as plt
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plt.plot(x,y)
Out[5]: [<matplotlib.lines.Line2D at 0x7fd3453b72e8>]
In[6]: plt.show()
</code>```

But if I do both, it crashes too (even calling the plot function using plt.plot):

```<code>In[2]: from matplotlib.pyplot import *
In[3]: import matplotlib.pyplot as plt
In[4]: x = range(5)
In[5]: y = range(5,10)
In[6]: plt.plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[6]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[7]: plt.show()
</code>```

Furthermore, when I run it all in one command, it works the first time. But if I try to plot another time, it crashes:

```<code>In[2]: from matplotlib.pyplot import *
  ...: x = range(5)
  ...: y = range(5,10)
  ...: plot(x,y)
  ...: show()
In[3]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[3]: [<matplotlib.lines.Line2D at 0x7fc68a3009e8>]
In[4]: show()
</code>```

So it is something related with using the matplotlib library with the import using * and with running in the interactive console after the first time it was imported. I know the wildcard import is not recommended, but sometimes it is useful to do it for a sake of testing things faster and being less verbose.

Looking for this warning online, I have only found these

https://github.com/matplotlib/matplotlib/issues/13296
But my case doesn't seem to be related to multiprocessing. And even if pycharm is doing something behind the scenes, I wonder why it has changed, as I had no problems with this like a month ago;

Suppress warning "QApplication was not created in main() thread"
and other posts related to C++, which is not my case;

WARNING: QApplication was not created in main() thread -> related to pycharm, but has an additional error different than mine

Which didn't help much. Anyone knows what is happening and how to solve it?

SPECS:

PyCharm 2019.1.2 (Professional Edition)

Build #PY-191.7141.48, built on May 7, 2019

JRE: 11.0.2+9-b159.56 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Linux 4.15.0-50-generic

conda 4.6.14, with Python 3.7.3

Qt5

答:
I sent this question to JetBrains: https://youtrack.jetbrains.com/issue/PY-36136

They couldn't find a solution yet, but the workaround they suggested is the following:

Disable Show plots in tool window in File | Settings | Tools | Python Scientific.

This worked for me, although it doesn't plot in the PyCharm window.

Body:
In PyCharm, when I try to plot something using its interactive console, such as:

In[2]: from matplotlib.pyplot import *
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[5]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[6]: show()

It opens a window and crashes. I have to stop the console and start a new one.

It works fine when I run anything like that in an ipython console in my terminal, the error happens only in Pycharm, it seems.

On the other hand, if import matplotlib with import matplotlib.pyplot as plt it works fine:

In[2]: import matplotlib.pyplot as plt
In[3]: x = range(5)
In[4]: y = range(5,10)
In[5]: plt.plot(x,y)
Out[5]: [<matplotlib.lines.Line2D at 0x7fd3453b72e8>]
In[6]: plt.show()

But if I do both, it crashes too (even calling the plot function using plt.plot):

In[2]: from matplotlib.pyplot import *
In[3]: import matplotlib.pyplot as plt
In[4]: x = range(5)
In[5]: y = range(5,10)
In[6]: plt.plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[6]: [<matplotlib.lines.Line2D at 0x7fade916a438>]
In[7]: plt.show()

Furthermore, when I run it all in one command, it works the first time. But if I try to plot another time, it crashes:

In[2]: from matplotlib.pyplot import *
  ...: x = range(5)
  ...: y = range(5,10)
  ...: plot(x,y)
  ...: show()
In[3]: plot(x,y)
WARNING: QApplication was not created in the main() thread.
Out[3]: [<matplotlib.lines.Line2D at 0x7fc68a3009e8>]
In[4]: show()

So it is something related with using the matplotlib library with the import using * and with running in the interactive console after the first time it was imported. I know the wildcard import is not recommended, but sometimes it is useful to do it for a sake of testing things faster and being less verbose.

Looking for this warning online, I have only found these

https://github.com/matplotlib/matplotlib/issues/13296
But my case doesn't seem to be related to multiprocessing. And even if pycharm is doing something behind the scenes, I wonder why it has changed, as I had no problems with this like a month ago;

Suppress warning "QApplication was not created in main() thread"
and other posts related to C++, which is not my case;

WARNING: QApplication was not created in main() thread -> related to pycharm, but has an additional error different than mine

Which didn't help much. Anyone knows what is happening and how to solve it?

SPECS:

PyCharm 2019.1.2 (Professional Edition)

Build #PY-191.7141.48, built on May 7, 2019

JRE: 11.0.2+9-b159.56 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Linux 4.15.0-50-generic

conda 4.6.14, with Python 3.7.3

Qt5


问:
how to remember inputs value by using local storage?
I have tried to use local storage to remember the input's value after refreshing page. but my code does not work.

here is the HTML code

```<code><input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>
</code>```

and here is javascript

```<code><script type="text/javascript">
var nameArr = ["name"];
var inputs = document.getElementsByName('name');
inputs.forEach(function(el){
    el.value = getSavedValue(el);
})

function saveValue(e) {
  var name = e.target.name;
  var val = e.target.value;
  localStorage.setItem(name, val);
}

function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return "";
  }
  return localStorage.getItem(v);
}
</script>
</code>```

if there is a way to solve this problem please tell me.
and if there is a way to do that with jquery I will be thankful to tell me that.

答:
Here are couple of things. First instead of onkeyup use onblur so value will be saved in storage only when the focus is removed from the element.

Secondly use a common class inputs in this case and give separate name to each element.

Then get all the elements with same class, iterate through it and get value of  name property using getAttribute. Use this value to check if there exist a key in localStorage

var nameArr = ["name"];
var inputs = [...document.getElementsByClassName('inputs')];
inputs.forEach(function(el) {
  console.log()
  el.value = getSavedValue(el.getAttribute('name'));
})

function saveValue(e) {
  var name = e.target.name;
  var val = e.target.value;
  localStorage.setItem(name, val);
}

function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return "";
  }
  return localStorage.getItem(v);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class='inputs' name="firstName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="lastName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="age" onblur="saveValue(event)" /></code>```

Body:
I have tried to use local storage to remember the input's value after refreshing page. but my code does not work.

here is the HTML code

<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>

and here is javascript

if there is a way to solve this problem please tell me.
and if there is a way to do that with jquery I will be thankful to tell me that.

Body:
Here are couple of things. First instead of onkeyup use onblur so value will be saved in storage only when the focus is removed from the element.

Secondly use a common class inputs in this case and give separate name to each element.

Then get all the elements with same class, iterate through it and get value of  name property using getAttribute. Use this value to check if there exist a key in localStorage

var nameArr = ["name"];
var inputs = [...document.getElementsByClassName('inputs')];
inputs.forEach(function(el) {
  console.log()
  el.value = getSavedValue(el.getAttribute('name'));
})

function saveValue(e) {
  var name = e.target.name;
  var val = e.target.value;
  localStorage.setItem(name, val);
}

function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return "";
  }
  return localStorage.getItem(v);
}

<input type="text" class='inputs' name="firstName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="lastName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="age" onblur="saveValue(event)" />


问:
Laravel Carbon date diffInDays() on string error
I need to find the difference between the two dates.  Say i have 2017-02-01 - 2017-01-01.  The number of days between the two days is the output

```<code>$formatted_dt1=Carbon::parse($a->date)->format('Y-m-d');
$formatted_dt2=Carbon::parse($c->dt)->format('Y-m-d');
$date_diff=$formatted_dt1->diffInDays($formatted_dt2);
</code>```

If I give the above code I get the error as

```<code>FatalThrowableError in ReportsController.php line 67:
Call to a member function diffInDays() on string
</code>```

答:
You are having this problem because you stored your date as string in the database. You can perform diffInDays($updated_at) or diffInDays($created_at) on the original laravel's created_at and updated_at because Laravel already stores them as dates by default so, when you are fetching them from the database, laravel gives it to you as a carborn instance (try dd($created_at)).

To solve your problem, go to your model and use this to convert your date column to dates

```<code>protected $dates = [
'my_date',
'my_other_date'
]
</code>```

Then, you can now do

```<code>$formatted_dt1=Carbon::parse($a->date)->format('Y-m-d');
$formatted_dt2=Carbon::parse($c->dt)->format('Y-m-d');
$date_diff=$formatted_dt1->diffInDays($formatted_dt2);
</code>```

OR You can use

```<code>Carbon\Carbon::parse($formatted_dt1)->diffInDays()
</code>```

Body:
I need to find the difference between the two dates.  Say i have 2017-02-01 - 2017-01-01.  The number of days between the two days is the output

$formatted_dt1=Carbon::parse($a->date)->format('Y-m-d');
$formatted_dt2=Carbon::parse($c->dt)->format('Y-m-d');
$date_diff=$formatted_dt1->diffInDays($formatted_dt2);

If I give the above code I get the error as

FatalThrowableError in ReportsController.php line 67:
Call to a member function diffInDays() on string

Body:
You are having this problem because you stored your date as string in the database. You can perform diffInDays($updated_at) or diffInDays($created_at) on the original laravel's created_at and updated_at because Laravel already stores them as dates by default so, when you are fetching them from the database, laravel gives it to you as a carborn instance (try dd($created_at)).

To solve your problem, go to your model and use this to convert your date column to dates

protected $dates = [
'my_date',
'my_other_date'
]

Then, you can now do

$formatted_dt1=Carbon::parse($a->date)->format('Y-m-d');
$formatted_dt2=Carbon::parse($c->dt)->format('Y-m-d');
$date_diff=$formatted_dt1->diffInDays($formatted_dt2);

OR You can use

Carbon\Carbon::parse($formatted_dt1)->diffInDays()


问:
Kafka consumers unable to send heartbeat but receives messages
I'm using a Kafka Cluster from Bitnami on Azure (https://bitnami.com/stack/kafka/cloud/azure). It is a single node cluster with broker on one VM and Zookeeper on another. I have enabled the ports 9090 and 2181.

I have .Net Core WebApps running on azure with Confluent .NET Client (v1.0.0) for Kafka. The WebApps have producers and consumers configured.

The problem I'm facing is, soon after starting the web app, the consumer fails due to heartbeat expiration. But it is able to receive some messages from the producer in the meanwhile. Even if I simply start one Consumer only, it automatically fails after SessionTimeoutMs due to heartbeat expiration.

I'm unable to understand why the heartbeat expires (while messages are being received by the consumer). Does it happen on a separate port? If I set the SessionTimeoutMs = 300000 (max), it expires after exactly 5 minutes.

Server log (when I add a consumer in a WebApp - notice that the heartbeat expires within 16 seconds):

```<code>[2019-05-22 17:57:42,302] INFO [GroupCoordinator 1001]: Preparing to rebalance group test-consumer-group-new2 in state PreparingRebalance with old generation 4 (__consumer_offsets-40) (reason: Adding new member rdkafka-03f8db78-4f74-4cb2-9389-bb949c53281c) (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:42,303] INFO [GroupCoordinator 1001]: Stabilized group test-consumer-group-new2 generation 5 (__consumer_offsets-40) (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:42,349] INFO [GroupCoordinator 1001]: Assignment received from leader for group test-consumer-group-new2 for generation 5 (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:58,403] INFO [GroupCoordinator 1001]: Member rdkafka-03f8db78-4f74-4cb2-9389-bb949c53281c in group test-consumer-group-new2 has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:58,403] INFO [GroupCoordinator 1001]: Preparing to rebalance group test-consumer-group-new2 in state PreparingRebalance with old generation 5 (__consumer_offsets-40) (reason: removing member rdkafka-03f8db78-4f74-4cb2-9389-bb949c53281c on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:58,404] INFO [GroupCoordinator 1001]: Group test-consumer-group-new2 with generation 6 is now empty (__consumer_offsets-40) (kafka.coordinator.group.GroupCoordinator)
</code>```

My server.properties:

```<code>listeners=PLAINTEXT://:9092
advertised.listeners=PLAINTEXT://40.X.X.X:9092
</code>```

The consumer's config:

```<code>var conf = new ConsumerConfig
{
    GroupId = "test-consumer-group-new2",
    BootstrapServers = "40.X.X.X:9092",
    SecurityProtocol = SecurityProtocol.Plaintext,
    SaslMechanism = SaslMechanism.Plain,
    SaslUsername = "user",
    SaslPassword = "<passowrd>"
}
</code>```

I also do not understand the old/new Generations in Kafka and could not find documentation on the same. Can anyone please shed some light on it? Thanks.

答:
max.poll.records - may need to be reduced;

pay attention for heartbeat.interval.ms - the value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value

Body:
I'm using a Kafka Cluster from Bitnami on Azure (https://bitnami.com/stack/kafka/cloud/azure). It is a single node cluster with broker on one VM and Zookeeper on another. I have enabled the ports 9090 and 2181.

I have .Net Core WebApps running on azure with Confluent .NET Client (v1.0.0) for Kafka. The WebApps have producers and consumers configured.

The problem I'm facing is, soon after starting the web app, the consumer fails due to heartbeat expiration. But it is able to receive some messages from the producer in the meanwhile. Even if I simply start one Consumer only, it automatically fails after SessionTimeoutMs due to heartbeat expiration.

I'm unable to understand why the heartbeat expires (while messages are being received by the consumer). Does it happen on a separate port? If I set the SessionTimeoutMs = 300000 (max), it expires after exactly 5 minutes.

Server log (when I add a consumer in a WebApp - notice that the heartbeat expires within 16 seconds):

[2019-05-22 17:57:42,302] INFO [GroupCoordinator 1001]: Preparing to rebalance group test-consumer-group-new2 in state PreparingRebalance with old generation 4 (__consumer_offsets-40) (reason: Adding new member rdkafka-03f8db78-4f74-4cb2-9389-bb949c53281c) (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:42,303] INFO [GroupCoordinator 1001]: Stabilized group test-consumer-group-new2 generation 5 (__consumer_offsets-40) (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:42,349] INFO [GroupCoordinator 1001]: Assignment received from leader for group test-consumer-group-new2 for generation 5 (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:58,403] INFO [GroupCoordinator 1001]: Member rdkafka-03f8db78-4f74-4cb2-9389-bb949c53281c in group test-consumer-group-new2 has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:58,403] INFO [GroupCoordinator 1001]: Preparing to rebalance group test-consumer-group-new2 in state PreparingRebalance with old generation 5 (__consumer_offsets-40) (reason: removing member rdkafka-03f8db78-4f74-4cb2-9389-bb949c53281c on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
[2019-05-22 17:57:58,404] INFO [GroupCoordinator 1001]: Group test-consumer-group-new2 with generation 6 is now empty (__consumer_offsets-40) (kafka.coordinator.group.GroupCoordinator)

My server.properties:

listeners=PLAINTEXT://:9092
advertised.listeners=PLAINTEXT://40.X.X.X:9092

The consumer's config:

var conf = new ConsumerConfig
{
    GroupId = "test-consumer-group-new2",
    BootstrapServers = "40.X.X.X:9092",
    SecurityProtocol = SecurityProtocol.Plaintext,
    SaslMechanism = SaslMechanism.Plain,
    SaslUsername = "user",
    SaslPassword = "<passowrd>"
}

I also do not understand the old/new Generations in Kafka and could not find documentation on the same. Can anyone please shed some light on it? Thanks.


问:
Loader for a specific section in HTML
I am kind of newbie in website development, so kind of confused with the behavior of web page.
I want to use loader to hide the image loading in the HTML. In index page I have used tabs view to show the product category and in every category, images are shown. So loading images is taking time and at first it shows all the product images of all categories which is not acceptable. I am talking about a section that is after slider.

```<code>                <ul class="nav nav-pills sort-source sort-source-style-3 justify-content-center" data-sort-id="portfolio" data-option-key="filter" data-plugin-options="{'layoutMode': 'fitRows', 'filter': '.custom'}">
                    <li class="nav-item active" data-option-value=".custom"><a class="nav-link text-1 text-uppercase active" href="#">Custom Point of Sale Displays</a></li>
                    <li class="nav-item" data-option-value=".wide-format"><a class="nav-link text-1 text-uppercase" href="#">Wide Format printing</a></li>
                    <li class="nav-item" data-option-value=".digital"><a class="nav-link text-1 text-uppercase" href="#">Digital small Format</a></li>
                    <li class="nav-item" data-option-value=".mailing"><a class="nav-link text-1 text-uppercase" href="#">Mailing</a></li>
                    <li class="nav-item" data-option-value=".kitting"><a class="nav-link text-1 text-uppercase" href="#">Kitting & Distribution with Online Tracking</a></li>
                    </ul>

                <div class="sort-destination-loader sort-destination-loader-showing mt-4 pt-2">
                    <div  class="row portfolio-list sort-destination lightbox" data-sort-id="portfolio" data-plugin-options="{'delegate': 'a.lightbox-portfolio', 'type': 'image', 'gallery': {'enabled': true}}">
                        <!-- custom point of sales display-->
                        <div class="col-sm-6 col-lg-3 isotope-item custom">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/custom1.png" class="img-fluid border-radius-0" alt="">
                                        <!-- <span class=" thumb-info-title thumb-info line-height-1">Project Title</span>   -->
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/custom1.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item custom">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/custom2.png" class="img-fluid border-radius-0" alt="">
                                        <!-- <span class=" thumb-info-title thumb-info line-height-1">Project Title</span> -->
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/custom2.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <!-- custom displays end-->
                        <!-- wide format starts-->
                        <div class="col-sm-6 col-lg-3 isotope-item wide-format">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/corflutes.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Corflute Signs</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/corflutes.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item wide-format">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/screenboard.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Screen Board Signs</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/screenboard.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item wide-format">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/economy.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Economy Pull Up Banners</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/economy.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>

                        <!-- wide format ends-->

                        <!-- digital small format-->
                        <div class="col-sm-6 col-lg-3 isotope-item digital">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/doorhangers.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Door Hangers</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/doorhangers.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item digital">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/businesscards.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Business Cards</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/businesscards.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item digital">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/flyers.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Flyers</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/flyers.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <!-- digital displays end-->

                        <!-- mailing -->
                        <div class="col-sm-6 col-lg-3 isotope-item mailing">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/mailing.png" class="img-fluid border-radius-0" alt="">
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/mailing.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item mailing">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/mailing2.png" class="img-fluid border-radius-0" alt="">
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/mailing2.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <!-- mailing ends-->

                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</code>```

答: while browsing your website from my computer, it seems to me you everything is ok according to your issue. It may happen for my fast internet. The loading time of your website can't take extra time in my computer. By the way, I can suggest you wrap hole body tag under a div. After then add a unique id with your wrap div. Afterwards, just apply some jquery code against id when all document load properly. Let me know, yet you can't finish the issue.  </p>

Title: Loader for a specific section in HTML

Body:
I am kind of newbie in website development, so kind of confused with the behavior of web page.
I want to use loader to hide the image loading in the HTML. In index page I have used tabs view to show the product category and in every category, images are shown. So loading images is taking time and at first it shows all the product images of all categories which is not acceptable. I am talking about a section that is after slider.

Custom Point of Sale Displays

Wide Format printing

Digital small Format

Mailing

Kitting & Distribution with Online Tracking

                                        Corflute Signs

                                        Screen Board Signs

                                        Economy Pull Up Banners

                                        Door Hangers

                                        Business Cards

                                        Flyers


问:
CSS precedence rules
My understanding is that there are 3 types of stylesheet:

Defined by the page author

Defined by the user (i.e. a set of default styles defined by the user and installed into their browser)

Default stylesheet defined by the browser

According to this book if an element is not matched by a selector in any of these stylesheets, only then will the property value be inherited from parent elements. However, the book also says that a browser's default stylesheet should define a style for all types of elements.

If a browser's stylesheet does define a style for all types of element, and this style has a higher precendence than inheritance, then inherited property values should never be observed. Clearly this is not the case, so what exactly are the correct precedence rules for properties defined in a browser's default stylesheet and those defined for parent elements? (I'm aware that not all CSS properties inherited, but for the sake of this discussion assume I'm referring to a property that is, e.g. color)

Thanks in advance,
Don

答:
You may want to look into "Specificity" also

http://htmldog.com/guides/cssadvanced/specificity/

OwnerDisplayName: Don

ContentLicense: CC BY-SA 2.5

Title: CSS precedence rules

OwnerDisplayName: Andy Johnston


问:
how to add custom color to flutter?
I want to change the color of AppBar and use a custom color for it, I tried many options but none seem to work.
Is there anything I'm missing?

```<code>import 'package:flutter/material.dart';

final ThemeData CompanyThemeData = new ThemeData(
  brightness: Brightness.light,
  primaryColorBrightness: Brightness.light,
  accentColor: CompanyColors.black[500],
  accentColorBrightness: Brightness.light
);

class CompanyColors {
  CompanyColors._(); // this basically makes it so you can instantiate this class

 static const _blackPrimaryValue = 0xFF000000;

  static const MaterialColor black = const MaterialColor(
    _blackPrimaryValue,
    const <int, Color>{
      50:  const Color(0xFFe0e0e0),
      100: const Color(0xFFb3b3b3),
      200: const Color(0xFF808080),
      300: const Color(0xFF4d4d4d),
      400: const Color(0xFF262626),
      500: const Color(_blackPrimaryValue),
      600: const Color(0xFF000000),
      700: const Color(0xFF000000),
      800: const Color(0xFF000000),
      900: const Color(0xFF000000),
    },
  );
}
</code>```

and then I have used it in main.dart as

```<code>Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch:Theme1.CompanyColors.black[50],
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
</code>```

but after execution it says

type Color is not of subtype MaterialColor

答:
It's a MaterialColor object (not Color) you should assign for a swatch property, providing color values for the ten different luminances.

Many people suggested adjusting the alpha/opacity value of the colors used in the MaterialColor. It's actually a big mistake because it will result in making your element translucent without providing color variety of different shades.

Please consider using this solution for a better approach.

Flutter: Creating a custom color swatch for MaterialColor

MaterialColor createMaterialColor(Color color) {
  List strengths = <double>[.05];
  final swatch = <int, Color>{};
  final int r = color.red, g = color.green, b = color.blue;

  for (int i = 1; i < 10; i++) {
    strengths.add(0.1 * i);
  }
  strengths.forEach((strength) {
    final double ds = 0.5 - strength;
    swatch[(strength * 1000).round()] = Color.fromRGBO(
      r + ((ds < 0 ? r : (255 - r)) * ds).round(),
      g + ((ds < 0 ? g : (255 - g)) * ds).round(),
      b + ((ds < 0 ? b : (255 - b)) * ds).round(),
      1,
    );
  });
  return MaterialColor(color.value, swatch);
}
```

Title: how to add custom color to flutter?

Body:
I want to change the color of AppBar and use a custom color for it, I tried many options but none seem to work.
Is there anything I'm missing?

import 'package:flutter/material.dart';

final ThemeData CompanyThemeData = new ThemeData(
  brightness: Brightness.light,
  primaryColorBrightness: Brightness.light,
  accentColor: CompanyColors.black[500],
  accentColorBrightness: Brightness.light
);

class CompanyColors {
  CompanyColors._(); // this basically makes it so you can instantiate this class

 static const _blackPrimaryValue = 0xFF000000;

  static const MaterialColor black = const MaterialColor(
    _blackPrimaryValue,
    const <int, Color>{
      50:  const Color(0xFFe0e0e0),
      100: const Color(0xFFb3b3b3),
      200: const Color(0xFF808080),
      300: const Color(0xFF4d4d4d),
      400: const Color(0xFF262626),
      500: const Color(_blackPrimaryValue),
      600: const Color(0xFF000000),
      700: const Color(0xFF000000),
      800: const Color(0xFF000000),
      900: const Color(0xFF000000),
    },
  );
}

and then I have used it in main.dart as

Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch:Theme1.CompanyColors.black[50],
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }

but after execution it says

type Color is not of subtype MaterialColor


问:
Adding types when using tfjs-node
I would like to install the types when using tensorflow/tfjs-node as I'm using Typescript.

I installed it via npm install @tensorflow/tfjs-node

But non of them are working to install the typings:

```<code>npm install --save @types/tensorflow/tfjs-node
npm install --save @types/tfjs-node
</code>```

答:
You don't need to install the types separately as they come already bundled with the main repository.

To remove the old typings from @types/... use npm uninstall. After that, When using TypeScript and importing the data via import it should automatically pick up the correct types.

Title: Adding types when using tfjs-node

Body:
I would like to install the types when using tensorflow/tfjs-node as I'm using Typescript.

I installed it via npm install @tensorflow/tfjs-node

But non of them are working to install the typings:

npm install --save @types/tensorflow/tfjs-node
npm install --save @types/tfjs-node


问:
Get the first unique element from the array
I was solving the problem on LeetCode. i.e Single Number.

You need to create a function which takes a array as input and return the only element which is not repeated in array. The array will contain only one element like that.

```<code>[2,2,1] //1
[2,3,5,2,3] //5
</code>```

I have solved the problem with the code below.

```<code>var singleNumber = function(nums) {
    let obj = {}
    for(let a of nums){
        obj[a] = obj[a] + 1 || 1;
    }
    for(let key in obj){
        if(obj[key] === 1) return key;
    }
};
</code>```

However after submitting the result it says

Runtime: 68 ms, faster than 72.96% of JavaScript online submissions for Single Number.

I am curious to know what is more efficient method for this problem.

答:
This code should do it:

function getUniqueEl(arr) {
  for (let i = 0; i < arr.length; i++) {
    let temp = arr.lastIndexOf(arr[i]);
    if (temp !== i) {
      delete arr[temp];
    } else {
      return arr[i];
    }
  }
}

console.log(getUniqueEl([2, 2, 1]))```

Body:
I was solving the problem on LeetCode. i.e Single Number.

You need to create a function which takes a array as input and return the only element which is not repeated in array. The array will contain only one element like that.

[2,2,1] //1
[2,3,5,2,3] //5

I have solved the problem with the code below.

var singleNumber = function(nums) {
    let obj = {}
    for(let a of nums){
        obj[a] = obj[a] + 1 || 1;
    }
    for(let key in obj){
        if(obj[key] === 1) return key;
    }
};

However after submitting the result it says

Runtime: 68 ms, faster than 72.96% of JavaScript online submissions for Single Number.

I am curious to know what is more efficient method for this problem.


问:
How to call WKWebView's evaluateJavaScript method
I'm trying to call a native WKWebView method, but nativescript keeps saying that the evaluateJavaScript function is undefined.

How should I try calling that function?

Here's the code I'm trying to run

```<code>console.log(nativeView.ios.evaluateJavaScript('document.URL', () => console.log('Hello, world')));
</code>```

答:
evaluateJavaScriptCompletionHandler is the valid method name, it's documented here.

You may verify the callback for any errors before accessing the result.

```<code>webView.ios.evaluateJavaScriptCompletionHandler(jsStr,
            function (
                result,
                error
            ) {
                if (error) {
                    console.log("error...");
                    return;
                }
                console.log(result);
            });
</code>```

If you still have issues, please share a Playground sample where the issue can be reproduced.

Body:
I'm trying to call a native WKWebView method, but nativescript keeps saying that the evaluateJavaScript function is undefined.

How should I try calling that function?

Here's the code I'm trying to run

console.log(nativeView.ios.evaluateJavaScript('document.URL', () => console.log('Hello, world')));

Body:
evaluateJavaScriptCompletionHandler is the valid method name, it's documented here.

You may verify the callback for any errors before accessing the result.

webView.ios.evaluateJavaScriptCompletionHandler(jsStr,
            function (
                result,
                error
            ) {
                if (error) {
                    console.log("error...");
                    return;
                }
                console.log(result);
            });

If you still have issues, please share a Playground sample where the issue can be reproduced.


问:
keras - keyword initial_state not understood
I am trying to implement a Seq-2-Seq model in keras but I am having trouble resolving an error from SimpleRNN:

TypeError: ('Keyword argument not understood:', 'initial_state')

Here is a small example:

```<code>from keras.models import Model
from keras.layers import Input, SimpleRNN, Embedding

encoder_input = Input(shape=(16,))
encoder_embedding = Embedding(input_dim=40, output_dim=12)(encoder_input)
encoder_rnn_out, encoder_rnn_state = SimpleRNN(32, activation='relu', return_sequences=False, return_state=True)(encoder_embedding)

decoder_input = Input(shape=(11,))
decoder_embedding = Embedding(input_dim=12, output_dim=12)(decoder_input)
decoder_rnn = SimpleRNN(32, activation='relu', initial_state=encoder_rnn_state, return_sequences=True)(decoder_embedding)
decoder_predictions = Dense(12, activation='softmax')(decoder_rnn)

model = Model(encoder_input, decoder_predictions)
</code>```

These are my tensorflow and keras versions (I have already uninstalled and reinstalled them using pip)

```<code>$ conda list -n py36 | grep tensorflow
tensorflow                1.13.1                    <pip>
tensorflow-estimator      1.13.0                    <pip>
$ conda list -n py36 | grep Keras
Keras                     2.2.4                     <pip>
Keras-Applications        1.0.7                     <pip>
Keras-Preprocessing       1.0.9                     <pip>
</code>```

My ~/.keras/keras.json

```<code>{
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}
</code>```

答:
The SimpleRNN constructor does not take initial_state as input argument. You probably meant to use the kernel_initializer or the recurrent_initializer argument instead.

See https://keras.io/layers/recurrent/.

Body:
I am trying to implement a Seq-2-Seq model in keras but I am having trouble resolving an error from SimpleRNN:

TypeError: ('Keyword argument not understood:', 'initial_state')

Here is a small example:

from keras.models import Model
from keras.layers import Input, SimpleRNN, Embedding

encoder_input = Input(shape=(16,))
encoder_embedding = Embedding(input_dim=40, output_dim=12)(encoder_input)
encoder_rnn_out, encoder_rnn_state = SimpleRNN(32, activation='relu', return_sequences=False, return_state=True)(encoder_embedding)

decoder_input = Input(shape=(11,))
decoder_embedding = Embedding(input_dim=12, output_dim=12)(decoder_input)
decoder_rnn = SimpleRNN(32, activation='relu', initial_state=encoder_rnn_state, return_sequences=True)(decoder_embedding)
decoder_predictions = Dense(12, activation='softmax')(decoder_rnn)

model = Model(encoder_input, decoder_predictions)

These are my tensorflow and keras versions (I have already uninstalled and reinstalled them using pip)

$ conda list -n py36 | grep tensorflow
tensorflow                1.13.1                    <pip>
tensorflow-estimator      1.13.0                    <pip>
$ conda list -n py36 | grep Keras
Keras                     2.2.4                     <pip>
Keras-Applications        1.0.7                     <pip>
Keras-Preprocessing       1.0.9                     <pip>

My ~/.keras/keras.json

{
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}


问:
Displaying an Image from URL Objective C
Is there any way of achieving the following that avoids using "initWithData" ? (Just in case you are curious, initWithData is getting my app flagged by Apple as using an illegal API sigh).

```<code>NSData * imageData = [NSData dataWithContentsOfURL : [NSURL URLWithString : [details image]]];
    picture = [[UIImage alloc] initWithData:imageData];
</code>```

Many thanks,

Martin

答:
```<code>NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://Serverurl/pic007.jpg"]];
 self.image=nil;
 UIImage *img = [[UIImage alloc] initWithData:receivedData ];
 self.image = img;
 [img release];
</code>```

I hope this code will help you!!

Body:
Is there any way of achieving the following that avoids using "initWithData" ? (Just in case you are curious, initWithData is getting my app flagged by Apple as using an illegal API sigh).

NSData * imageData = [NSData dataWithContentsOfURL : [NSURL URLWithString : [details image]]];
    picture = [[UIImage alloc] initWithData:imageData];

Many thanks,

Martin

Body:
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://Serverurl/pic007.jpg"]];
 self.image=nil;
 UIImage *img = [[UIImage alloc] initWithData:receivedData ];
 self.image = img;
 [img release];

I hope this code will help you!!


问:
Reading a stacked heading excel sheet using Python
I have an excel sheet where the headings (TradeDate, Value) are stacked on top of each other separated by a type(ABS, MBS), an example of the format:

```<code>ABS,
TradeDate,Value
2019-01-21,21
2019-01-22,22
MBS,
TradeDate,Value
2019-01-21,11
2019-01-22,12
2019-01-23,13
</code>```

How can I load this into python, preferably pandas or another package, where I load each heading separately? The headings are unique/the same for each type and the heading index can change. Using the example above I'd want to return two separate data frames or objects.

df_abs

```<code>TradeDate,Value
2019-01-21,21
2019-01-22,22
</code>```

and df_mbs

```<code>TradeDate,Value
2019-01-21,11
2019-01-22,12
2019-01-23,13
</code>```

答:
This might be a bit overengeneering, but couldn't find a more easy solution:

```<code># Mask all the rows which have a date
m = df[0].str.match('([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))')

# Create an equal indicator on each row which has a date, but stops when value changes so we can groupby
df['ind'] = np.where(~m, 0, (m != m.shift(1)).astype(int).cumsum())

# Extract seperate dataframe into a list
dfs = [d for _, d in df[df.ind.ne(0)].groupby('ind')]

# Rename columns to expected output
dfs = [df.reset_index(drop=True).rename(columns={0:'TradeDate', 1:'Value'}) for df in dfs]
</code>```

Output

```<code>for d in dfs:
    print(d,'\n')

    TradeDate Value  ind
0  2019-01-21    21    2
1  2019-01-22    22    2

    TradeDate Value  ind
0  2019-01-21    11    4
1  2019-01-22    12    4
2  2019-01-23    13    4
</code>```

Reproducable example

```<code>from io import StringIO

a = StringIO('''
ABS,
TradeDate,Value
2019-01-21,21
2019-01-22,22
MBS,
TradeDate,Value
2019-01-21,11
2019-01-22,12
2019-01-23,13
''')

df = pd.read_csv(a, header=None)

# Out
            0      1
0         ABS    NaN
1   TradeDate  Value
2  2019-01-21     21
3  2019-01-22     22
4         MBS    NaN
5   TradeDate  Value
6  2019-01-21     11
7  2019-01-22     12
8  2019-01-23     13
</code>```

Body:
I have an excel sheet where the headings (TradeDate, Value) are stacked on top of each other separated by a type(ABS, MBS), an example of the format:

ABS,
TradeDate,Value
2019-01-21,21
2019-01-22,22
MBS,
TradeDate,Value
2019-01-21,11
2019-01-22,12
2019-01-23,13

How can I load this into python, preferably pandas or another package, where I load each heading separately? The headings are unique/the same for each type and the heading index can change. Using the example above I'd want to return two separate data frames or objects.

df_abs

TradeDate,Value
2019-01-21,21
2019-01-22,22

and df_mbs

TradeDate,Value
2019-01-21,11
2019-01-22,12
2019-01-23,13

Body:
This might be a bit overengeneering, but couldn't find a more easy solution:

# Mask all the rows which have a date
m = df[0].str.match('([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))')

# Create an equal indicator on each row which has a date, but stops when value changes so we can groupby
df['ind'] = np.where(~m, 0, (m != m.shift(1)).astype(int).cumsum())

# Extract seperate dataframe into a list
dfs = [d for _, d in df[df.ind.ne(0)].groupby('ind')]

# Rename columns to expected output
dfs = [df.reset_index(drop=True).rename(columns={0:'TradeDate', 1:'Value'}) for df in dfs]

Output

for d in dfs:
    print(d,'\n')

    TradeDate Value  ind
0  2019-01-21    21    2
1  2019-01-22    22    2

    TradeDate Value  ind
0  2019-01-21    11    4
1  2019-01-22    12    4
2  2019-01-23    13    4

Reproducable example

from io import StringIO

a = StringIO('''
ABS,
TradeDate,Value
2019-01-21,21
2019-01-22,22
MBS,
TradeDate,Value
2019-01-21,11
2019-01-22,12
2019-01-23,13
''')

df = pd.read_csv(a, header=None)

# Out
            0      1
0         ABS    NaN
1   TradeDate  Value
2  2019-01-21     21
3  2019-01-22     22
4         MBS    NaN
5   TradeDate  Value
6  2019-01-21     11
7  2019-01-22     12
8  2019-01-23     13


问:
Batch File to Loop Over Files In a Folder and Run Exe for Info
I am writing a *.BAT file to count the frames in every GIF file in a folder. Writing all that to TXT files would be nice, but I haven't gotten that far yet.

I can do this from the command line for single files.

This does what I want, but it does not output the number of frames to the window.
The next line is a sample of what it should do for a single file.

```<code>"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n 14215349.gif
</code>```

These two lines should do the same for every file in the folder.
But, they just echo the command, rather than show its output.

```<code>set "frames=^0x22c:\program^ files\ImageMagick-6.8.9-Q8\identify.exe^0x22^ -format^ %%n"
forfiles /m *.gif /c "cmd /c echo %frames% @file"
</code>```

The only thing I can see wrong is the double quotes, but this shows that's not it:

```<code>"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n "14215349.gif"
pause
</code>```

It should output an integer for each file. Line 1 does this. Lines 2 and 3 do not; they just echo the command.

答:
This code works:

```<code>for %%I in (*.gif) do "c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n %%I >>FramesList.txt
pause
</code>```

Thanks.

I hope I can ask for one more thing. The output I get is integers only, on one line, no spaces of filenames. How do I write this so the FramesList.txt file shows the frame count integer (never more than 3 digits) followed by the filename on each line?

Body:
I am writing a *.BAT file to count the frames in every GIF file in a folder. Writing all that to TXT files would be nice, but I haven't gotten that far yet.

I can do this from the command line for single files.

This does what I want, but it does not output the number of frames to the window.
The next line is a sample of what it should do for a single file.

"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n 14215349.gif

These two lines should do the same for every file in the folder.
But, they just echo the command, rather than show its output.

set "frames=^0x22c:\program^ files\ImageMagick-6.8.9-Q8\identify.exe^0x22^ -format^ %%n"
forfiles /m *.gif /c "cmd /c echo %frames% @file"

The only thing I can see wrong is the double quotes, but this shows that's not it:

"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n "14215349.gif"
pause

It should output an integer for each file. Line 1 does this. Lines 2 and 3 do not; they just echo the command.

Body:
This code works:

for %%I in (*.gif) do "c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n %%I >>FramesList.txt
pause

Thanks.

I hope I can ask for one more thing. The output I get is integers only, on one line, no spaces of filenames. How do I write this so the FramesList.txt file shows the frame count integer (never more than 3 digits) followed by the filename on each line?