问:
Missing dependency for method public javax.ws.rs.core.Response (Upload File JAX-RS)
I found an error when create method POST for upload file function. how to solve this problem? Thanks.

this log error:

Jul 05, 2017 4:20:23 PM org.apache.coyote.AbstractProtocol init INFO:
  Initializing ProtocolHandler ["http-bio-8087"] Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardService startInternal INFO: Starting
  service Tomcat Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardEngine startInternal INFO: Starting
  Servlet Engine: Apache Tomcat/7.0.47 Jul 05, 2017 4:20:27 PM
  com.sun.jersey.api.core.PackagesResourceConfig init INFO: Scanning for
  root resource and provider classes in the packages:

  org.arpit.java2blog.controller Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig logClasses INFO: Root
  resource classes found:   class
  org.arpit.java2blog.controller.FileUploadController   class
  org.arpit.java2blog.controller.CountryController   class
  org.arpit.java2blog.controller.KasusController Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig init INFO: No provider
  classes found. Jul 05, 2017 4:20:28 PM
  com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
  INFO: Initiating Jersey application, version 'Jersey: 1.19.3
  10/24/2016 03:43 PM' Jul 05, 2017 4:20:29 PM
  com.sun.jersey.spi.inject.Errors processErrorMessages SEVERE: The
  following errors and warnings have been detected with resource and/or
  provider classes:   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 0   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 1   SEVERE: Method, public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition),
  annotated with POST of resource, class
  org.arpit.java2blog.controller.FileUploadController, is not recognized
  as valid resource method. Jul 05, 2017 4:20:29 PM
  org.apache.catalina.core.ApplicationContext log SEVERE:
  StandardWrapper.Throwable
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Jul 05, 2017 4:20:29 PM org.apache.catalina.core.StandardContext
  loadOnStartup SEVERE: Servlet /JSONExampleJAXB threw load() exception
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

my pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>JSONExampleJAXB</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JSONExampleJAXB Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jersey.version>1.19.3</jersey.version>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
    </properties>

    <dependencies>
        <!-- Local Libraries -->
        <dependency>
            <groupId>com.sap.hana</groupId>
            <artifactId>ng</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ngdbc-1.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1-m05</version>
            <scope>provided</scope>
        </dependency>

        <!-- Dependency untuk mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- JSON Dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- Jersey -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <!-- Mimepull untuk prerequisites upload file -->
        <dependency>
            <groupId>org.jvnet.mimepull</groupId>
            <artifactId>mimepull</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!--  -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jettison-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.10</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>JSONExampleJAXB</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8087</port>
                    <path>/JSONExampleJAXB</path>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>
</code>```

my web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>org.arpit.java2blog.controller</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
            <param-value>org.arpit.java2blog.config.CORSFilter</param-value>
        </init-param>

        <init-param>
            <param-name>org.arpit.java2blog.controller.FileUploadController</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;
             org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

FileUploadController.java

```<code>package org.arpit.java2blog.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/files")
public class FileUploadController {

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) {
            String fileLocation = "d://" + fileDetail.getFileName();
                    //saving file
            try {
                FileOutputStream out = new FileOutputStream(new File(fileLocation));
                int read = 0;
                byte[] bytes = new byte[1024];
                out = new FileOutputStream(new File(fileLocation));
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                out.close();
            } catch (IOException e) {e.printStackTrace();}
            String output = "File successfully uploaded to : " + fileLocation;
            return Response.status(200).entity(output).build();
        }

}
</code>```

答:
Update your pom.xml. Shoud be help you</p>

```<code><dependency>
    <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
      <scope>provided</scope>
  </dependency>
</code>```

Body:
I found an error when create method POST for upload file function. how to solve this problem? Thanks.

this log error:

Jul 05, 2017 4:20:23 PM org.apache.coyote.AbstractProtocol init INFO:
  Initializing ProtocolHandler ["http-bio-8087"] Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardService startInternal INFO: Starting
  service Tomcat Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardEngine startInternal INFO: Starting
  Servlet Engine: Apache Tomcat/7.0.47 Jul 05, 2017 4:20:27 PM
  com.sun.jersey.api.core.PackagesResourceConfig init INFO: Scanning for
  root resource and provider classes in the packages:

  org.arpit.java2blog.controller Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig logClasses INFO: Root
  resource classes found:   class
  org.arpit.java2blog.controller.FileUploadController   class
  org.arpit.java2blog.controller.CountryController   class
  org.arpit.java2blog.controller.KasusController Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig init INFO: No provider
  classes found. Jul 05, 2017 4:20:28 PM
  com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
  INFO: Initiating Jersey application, version 'Jersey: 1.19.3
  10/24/2016 03:43 PM' Jul 05, 2017 4:20:29 PM
  com.sun.jersey.spi.inject.Errors processErrorMessages SEVERE: The
  following errors and warnings have been detected with resource and/or
  provider classes:   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 0   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 1   SEVERE: Method, public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition),
  annotated with POST of resource, class
  org.arpit.java2blog.controller.FileUploadController, is not recognized
  as valid resource method. Jul 05, 2017 4:20:29 PM
  org.apache.catalina.core.ApplicationContext log SEVERE:
  StandardWrapper.Throwable
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Jul 05, 2017 4:20:29 PM org.apache.catalina.core.StandardContext
  loadOnStartup SEVERE: Servlet /JSONExampleJAXB threw load() exception
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>JSONExampleJAXB</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JSONExampleJAXB Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jersey.version>1.19.3</jersey.version>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.sap.hana</groupId>
            <artifactId>ng</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ngdbc-1.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1-m05</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jvnet.mimepull</groupId>
            <artifactId>mimepull</artifactId>
            <version>1.9.4</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jettison-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.10</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>JSONExampleJAXB</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8087</port>
                    <path>/JSONExampleJAXB</path>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>

my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>org.arpit.java2blog.controller</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
            <param-value>org.arpit.java2blog.config.CORSFilter</param-value>
        </init-param>

        <init-param>
            <param-name>org.arpit.java2blog.controller.FileUploadController</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;
             org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

FileUploadController.java

package org.arpit.java2blog.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/files")
public class FileUploadController {

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) {
            String fileLocation = "d://" + fileDetail.getFileName();
                    //saving file
            try {
                FileOutputStream out = new FileOutputStream(new File(fileLocation));
                int read = 0;
                byte[] bytes = new byte[1024];
                out = new FileOutputStream(new File(fileLocation));
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                out.close();
            } catch (IOException e) {e.printStackTrace();}
            String output = "File successfully uploaded to : " + fileLocation;
            return Response.status(200).entity(output).build();
        }

}

Body:
Update your pom.xml. Shoud be help you

<dependency>
    <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
      <scope>provided</scope>
  </dependency>


来源: stackexchange

问:
How can I build a two or multidimensional list from already available one dimension list in python?
I have a list below.  I would like to create a two or multidimensional list from one dimension normal list

x= [ light, double , motor , boolean , brakes , unit 8]

I would like to see like that

x= [ [light, double] , [motor , boolean] , [brakes , unit 8]]

in this way I can select and check the type of specific signal

答:
You can slice and the zip the list like this:

```<code>zip(x[::2], x[1::2])
</code>```

This will generate a list of two-element tuples.

ContentLicense: CC BY-SA 4.0

Body:
You can slice and the zip the list like this:

zip(x[::2], x[1::2])

This will generate a list of two-element tuples.

ContentLicense: CC BY-SA 3.0


问:
How to use Angular UI Bootstrap Tooltip
I want to use Angular UI Bootstrap Tooltip ui.bootstrap.tooltip separated.

I'm able to use tooltip by adding full ui-bootstrap file, like:

```<code><script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.js"></script>
<script>var App = angular.module("App", ['ui.bootstrap']);</script>
</code>```

But I want to include only tooltip functionality instead of adding full UI Bootstrap featured.

答:
Use like this:

```<code>angular.module("App", ['ui.bootstrap.tooltip']);
</code>```

it will load only tooltip library.

Title: How to use Angular UI Bootstrap Tooltip

Body:
I want to use Angular UI Bootstrap Tooltip ui.bootstrap.tooltip separated.

I'm able to use tooltip by adding full ui-bootstrap file, like:

But I want to include only tooltip functionality instead of adding full UI Bootstrap featured.

Body:
Use like this:

angular.module("App", ['ui.bootstrap.tooltip']);

it will load only tooltip library.


问:
Best way to pass the value in Some to a function with a default parameter value?
I have a function from a third party library as below :

```<code>def myfunction(input:String = "some constant value")
</code>```

I have a

```<code>myinput:Option[String]
</code>```

with me and I need to pass the function. Right now I am doing this:

```<code>myfunction(myinput.getOrElse("some constant value"))
</code>```

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

答:
Another way would be a fold.
Assuming myfunction returns String we get:</p>

```<code>val callIt: Option[String] => String = it => it.fold(myfunction())(myfunction(_))

callIt(None)
callIt(Some("abc"))
</code>```

Body:
I have a function from a third party library as below :

def myfunction(input:String = "some constant value")

I have a

myinput:Option[String]

with me and I need to pass the function. Right now I am doing this:

myfunction(myinput.getOrElse("some constant value"))

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

Body:
Another way would be a fold.
Assuming myfunction returns String we get:

val callIt: Option[String] => String = it => it.fold(myfunction())(myfunction(_))

callIt(None)
callIt(Some("abc"))


问:
How to add an onclick method on dynamically created button using jquery
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

```<code>'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '
</code>```

but it leaves me an error saying the test function isn't defined.

here's my whole code:

```<code>$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('<tr><td>' + items[i].unitId + '</td><td>'+
             items[i].pcName +'</td><td>'+ items[i].user + '</td><td>'+
             items[i].department+'</td><td>'+items[i].location+ '</td><td>'+
             items[i].dateAssigned + '</td><td>' + items[i].status +'</td><td>' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '</td></tr>');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});
</code>```

答:
Calling a function inline will only work from global scope, so defined it outside of the success callback. Or alternatively you could just attach the listener dynamically, like so:

```<code>$(.test).off('click').on('click', test)
</code>```

And then your test() function could be defined in global scope. You can add the off('click') to make sure only one listener is on the buttons at all times. Perhaps a more performant option, however could be the following:

```<code>$(document).on('click', function (event) {
    if ($(event.target).is('.test')) {
        // call test() here
    }
})
</code>```

This way, only a single listener needs to be attached and it does not have to be re-attached when new buttons are added.

Body:
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '

but it leaves me an error saying the test function isn't defined.

here's my whole code:

$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('
' + items[i].unitId + '	'+
             items[i].pcName +'	'+ items[i].user + '	'+
             items[i].department+'	'+items[i].location+ '	'+
             items[i].dateAssigned + '	' + items[i].status +'	' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '
');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});

Body:
Calling a function inline will only work from global scope, so defined it outside of the success callback. Or alternatively you could just attach the listener dynamically, like so:

$(.test).off('click').on('click', test)

And then your test() function could be defined in global scope. You can add the off('click') to make sure only one listener is on the buttons at all times. Perhaps a more performant option, however could be the following:

$(document).on('click', function (event) {
    if ($(event.target).is('.test')) {
        // call test() here
    }
})

This way, only a single listener needs to be attached and it does not have to be re-attached when new buttons are added.


问:
Xpath does not recognize regex parts
I am new to this and I am trying to understand the usage of selenium and XPath

```<code>string exp = "//*[@id=\"g_1_bHwVovAN\"]/td[2]";
var dateTime = chromeDriver.FindElementsByXPath(exp);
</code>```

With this code, I can only take 1 element. How can I change this "bHwVovAN" part, so I can reach the all that kinds of elements on the website.

```<code>string exp = "//*[@id=\"g_1_[^[0-9+]]\"]/td[2]";
var dateTime = chromeDriver.FindElementsByXPath(exp);
</code>```

I tried to use regex, but It did not work. It did not recognize regex parts. Also, I looked at the other posts, and tried to use matches, and also did not work. How can I solve it?

If I did not write clear and correct way, I am also new to English. Sorry

答:
There is a matches() function in XPath 2.0 that would solve your issue, but selenium doesn't support this XPath version.

You can try below to match elements with id attribute that starts with "g_1_":

```<code>string exp = "//*[starts-with(@id,\"g_1_\")]/td[2]";
</code>```

Title: Xpath does not recognize regex parts

Body:
I am new to this and I am trying to understand the usage of selenium and XPath

string exp = "//*[@id=\"g_1_bHwVovAN\"]/td[2]";
var dateTime = chromeDriver.FindElementsByXPath(exp);

With this code, I can only take 1 element. How can I change this "bHwVovAN" part, so I can reach the all that kinds of elements on the website.

string exp = "//*[@id=\"g_1_[^[0-9+]]\"]/td[2]";
var dateTime = chromeDriver.FindElementsByXPath(exp);

I tried to use regex, but It did not work. It did not recognize regex parts. Also, I looked at the other posts, and tried to use matches, and also did not work. How can I solve it?

If I did not write clear and correct way, I am also new to English. Sorry

Body:
There is a matches() function in XPath 2.0 that would solve your issue, but selenium doesn't support this XPath version.

You can try below to match elements with id attribute that starts with "g_1_":

string exp = "//*[starts-with(@id,\"g_1_\")]/td[2]";


问:
Defining angle of the gradient using CAGradientLayer
I am trying to draw angular gradient using CaGradientLayer. I know angle can be defined using startPoint and endPoint. I can compute these points for some standard angles like 0, 90, 180, 360 etc. But I want formulate these points for arbitrary angle. I have tried computing it using some trigonometry, but didn't get any success. Can anyone give me any directions on how to compute these points for arbitrary angles?

答:
Swift 3

```<code>static func setGradient(view: UIView!,viewRadius: CGFloat!, color1: UIColor!, color2: UIColor!, angle: Double!, alphaValue: CGFloat!){
    let gradient = CAGradientLayer()

    gradient.frame =  CGRect(origin: CGPoint.zero, size: view.frame.size)

    gradient.colors = [color1.withAlphaComponent(alphaValue).cgColor, color2.withAlphaComponent(alphaValue).cgColor]
    let x: Double! = angle / 360.0
    let a = pow(sinf(Float(2.0 * M_PI * ((x + 0.75) / 2.0))),2.0);
    let b = pow(sinf(Float(2*M_PI*((x+0.0)/2))),2);
    let c = pow(sinf(Float(2*M_PI*((x+0.25)/2))),2);
    let d = pow(sinf(Float(2*M_PI*((x+0.5)/2))),2);

    gradient.endPoint = CGPoint(x: CGFloat(c),y: CGFloat(d))
    gradient.startPoint = CGPoint(x: CGFloat(a),y:CGFloat(b))

    view.roundCorners([.topLeft, .bottomLeft], radius: viewRadius)
    view.layer.insertSublayer(gradient, at: 0)

}
</code>```

Body:
Swift 3

static func setGradient(view: UIView!,viewRadius: CGFloat!, color1: UIColor!, color2: UIColor!, angle: Double!, alphaValue: CGFloat!){
    let gradient = CAGradientLayer()

    gradient.frame =  CGRect(origin: CGPoint.zero, size: view.frame.size)

    gradient.colors = [color1.withAlphaComponent(alphaValue).cgColor, color2.withAlphaComponent(alphaValue).cgColor]
    let x: Double! = angle / 360.0
    let a = pow(sinf(Float(2.0 * M_PI * ((x + 0.75) / 2.0))),2.0);
    let b = pow(sinf(Float(2*M_PI*((x+0.0)/2))),2);
    let c = pow(sinf(Float(2*M_PI*((x+0.25)/2))),2);
    let d = pow(sinf(Float(2*M_PI*((x+0.5)/2))),2);

    gradient.endPoint = CGPoint(x: CGFloat(c),y: CGFloat(d))
    gradient.startPoint = CGPoint(x: CGFloat(a),y:CGFloat(b))

    view.roundCorners([.topLeft, .bottomLeft], radius: viewRadius)
    view.layer.insertSublayer(gradient, at: 0)

}


问:
Why webpack commonChunk duplicates packages between my bundles?
I want to create a vendor.bundle.js from my modules.
I configured webpack:

```<code>...
  entry: {
    app: ['./src/index.js'],
    vendor: [
      'axios',
      'lodash',
      'recharts',
      'moment',
      ......
      'react-select',
      'react-tooltip',
      'react-toggle',
      'buffer',
      'jstz',
      'pikaday',
      'qrcode-js',
      'notie',
      'tippy.js',
      'react-dropzone',
      'react-dd-menu',
      'html-to-draftjs',
      'react-virtualized',
      'react-draft-wysiwyg',
      'js-search',
      'qr.js'
    ]
  },
  ...
  output: {
    path: '/Users/ben/pro/qbpanel2.0/qbpanel-2.0/qbpanel/app/assets/javascripts',
    publicPath: '/',
    filename: 'bundle.js'
  },
  ...
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerPort: 9998
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filename: 'vendor.bundle.js',
      path: '/Users/ben/pro/qbpanel2.0/qbpanel-2.0/qbpanel/app/assets/javascripts',
      publicPath: '/',
      minChunks: Infinity
    }),
...
  ]
}
</code>```

I expect to see all the packages listed in entry.vendor to end in the vendor.bundle.js, and for most of them it happens, but in my some of them show up in both bundle.js and vendor.bundle.js files.

Why?

bundle.js I was not expecting to find tippy.js or react-virtualized or lodash

vendor.bundle.js, there are the same packages that are in the bundle.js and I expect to be only here.

答:
Which version of webpack are you using ?
To do what you're looking for, you can use the commonsChunkPluggin

The configuration could look like something like this in webpack 2:

```<code>plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: ['node-modules'],
    minChunks(module) {
      const context = module.context;
      return context && context.indexOf('node_modules') >= 0;
    },
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: ['vendor'],
    chunks: ['node-modules'],
    minChunks(module) {
      return module.context && /.*\/axios|losash|allTheModulesYouWant.*/.test(module.context);
    },
  }),
]
</code>```

This creates a chunk with all the node modules and takes out of it some of them (that you need to name) to put them into vendor

Body:
I want to create a vendor.bundle.js from my modules.
I configured webpack:

...
  entry: {
    app: ['./src/index.js'],
    vendor: [
      'axios',
      'lodash',
      'recharts',
      'moment',
      ......
      'react-select',
      'react-tooltip',
      'react-toggle',
      'buffer',
      'jstz',
      'pikaday',
      'qrcode-js',
      'notie',
      'tippy.js',
      'react-dropzone',
      'react-dd-menu',
      'html-to-draftjs',
      'react-virtualized',
      'react-draft-wysiwyg',
      'js-search',
      'qr.js'
    ]
  },
  ...
  output: {
    path: '/Users/ben/pro/qbpanel2.0/qbpanel-2.0/qbpanel/app/assets/javascripts',
    publicPath: '/',
    filename: 'bundle.js'
  },
  ...
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerPort: 9998
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filename: 'vendor.bundle.js',
      path: '/Users/ben/pro/qbpanel2.0/qbpanel-2.0/qbpanel/app/assets/javascripts',
      publicPath: '/',
      minChunks: Infinity
    }),
...
  ]
}

I expect to see all the packages listed in entry.vendor to end in the vendor.bundle.js, and for most of them it happens, but in my some of them show up in both bundle.js and vendor.bundle.js files.

Why?

bundle.js I was not expecting to find tippy.js or react-virtualized or lodash

vendor.bundle.js, there are the same packages that are in the bundle.js and I expect to be only here.

Body:
Which version of webpack are you using ?
To do what you're looking for, you can use the commonsChunkPluggin

The configuration could look like something like this in webpack 2:

plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: ['node-modules'],
    minChunks(module) {
      const context = module.context;
      return context && context.indexOf('node_modules') >= 0;
    },
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: ['vendor'],
    chunks: ['node-modules'],
    minChunks(module) {
      return module.context && /.*\/axios|losash|allTheModulesYouWant.*/.test(module.context);
    },
  }),
]

This creates a chunk with all the node modules and takes out of it some of them (that you need to name) to put them into vendor


问:
Find all grouped records where a records are newer than a certain type of record
That would be the intermediary output I need:

```<code>Id1, Id2, Type,   Date
1,   2,    test,  2010-10-10
1,   3,    stage, 2010-05-05
1,   2,    stage, 2010-12-12
1,   3,    test,  2010-04-04
1,   3,    prod,  2010-12-31
</code>```

From that point I want to know how many grouped (Id1,Id2) records do exist after the record with Type = 'test'.

for the above I would get this final output:

```<code>Id1, Id2, Count
1,   2,   1
1,   3,   2
</code>```

What sql query would that be?

The use case would be to find all those records who never made it to a later stage than type = "test"

答:
You have to get the value of Date for "test" Type for corresponding ID1 and ID2 and then make a count of records. Like this:</p>

```<code>drop table if exists dbo.LaterThan;

create table dbo.LaterThan (
    Id1 int
    , Id2 int
    , Type varchar(100)
    , Date date
);

insert into dbo.LaterThan (Id1, Id2, Type, Date)
values (1, 2, 'test', '20101010')
    , (1, 3, 'stage', '20100505')
    , (1, 2, 'stage', '20101212')
    , (1, 3, 'test', '20100404')
    , (1, 3, 'prod', '20101231')

select
    lt.Id1
    , lt.Id2
    , count(case when lt.Date >= test.Date and lt.Type <> 'test' then 1 else null end) as Cnt
from dbo.LaterThan lt
    outer apply (
            select
                top (1)
                tlt.Date
            from dbo.LaterThan tlt
            where lt.ID1 = tlt.Id1
                and lt.ID2 = tlt.Id2
                and tlt.Type = 'test'
    ) test
group by lt.Id1, lt.Id2
</code>```

Body:
That would be the intermediary output I need:

Id1, Id2, Type,   Date
1,   2,    test,  2010-10-10
1,   3,    stage, 2010-05-05
1,   2,    stage, 2010-12-12
1,   3,    test,  2010-04-04
1,   3,    prod,  2010-12-31

From that point I want to know how many grouped (Id1,Id2) records do exist after the record with Type = 'test'.

for the above I would get this final output:

Id1, Id2, Count
1,   2,   1
1,   3,   2

What sql query would that be?

The use case would be to find all those records who never made it to a later stage than type = "test"

Body:
You have to get the value of Date for "test" Type for corresponding ID1 and ID2 and then make a count of records. Like this:

drop table if exists dbo.LaterThan;

create table dbo.LaterThan (
    Id1 int
    , Id2 int
    , Type varchar(100)
    , Date date
);

insert into dbo.LaterThan (Id1, Id2, Type, Date)
values (1, 2, 'test', '20101010')
    , (1, 3, 'stage', '20100505')
    , (1, 2, 'stage', '20101212')
    , (1, 3, 'test', '20100404')
    , (1, 3, 'prod', '20101231')

select
    lt.Id1
    , lt.Id2
    , count(case when lt.Date >= test.Date and lt.Type <> 'test' then 1 else null end) as Cnt
from dbo.LaterThan lt
    outer apply (
            select
                top (1)
                tlt.Date
            from dbo.LaterThan tlt
            where lt.ID1 = tlt.Id1
                and lt.ID2 = tlt.Id2
                and tlt.Type = 'test'
    ) test
group by lt.Id1, lt.Id2


问:
How to use Rxjs and document.querySelector('button') in angular2 cli project
Getting Error "Clicked NaN times".
What is the correct way to execute  Rxjs code below?</p>

```<code>import { Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/throttleTime';
export class AppComponent {
    count: number;
    title = 'app';
    @ViewChild('input') button: ElementRef;
    // @ViewChild('input1') button: ElementRef;
    constructor() {
    }

    ngAfterViewInit() {
        Observable.fromEvent(this.button.nativeElement, 'click')
            .throttleTime(1000)
            .scan(count => this.count + 1, 0)
            .subscribe(count => console.log(`Clicked ${count} times`));

    }
}
</code>```

答:
You don't need to use this.count:

```<code>Observable.fromEvent(this.button.nativeElement, 'click')
   .throttleTime(1000)
   .scan(count => count + 1, 0)
   .subscribe(count => console.log(`Clicked ${count} times`));
</code>```

You're passing an initial value here:

```<code>   .scan(count => count + 1, 0)
                            ^^^
</code>```

As the docs say:

You can optionally pass scan a seed value as an additional parameter.
  scan will pass this seed value to the accumulator function the first
  time it is called (for the first emission from the source Observable)
  in place of the result from the missing prior call to the accumulator.

Body:
Getting Error "Clicked NaN times".
What is the correct way to execute  Rxjs code below?

import { Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/throttleTime';
export class AppComponent {
    count: number;
    title = 'app';
    @ViewChild('input') button: ElementRef;
    // @ViewChild('input1') button: ElementRef;
    constructor() {
    }

    ngAfterViewInit() {
        Observable.fromEvent(this.button.nativeElement, 'click')
            .throttleTime(1000)
            .scan(count => this.count + 1, 0)
            .subscribe(count => console.log(`Clicked ${count} times`));

    }
}

Body:
You don't need to use this.count:

Observable.fromEvent(this.button.nativeElement, 'click')
   .throttleTime(1000)
   .scan(count => count + 1, 0)
   .subscribe(count => console.log(`Clicked ${count} times`));

You're passing an initial value here:

   .scan(count => count + 1, 0)
                            ^^^

As the docs say:

You can optionally pass scan a seed value as an additional parameter.
  scan will pass this seed value to the accumulator function the first
  time it is called (for the first emission from the source Observable)
  in place of the result from the missing prior call to the accumulator.


问:
Rails: create symlink with capistrano before initializer from config/initializers is executed
I have a capistrano task that is executed like this in deploy.rb:

```<code>after  'deploy:update_code', 'deploy:create_symlink'
</code>```

The task:

```<code>Capistrano::Configuration.instance.load do
    namespace :deploy do
         task :create_symlink do
           run "touch #{shared_path}/somefile.yml"
           run "ln -nfs #{shared_path}/somefile.yml #{release_path}/config/somefile.yml"
         end
    end
end
</code>```

configs are loaded from somefile.yml like this:

```<code>customconf = OpenStruct.new(YAML::load_file(File.join(Rails.root, 'config', 'somefile.yml'))[Rails.env]||{})
</code>```

The issue that I'm having is that the configs are loaded in config/initializers/customconfig.rb. but the symlink seems to be created after the code in customconfig.rb is created.

This is the error I'm getting when trying to cap deploy:

Errno::ENOENT: No such file or directory - /var/www/vhosts/mysite/rails/releases/20170705083649/config/somefile.yml

Basically how can I load the configs from somefile.yml after the symlink is created. Or how can I run the cap task before the initializer is executed?

答: I solved my issue by changing after  'deploy:update_code' to after after 'deploy:finalize_update'. But I want to ask if this is the correct way of doing it before I accept this as accepted answer.

Body:
I have a capistrano task that is executed like this in deploy.rb:

after  'deploy:update_code', 'deploy:create_symlink'

The task:

Capistrano::Configuration.instance.load do
    namespace :deploy do
         task :create_symlink do
           run "touch #{shared_path}/somefile.yml"
           run "ln -nfs #{shared_path}/somefile.yml #{release_path}/config/somefile.yml"
         end
    end
end

configs are loaded from somefile.yml like this:

customconf = OpenStruct.new(YAML::load_file(File.join(Rails.root, 'config', 'somefile.yml'))[Rails.env]||{})

The issue that I'm having is that the configs are loaded in config/initializers/customconfig.rb. but the symlink seems to be created after the code in customconfig.rb is created.

This is the error I'm getting when trying to cap deploy:

Errno::ENOENT: No such file or directory - /var/www/vhosts/mysite/rails/releases/20170705083649/config/somefile.yml

Basically how can I load the configs from somefile.yml after the symlink is created. Or how can I run the cap task before the initializer is executed?


问:
Unable to retreive unique dates from mysql column having date and time in mysql using php
Hi friend am trying to retreive the dates from mysql column named 'date' which has date and time. I want to retreive only dates not times. I want retreive only dates which are not duplicates..

Here is sample data of mysql with column date..

```<code>   03/07/2017 03:37:12pm
   03/07/2017 10:38:12pm
   04/07/2017 10:38:12pm
   04/07/2017 2:38:12pm
</code>```

wanted out put as

```<code>     03/07/2017
     04/07/2017
</code>```

Here is my php code

```<code><?php

$sql = "SELECT  DISTINCT date('d/m/Y,date) FROM video_data";
echo $sql;
$result = mysqli_query($connection, $sql);
echo $result;
while ($row = mysqli_fetch_assoc($result)) {
    $id   = $row['id'];
    $date = $row['date'];
    $date = date('Y-m-d', strtotime($date));
    echo "<tr>";
    echo "<td>$date</td>";
    echo "</tr>";

}

?>
</code>```

Am unable to print dates using php

答:
Use something like</p>

```<code><?php
$sql = "SELECT DISTINCT id,date FROM video_data";
//echo $sql;
$result = mysqli_query($connection, $sql);
//echo $result;
while ($row = mysqli_fetch_assoc($result)) {
 $id   = $row['id'];
 $date = $row['date'];
 $date = date('d/m/Y', strtotime($date));
 echo "<tr>";
 echo "<td>".$date."</td>";
 echo "</tr>";
}
?>
</code>```

Body:
Hi friend am trying to retreive the dates from mysql column named 'date' which has date and time. I want to retreive only dates not times. I want retreive only dates which are not duplicates..

Here is sample data of mysql with column date..

   03/07/2017 03:37:12pm
   03/07/2017 10:38:12pm
   04/07/2017 10:38:12pm
   04/07/2017 2:38:12pm

wanted out put as

     03/07/2017
     04/07/2017

Here is my php code

<?php

$sql = "SELECT  DISTINCT date('d/m/Y,date) FROM video_data";
echo $sql;
$result = mysqli_query($connection, $sql);
echo $result;
while ($row = mysqli_fetch_assoc($result)) {
    $id   = $row['id'];
    $date = $row['date'];
    $date = date('Y-m-d', strtotime($date));
    echo "
";
    echo "$date	";
    echo "
";

}

?>

Am unable to print dates using php

Body:
Use something like

<?php
$sql = "SELECT DISTINCT id,date FROM video_data";
//echo $sql;
$result = mysqli_query($connection, $sql);
//echo $result;
while ($row = mysqli_fetch_assoc($result)) {
 $id   = $row['id'];
 $date = $row['date'];
 $date = date('d/m/Y', strtotime($date));
 echo "<tr>";
 echo "<td>".$date."</td>";
 echo "</tr>";
}
?>


问:
Jquery Ajax Post array of input data
I am writing a thing to compare two passwords with each other, if they match the script sends out a response that says it is the same.

I currently have got this code:

```<code>$("#repeatPw").keyup(function(){
    jQuery.ajax({
        url: "System/Javascript/Functions/checkPasswords.php",
        data: "'password1'='" + $("#Password").val() + "', 'password2'='" + $("#repeatPw").val() + "'",
        type: "POST",
        success: function(data) {
            $("#passwordMatch").html(data);
        },
        error: function(data) {}
    });
});
</code>```

Now my problem is that i cant get this password1 and password2 in a proper array i can explode in the checkPasswords.php, this posts this:

Array ( ['password1'] => 'fasfasdfasSD2', 'password2'='asdasdasd' )

But this is not a proper array as it only puts password1 in proper array format, how would i go about making password2 in this format too?

Thank you all in advance!

答:
Create an array and pass it as the ajax post data,

```<code>   var data=[];

    data['password1']= $("#Password").val();
    data['password2']= $("#repeatPw").val();
</code>```

Though you could do this in the client side itself.

```<code>if($("#Password").val().trim() == $("#repeatPw").val().trim())
    //password Matches
</code>```

Title: Jquery Ajax Post array of input data

Body:
I am writing a thing to compare two passwords with each other, if they match the script sends out a response that says it is the same.

I currently have got this code:

$("#repeatPw").keyup(function(){
    jQuery.ajax({
        url: "System/Javascript/Functions/checkPasswords.php",
        data: "'password1'='" + $("#Password").val() + "', 'password2'='" + $("#repeatPw").val() + "'",
        type: "POST",
        success: function(data) {
            $("#passwordMatch").html(data);
        },
        error: function(data) {}
    });
});

Now my problem is that i cant get this password1 and password2 in a proper array i can explode in the checkPasswords.php, this posts this:

Array ( ['password1'] => 'fasfasdfasSD2', 'password2'='asdasdasd' )

But this is not a proper array as it only puts password1 in proper array format, how would i go about making password2 in this format too?

Thank you all in advance!

Body:
Create an array and pass it as the ajax post data,

   var data=[];

    data['password1']= $("#Password").val();
    data['password2']= $("#repeatPw").val();

Though you could do this in the client side itself.

if($("#Password").val().trim() == $("#repeatPw").val().trim())
    //password Matches


问:
How to show the text on a ImageButton?
I have an ImageButton and I want to show a text and an image on it. But when I try on emulator:

```<code><ImageButton
    android:text="OK"
    android:id="@+id/buttonok"
    android:src="@drawable/buttonok"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</code>```

I get the image but without the text. How can I show the text? Please help me!

答:
Guys I need to develop the setting and logout button, I used the below code.

```<code>    <Button
        android:id="@+id/imageViewLogout"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/size_30dp"
        android:layout_alignParentLeft="true"
        android:text="Settings"
        android:drawablePadding="10dp"
        android:background="@android:color/transparent"
        android:layout_alignParentBottom="true"
        android:drawableTop="@drawable/logout" />
</code>```

Title: How to show the text on a ImageButton?

Body:
I have an ImageButton and I want to show a text and an image on it. But when I try on emulator:

<ImageButton
    android:text="OK"
    android:id="@+id/buttonok"
    android:src="@drawable/buttonok"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

I get the image but without the text. How can I show the text? Please help me!

Body:
Guys I need to develop the setting and logout button, I used the below code.

    <Button
        android:id="@+id/imageViewLogout"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/size_30dp"
        android:layout_alignParentLeft="true"
        android:text="Settings"
        android:drawablePadding="10dp"
        android:background="@android:color/transparent"
        android:layout_alignParentBottom="true"
        android:drawableTop="@drawable/logout" />


问:
View's height is 0 under certain conditions when transitioning between Activities
Here is the context: I have a Activity with complex layout to which I want to transition using relatively complex Transitions. The catch is that I need to position one view (scroll_frame) below the image (I can't use XML), so I need to know it's height. It works fine the first time, however after some number of going back and forth between Activities image's height is suddenly zero (caching, race conditions?)

Here is the snippet of onCreate:

```<code>    super.onCreate(savedInstanceState)
    postponeEnterTransition()
    setContentView(R.layout.some_id)

    // ... non-essential stuff.

    Glide.with(this)
            .load([some resource id])
            .into(object : SimpleTarget<Drawable>() {
                override fun onResourceReady(d: Drawable?, t: Transition<in Drawable>?) {
                    // Prepare image.
                    image.setImageDrawable(d)

                    val margin = Math.max(image.measuredHeight, 0)

                    // ... non-essential stuff

                    layoutParams.setMargins(0, margin, 0, 0)

                    // Critical part.
                    scroll_frame?.layoutParams = layoutParams

                    // Start transition.
                    startPostponedEnterTransition()
                }
            })
</code>```

答:
that's because your view isn't set yet:

use this:

```<code>image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            public void onGlobalLayout() {
             //don't forget to remove the listener to prevent being called again by future layout events:
                image.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            val margin = Math.max(image.measuredHeight, 0)

                    // ... non-essential stuff

                    layoutParams.setMargins(0, margin, 0, 0)

                    // Critical part.
                    scroll_frame?.layoutParams = layoutParams

                    // Start transition.
                    startPostponedEnterTransition()
          }
}
</code>```

Body:
Here is the context: I have a Activity with complex layout to which I want to transition using relatively complex Transitions. The catch is that I need to position one view (scroll_frame) below the image (I can't use XML), so I need to know it's height. It works fine the first time, however after some number of going back and forth between Activities image's height is suddenly zero (caching, race conditions?)

Here is the snippet of onCreate:

    super.onCreate(savedInstanceState)
    postponeEnterTransition()
    setContentView(R.layout.some_id)

    // ... non-essential stuff.

    Glide.with(this)
            .load([some resource id])
            .into(object : SimpleTarget<Drawable>() {
                override fun onResourceReady(d: Drawable?, t: Transition<in Drawable>?) {
                    // Prepare image.
                    image.setImageDrawable(d)

                    val margin = Math.max(image.measuredHeight, 0)

                    // ... non-essential stuff

                    layoutParams.setMargins(0, margin, 0, 0)

                    // Critical part.
                    scroll_frame?.layoutParams = layoutParams

                    // Start transition.
                    startPostponedEnterTransition()
                }
            })

Body:
that's because your view isn't set yet:

use this:

image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            public void onGlobalLayout() {
             //don't forget to remove the listener to prevent being called again by future layout events:
                image.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            val margin = Math.max(image.measuredHeight, 0)

                    // ... non-essential stuff

                    layoutParams.setMargins(0, margin, 0, 0)

                    // Critical part.
                    scroll_frame?.layoutParams = layoutParams

                    // Start transition.
                    startPostponedEnterTransition()
          }
}


问:
Javascript adding variable to a regular expression
I've written the following function in Typescript:

```<code>public searchPosts(keyword ? : string): Post[] {
  return this._posts.filter(function(post) {
    if (post.title.search(new RegExp('money', 'gi')) >= 0) {
      return post;
    }
  });
}
</code>```

It's working just fine but, I need to make it a little dynamic so that instead of hardcoded value i.e. money, I can put my keyword variable in RegExp (new RegExp(keyword, 'gi')). But doing so does not return anything even for 'money' as a keyword.

Any ideas on what I'm doing wrong here?

答:
This is how it should work

  var keyword = '345';
  var f = ['1234', '3456'].filter(function(post) {
    return (post.search(new RegExp(keyword, 'gi')) >= 0);
  });

  console.log(f);```
</div>
</div>
</p>

<p>This is your function in pure JS
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var posts = [{title: '1234'}, {title: '3456'}];

function searchPosts (keyword) {
  return posts.filter(function(post) {
    return (post.title.search(new RegExp(keyword, 'gi')) >= 0);
  });
}

console.log(searchPosts('345'));</code>```

If this doesnt work, the problem is somewhere else ;].

Body:
I've written the following function in Typescript:

public searchPosts(keyword ? : string): Post[] {
  return this._posts.filter(function(post) {
    if (post.title.search(new RegExp('money', 'gi')) >= 0) {
      return post;
    }
  });
}

It's working just fine but, I need to make it a little dynamic so that instead of hardcoded value i.e. money, I can put my keyword variable in RegExp (new RegExp(keyword, 'gi')). But doing so does not return anything even for 'money' as a keyword.

Any ideas on what I'm doing wrong here?

Body:
This is how it should work

  var keyword = '345';
  var f = ['1234', '3456'].filter(function(post) {
    return (post.search(new RegExp(keyword, 'gi')) >= 0);
  });

  console.log(f);

This is your function in pure JS

var posts = [{title: '1234'}, {title: '3456'}];

function searchPosts (keyword) {
  return posts.filter(function(post) {
    return (post.title.search(new RegExp(keyword, 'gi')) >= 0);
  });
}

console.log(searchPosts('345'));

If this doesnt work, the problem is somewhere else ;].


问:
Operation not permitted - /usr/bin/update_rubygems
When I execute on osx El Capitan:

```<code>sudo gem update --system
</code>```

I got the error:

```<code>Updating rubygems-update
ERROR:  While executing gem ... (Errno::EPERM)
    Operation not permitted - /usr/bin/update_rubygems
</code>```

答:
I also encountered this problem when upgrading cocopods, my operating system is macOS Sierra , ruby version is 2.0.0.The following way to solve my problem.

Through the homebrew upgrade your ruby version.

brew upgrade ruby

If you fail to update ruby, this link can help you.

https://github.com/Homebrew/legacy-homebrew/issues/49895

Body:
When I execute on osx El Capitan:

sudo gem update --system

I got the error:

Updating rubygems-update
ERROR:  While executing gem ... (Errno::EPERM)
    Operation not permitted - /usr/bin/update_rubygems


问:
Reinstall libprotobuf.so files in /usr/lib/x86_64-linux-gnu
While encountering problems updating protobuf to 3.1 I foolishly ended up removing the libprotbuf* files in /usr/lib/x86_64-linux-gnu

Fortunately Protoc --version now outputs "libprotoc 3.1.0", but I am now trying to get the libprotobuf.so files back. When trying to use things that link to protobuf like matplotlib.pyplot I get an error like

** (process:15246): WARNING **: Failed to load shared library 'libgdk-3.so.0' referenced by the typelib: libprotobuf-lite.so.9: cannot open shared object file: No such file or directory

I have been able to reinstall some of libprotobuf files but the .so files are still missing.

```<code>$ ll /usr/lib/x86_64-linux-gnu/libprotobuf*

-rw-r--r-- 1 root root 2.3M Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf.a
-rw-r--r-- 1 root root 387K Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf-lite.a
lrwxrwxrwx 1 root root   25 Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf-lite.so -> libprotobuf-lite.so.9.0.1
lrwxrwxrwx 1 root root   20 Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf.so -> libprotobuf.so.9.0.1
</code>```

Anyone know a way to recover the protobuf.so.9.0.1 and libprotobuf-lite.so.9.0.1 files in ubuntu 16.04?

答: Build Protobuf 2.6.1 version. After building this version it will create libprotobuf.so.9.0.1 and libprotobuf-lite.so.9.0.1.

Body:
While encountering problems updating protobuf to 3.1 I foolishly ended up removing the libprotbuf* files in /usr/lib/x86_64-linux-gnu

Fortunately Protoc --version now outputs "libprotoc 3.1.0", but I am now trying to get the libprotobuf.so files back. When trying to use things that link to protobuf like matplotlib.pyplot I get an error like

** (process:15246): WARNING **: Failed to load shared library 'libgdk-3.so.0' referenced by the typelib: libprotobuf-lite.so.9: cannot open shared object file: No such file or directory

I have been able to reinstall some of libprotobuf files but the .so files are still missing.

$ ll /usr/lib/x86_64-linux-gnu/libprotobuf*

-rw-r--r-- 1 root root 2.3M Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf.a
-rw-r--r-- 1 root root 387K Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf-lite.a
lrwxrwxrwx 1 root root   25 Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf-lite.so -> libprotobuf-lite.so.9.0.1
lrwxrwxrwx 1 root root   20 Oct 23  2015 /usr/lib/x86_64-linux-gnu/libprotobuf.so -> libprotobuf.so.9.0.1

Anyone know a way to recover the protobuf.so.9.0.1 and libprotobuf-lite.so.9.0.1 files in ubuntu 16.04?


问:
Contact Form 7 Plugin (Wordpress) - Catch date from page
I want to insert a contact form on an event, so the user can register to that event. I don't want to generate a contact form for each event, so my idea is to catch the date from a site element

Date:

```<code><span class="ecwd-event-date" itemprop="startDate" content="2017-06-22T18:00">                                        22.06.2017 18:00  - 13.07.2017 21:30                                 </span>
</code>```

Subject:

```<code><h1 itemprop="name" class="ecwd-events-single-event-title summary entry-title">subject</h1>
</code>```

Is that possible?

答: Might be easier to use this plugin https://wordpress.org/plugins/cf7-database/ . This will let you keep a db record of the submission with a timestamp. Rather than the form generating the timestamp, the DB will generate it when the user submits the form.</p>

Body:
I want to insert a contact form on an event, so the user can register to that event. I don't want to generate a contact form for each event, so my idea is to catch the date from a site element

Date:

                                        22.06.2017 18:00  - 13.07.2017 21:30

Subject:

subject

Is that possible?


答:
Hopes this help u..</p>

```<code>$("#repeatPw").keyup(function(){
  jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data :{
            password1: $("#Password").val(),
            password2: $("#repeatPw").val(),
            },
    type: "POST",
    success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
  });
});
</code>```

Title: Jquery Ajax Post array of input data

Body:
Hopes this help u..

$("#repeatPw").keyup(function(){
  jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data :{
            password1: $("#Password").val(),
            password2: $("#repeatPw").val(),
            },
    type: "POST",
    success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
  });
});


问:
Ajax Autocomplete Webservice Call - Service Method, am I calling this correctly?
Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:

```<code>ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"
</code>```

where subCategory is a page property that looks like this:

```<code>protected SubCategory subCategory
{
    get
    {
        var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
        return subCategory;
    }
}
</code>```

答:
I dont' think calling a Generic Method on a webservice is possible.

If you look at the service description of two identical methods, one generic, one not:

```<code>[WebMethod]
public string[] GetSearchList(string prefixText, int count)
{
}

[WebMethod]
public string[] GetSearchList2<T>(string prefixText, int count)
{
}
</code>```

They are identical.  It appears that both SOAP 1.x and HTTP POST do not allow this type of operation.

OwnerDisplayName: Sara Chipps

Body:
Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:

ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"

where subCategory is a page property that looks like this:

protected SubCategory subCategory
{
    get
    {
        var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
        return subCategory;
    }
}

Body:
I dont' think calling a Generic Method on a webservice is possible.

If you look at the service description of two identical methods, one generic, one not:

[WebMethod]
public string[] GetSearchList(string prefixText, int count)
{
}

[WebMethod]
public string[] GetSearchList2<T>(string prefixText, int count)
{
}

They are identical.  It appears that both SOAP 1.x and HTTP POST do not allow this type of operation.

OwnerDisplayName: blarggstar

ContentLicense: CC BY-SA 2.5


答:
Try like this</p>

```<code>$("#repeatPw").keyup(function(){
jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data: {'password1' : $("#Password").val(), 'password2' : $("#repeatPw").val() },
    type: "POST",
    success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
});
 });
</code>```

Title: Jquery Ajax Post array of input data

Body:
Try like this

$("#repeatPw").keyup(function(){
jQuery.ajax({
    url: "System/Javascript/Functions/checkPasswords.php",
    data: {'password1' : $("#Password").val(), 'password2' : $("#repeatPw").val() },
    type: "POST",
    success: function(data) {
        $("#passwordMatch").html(data);
    },
    error: function(data) {}
});
 });


问:
How to recompile framework created using carthage with latest xcode version?
I created some frameworks on my own using Xcode 8.2.1 with Carthage package manager. When I try to use this framework in Xcode 8.3.3 I am getting the error below:

Module compiled with Swift 3.0.2 cannot be imported in Swift 3.1

I tried rebuilding the created framework using Xcode 8.3.3 and did carthage update in my existing project in which I am trying to use the framework. Still it throws the same error. Do I need to create the framework again using Xcode 8.3.3 in order to get rid of this error? Or is there a way to re-compile the existing framework?

答:
The problem was my default Xcode selection path was set to Xcode 8.2.1.

So every time I built the framework using carthage build --no-skip-current, it was building with Xcode 8.2.1.

I changed my Xcode selection path to point to Xcode 8.3.3 by using the following command in Terminal:

```<code>sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
</code>```

Now the framework has been updated and I am able to access my framework in Xcode 8.3.3 without any issue.

Body:
The problem was my default Xcode selection path was set to Xcode 8.2.1.

So every time I built the framework using carthage build --no-skip-current, it was building with Xcode 8.2.1.

I changed my Xcode selection path to point to Xcode 8.3.3 by using the following command in Terminal:

sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer

Now the framework has been updated and I am able to access my framework in Xcode 8.3.3 without any issue.


问:
how to reuse JDBC Statements and automatic close back resultsets?
iam working on an project that will have many statements connected to DB
and i want to reuse statements instead of create new one every connect
and the most important thing that i don't want to close every resultset after use

i want to close back resultsets on statement before reuse it

my code look like this

```<code>ArrayList<Statement> BackStatements = new ArrayList();
int lastStatementIndex = 0;

private Statement GetStatement() throws SQLException {
    Statement SM;
    int MaxStatements = 5;
    if (BackStatements.size() < MaxStatements) {
        SM = Connection.createStatement();
        BackStatements.add(SM);
        lastStatementIndex = BackStatements.size() - 1;
    } else {
        lastStatementIndex = lastStatementIndex + 1;
        if (lastStatementIndex == MaxStatements) {
            lastStatementIndex = 0;
        }
        SM = BackStatements.get(lastStatementIndex);
     /// i want to close resultset generated by SM now and i do this before return this SM
        SM.getResultSet().close();

    }

    System.out.println("Last Index:" + lastStatementIndex + "---- Size:" + BackStatements.size());
    return SM;
}
</code>```

but this method return this error by logger

```<code>Caused by: java.sql.SQLException: ResultSet already requested
</code>```

答:
That's bad idea in general. Statement is an interface, actual class can be anything JDBC driver returns.
In general you can not reuse one statement class for another type. For example,
CallableStatement and PreparedStatement (for oracle JDBC) are incompatible.

As for ResultSet, closing it releases database cursor, at least in some scenarios. Postpone of resultSet.close() can negatively affect DB server capacity.

In general, if your JDBC driver supports connection pooling, it's the way to go. In general network round-trip is way more costful than creation of statements.

Body:
iam working on an project that will have many statements connected to DB
and i want to reuse statements instead of create new one every connect
and the most important thing that i don't want to close every resultset after use

i want to close back resultsets on statement before reuse it

my code look like this

ArrayList<Statement> BackStatements = new ArrayList();
int lastStatementIndex = 0;

private Statement GetStatement() throws SQLException {
    Statement SM;
    int MaxStatements = 5;
    if (BackStatements.size() < MaxStatements) {
        SM = Connection.createStatement();
        BackStatements.add(SM);
        lastStatementIndex = BackStatements.size() - 1;
    } else {
        lastStatementIndex = lastStatementIndex + 1;
        if (lastStatementIndex == MaxStatements) {
            lastStatementIndex = 0;
        }
        SM = BackStatements.get(lastStatementIndex);
     /// i want to close resultset generated by SM now and i do this before return this SM
        SM.getResultSet().close();

    }

    System.out.println("Last Index:" + lastStatementIndex + "---- Size:" + BackStatements.size());
    return SM;
}

but this method return this error by logger

Caused by: java.sql.SQLException: ResultSet already requested


答:
Addressing only the one another problem:

```<code>$ cat program.awk
BEGIN { FS="," }
NR==FNR {                              # file1
    if(substr($0,length($0),1)==2) {   # process only records ending in 2
        a[$0 " B"]                     # create B and ...
        a[$0 " F"]                     # ... F entries to a hash
    }
    next
}
{                                      # file2
    delete a[$1 $2 $3 $4 $5 2 " " $6]  # delete the ones we meet (* below)
}
END {                                  # in the end
    for(i in a)                        # the leftovers (in no order particular)
        print i                        # shall be outputed
}
</code>```

* The sample data is such that every record in file2 will be removed from the a hash, not just the ones that have B and F records.

Run it:

```<code>$ awk -f program.awk file1 file2
2017042100000000010000000943678177700000010000000000026622 B
2017042100000000010000000943678177700000012855000000026632 B
2017042100000000010000000943678177700000012855000000026632 F
</code>```

Title: Comparing specific column from a file to another file with specified number of times

Body:
I have 2 files say file1.txt & file2.txt.

file1.txt:

2017042100000000010000000943678177700000000819900000026572
2017042100000000010000000943678177700000003500000000026581
2017042100000000010000000943678177700000013450000000026591
2017042100000000010000000943678177700000011500000000026601
2017042100000000010000000943678177700000010000000000026611
2017042100000000010000000943678177700000010000000000026622
2017042100000000010000000943678177700000012855000000026632

file2.txt

20170421,0000000001,00000009436781777,000000008199,0000002657,F,3,img_F1_1.tiff
20170421,0000000001,00000009436781777,000000008199,0000002657,B,3,img_F1_1.tiff
20170421,0000000001,00000009436781777,000000035000,0000002658,F,8,img_F1_2.tiff
20170421,0000000001,00000009436781777,000000134500,0000002659,F,1,img_F1_3.tiff
20170421,0000000001,00000009436781777,000000115000,0000002660,F,2,img_F1_4.tiff
20170421,0000000001,00000009436781777,000000100000,0000002661,F,1,img_F1_5.tiff
20170421,0000000001,00000009436781777,000000100000,0000002662,F,8,img_F1_6.tiff

I have to compare entries of file1.txt(except last character) to first 5 columns of file2.txt. If it matches then I have to store entries of file2.txt to another file say matched.txt. If it doesn't then I have to store entries of file1.txt in another file say unmatched.txt. which works for me with below commands.

awk -F',' 'FILENAME=="file1.txt" {A[substr($1, 1, length($1)-1)]=substr($1, 1, length($1)-1)} FILENAME=="file2.txt"{if(A[$1$2$3$4$5]){print}}' file1.txt file2.txt > matched.txt

Now, I have one another problem:

If entries of file1.txt(except last character) matches to first 5 columns of file2.txt then it has to check last character of file1.txt(that will be either 1 or 2). if last digit/character is 2 then it has to search 2  same entries(first 5 columns) in file2.txt where 6th columns must have 'F' for first entries and 'B' for second entries.
eg:
file1.txt

2017042100000000010000000943678177700000000819900000026572

Here last digit is 2, then we must find 2 entries in file2.txt

file2.txt

20170421,0000000001,00000009436781777,000000008199,0000002657,F,3,img_F1_1.tiff
20170421,0000000001,00000009436781777,000000008199,0000002657,B,3,img_F1_1.tiff

which has both entries 'F' & 'B'.

If we find LESS THAN 2 entries then we have to store missing entries into file say missing.txt. My command is working for 2 entries or 0 entries but for only one entry not working.

Expected Output:

missing.txt

2017042100000000010000000943678177700000010000000000026622 'B'
2017042100000000010000000943678177700000012855000000026632 'F'
2017042100000000010000000943678177700000012855000000026632 'B'

Body:
Addressing only the one another problem:

$ cat program.awk
BEGIN { FS="," }
NR==FNR {                              # file1
    if(substr($0,length($0),1)==2) {   # process only records ending in 2
        a[$0 " B"]                     # create B and ...
        a[$0 " F"]                     # ... F entries to a hash
    }
    next
}
{                                      # file2
    delete a[$1 $2 $3 $4 $5 2 " " $6]  # delete the ones we meet (* below)
}
END {                                  # in the end
    for(i in a)                        # the leftovers (in no order particular)
        print i                        # shall be outputed
}

* The sample data is such that every record in file2 will be removed from the a hash, not just the ones that have B and F records.

Run it:

$ awk -f program.awk file1 file2
2017042100000000010000000943678177700000010000000000026622 B
2017042100000000010000000943678177700000012855000000026632 B
2017042100000000010000000943678177700000012855000000026632 F


问:
Performance for appending large element/datasets to the dom
I am appending large amounts of table row elements at a time and experiencing some major bottlenecks.  At the moment I am using jQuery, but i'm open to a javascript based solution if it gets the job done.

I have the need to append anywhere from 0-100 table rows at a given time (it's actually potentially more, but I'll be paginating anything over 100).

Right now I am appending each table row individually to the dom...

```<code>loop {
  ..build html str...
  $("#myTable").append(row);
}
</code>```

Then I fade them all in at once

```<code>$("#myTable tr").fadeIn();
</code>```

There are a couple things to consider here...

1) I am binding data to each individual table row, which is why i switched from a mass append to appending individual rows in the first place.

2) I really like the fade effect.  Although not essential to the application I am very big on aesthetics and animations (that of course don't distract from the use of the application).  There simply has to be a good way to apply a modest fade effect to larger amounts of data.

(edit)
3) A major reason for me approaching this in the smaller chunk/recursive way is I need to bind specific data to each row.  Am I binding my data wrong? Is there a better way to keep track of this data than binding it to their respective tr?

Is it better to apply affects/dom manipulations in large chunks or smaller chunks in recursive functions?

Are there situations where the it's better to do one or the other? If so, what are the indicators for choosing the appropriate method?

答:
i suspect your performance problems are because you are modifying the DOM multiple times, in your loop.

Instead, try modifying it once after you get all your rows.  Browsers are really good at innerHTML replaces.  Try something like

```<code>$("#myTable").html("all the rows dom here");
</code>```

note you might have to play with the exact selector to use, to get the dom in the correct place.  But the main idea is use innerHTML, and use it as few times as possible.

Body:
I am appending large amounts of table row elements at a time and experiencing some major bottlenecks.  At the moment I am using jQuery, but i'm open to a javascript based solution if it gets the job done.

I have the need to append anywhere from 0-100 table rows at a given time (it's actually potentially more, but I'll be paginating anything over 100).

Right now I am appending each table row individually to the dom...

loop {
  ..build html str...
  $("#myTable").append(row);
}

Then I fade them all in at once

$("#myTable tr").fadeIn();

There are a couple things to consider here...

1) I am binding data to each individual table row, which is why i switched from a mass append to appending individual rows in the first place.

2) I really like the fade effect.  Although not essential to the application I am very big on aesthetics and animations (that of course don't distract from the use of the application).  There simply has to be a good way to apply a modest fade effect to larger amounts of data.

(edit)
3) A major reason for me approaching this in the smaller chunk/recursive way is I need to bind specific data to each row.  Am I binding my data wrong? Is there a better way to keep track of this data than binding it to their respective tr?

Is it better to apply affects/dom manipulations in large chunks or smaller chunks in recursive functions?

Are there situations where the it's better to do one or the other? If so, what are the indicators for choosing the appropriate method?

Body:
i suspect your performance problems are because you are modifying the DOM multiple times, in your loop.

Instead, try modifying it once after you get all your rows.  Browsers are really good at innerHTML replaces.  Try something like

$("#myTable").html("all the rows dom here");

note you might have to play with the exact selector to use, to get the dom in the correct place.  But the main idea is use innerHTML, and use it as few times as possible.


问:
md-autocomplete dropdown not updating simultaneously with the md-search-text-change call
I show a dropdown using md-autocomplete, and also I have typeahead APIs which should get called once I start typing in the input box. The problem is that, it is calling the typeahead API and fetching the results and setting it to a variable in JS controller, but the dropdown in html shows the filtered dropdown results only if I type the next character in the input box or close and re-click on the dropdown. How to take the changes in the dropdown results as immediately as someone starts typing in? I am using md-search-text-change to get the text input and call the respective function.

HTML Code:

```<code><md-autocomplete flex-gt-xs md-no-cache="true"
                 required placeholder="Choose a Value"
                 md-selected-item="vm.item.value"
                 md-search-text-change="vm.searchTextChange(vm.valueSearchText)"
                 md-search-text="vm.valueSearchText"
                 md-items="value in vm.item.valueList"
                 md-item-text="value.id"
                 md-min-length="0">
</code>```

JS Controller:

```<code>function searchTextChange(text) {
  service.getValueList(text).then(function (values) {
    vm.item.valueList = values;
  });
}

function getValues() {
  service.getValueList().then(function (values) {
    vm.item.valueList = values;
  });
}
</code>```

So, the valueList is updated with the correct values from the API call, but I can't see the latest valueList in dropdown and instead see the immediate older values in the dropdown. Please help.

答:
Try the following

HTML:

```<code><md-autocomplete flex-gt-xs md-no-cache="true"
             required placeholder="Choose a Value"
             md-selected-item="vm.item.value"
             md-search-text-change="vm.searchTextChange(vm.valueSearchText)"
             md-search-text="vm.valueSearchText"
             md-items="value in vm.searchTextChange(vm.valueSearchText)"
             md-item-text="value.id"
             md-min-length="0">
</code>```

JS Controller:

```<code>function searchTextChange(text) {
  service.getValueList(text).then(function (values) {
    return values;
 });
}
</code>```

Body:
I show a dropdown using md-autocomplete, and also I have typeahead APIs which should get called once I start typing in the input box. The problem is that, it is calling the typeahead API and fetching the results and setting it to a variable in JS controller, but the dropdown in html shows the filtered dropdown results only if I type the next character in the input box or close and re-click on the dropdown. How to take the changes in the dropdown results as immediately as someone starts typing in? I am using md-search-text-change to get the text input and call the respective function.

HTML Code:

<md-autocomplete flex-gt-xs md-no-cache="true"
                 required placeholder="Choose a Value"
                 md-selected-item="vm.item.value"
                 md-search-text-change="vm.searchTextChange(vm.valueSearchText)"
                 md-search-text="vm.valueSearchText"
                 md-items="value in vm.item.valueList"
                 md-item-text="value.id"
                 md-min-length="0">

JS Controller:

function searchTextChange(text) {
  service.getValueList(text).then(function (values) {
    vm.item.valueList = values;
  });
}

function getValues() {
  service.getValueList().then(function (values) {
    vm.item.valueList = values;
  });
}

So, the valueList is updated with the correct values from the API call, but I can't see the latest valueList in dropdown and instead see the immediate older values in the dropdown. Please help.

Body:
Try the following

HTML:

<md-autocomplete flex-gt-xs md-no-cache="true"
             required placeholder="Choose a Value"
             md-selected-item="vm.item.value"
             md-search-text-change="vm.searchTextChange(vm.valueSearchText)"
             md-search-text="vm.valueSearchText"
             md-items="value in vm.searchTextChange(vm.valueSearchText)"
             md-item-text="value.id"
             md-min-length="0">

JS Controller:

function searchTextChange(text) {
  service.getValueList(text).then(function (values) {
    return values;
 });
}