问:
Getting Selenium-WebDriver Example to work
I am completely new to Selenium, and just want to install & run the example to begin with, as described here: http://www.seleniumhq.org/docs/03_webdriver.jsp
I have installed the Java SE 9.0.1 JDK, Eclipse IDE for Java Developers and Apache Maven.
Next I set up a pom.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>MySel20Proj</groupId>
        <artifactId>MySel20Proj</artifactId>
        <version>1.0</version>
        <dependencies>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-server</artifactId>
                <version>3.0.1</version>
            </dependency>
        </dependencies>
</project>
</code>```

Then I did mvn clean install

Then I imported the Maven project into Eclipse.

I also installed the m2eclipse plugin.

I called the project MySel20Proj.

Here, I created a class: Selenium2Example.java

Here, i pasted the code from the manual:

```<code>package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium2Example {
     public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");
        // Alternatively the same thing can be done like this
        // driver.navigate().to("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });

        // Should see: "cheese! - Google Search"
        System.out.println("Page title is: " + driver.getTitle());

        //Close the browser
        driver.quit();
    }

}
</code>```

The instructions seem to stop here. What do I do next? How do I run it?

Update 11/12/2017

I am now making some progress with this. The project is finally running, although it is not yet performing the test.

This is my latest POM file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
      </properties>
    <modelVersion>4.0.0</modelVersion>
    <groupId>MySel20Proj</groupId>
    <artifactId>MySel20Proj</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.8.1</version>
        </dependency>
    </dependencies>
     <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20.1</version>
            <configuration>
              <includes>
                <include>Selenium2Example.java</include>
              </includes>
            </configuration>
          </plugin>
        </plugins>
      </build>
</project>
</code>```

This is the java code:

```<code>//package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium2Example {
 public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        System.out.println("Hello world!");
        System.setProperty("webdriver.gecko.driver",
"C:\\Users\\sstaple\\Downloads\\geckodriver\\geckodriver.exe");

        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");
        // Alternatively the same thing can be done like this
        // driver.navigate().to("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the
element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>
() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });

        // Should see: "cheese! - Google Search"
        System.out.println("Page title is: " + driver.getTitle());

        //Close the browser
        driver.quit();
    }

}
</code>```

This was the result of running mvn install in the Command Prompt:

```<code>> C:\Users\sstaple\eclipse-workspace\MySel20Proj>mvn install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MySel20Proj 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MySel20Proj ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ MySel20Proj ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ MySel20Proj ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ MySel20Proj ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.20.1:test (default-test) @ MySel20Proj ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running Selenium2Example
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s - in Selenium2Example
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ MySel20Proj ---
[INFO] Building jar: C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ MySel20Proj ---
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.jar
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\pom.xml to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.089 s
[INFO] Finished at: 2017-12-11T11:31:42Z
[INFO] Final Memory: 16M/55M
[INFO] ------------------------------------------------------------------------
</code>```

Update 2 - 11/12/2017

Had to add a bunch of Depencies to the pom file to get it to compile clean:

```<code><dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.8.1</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>3.2.4</version>
    </dependency>
    <dependency>
        <groupId>com.codeborne</groupId>
        <artifactId>phantomjsdriver</artifactId>
        <version>1.3.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.netty/netty -->
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty</artifactId>
        <version>3.5.7.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform -->
    <dependency>
        <groupId>net.java.dev.jna</groupId>
        <artifactId>jna-platform</artifactId>
        <version>4.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sourceforge.cssparser/cssparser -->
    <dependency>
        <groupId>net.sourceforge.cssparser</groupId>
        <artifactId>cssparser</artifactId>
        <version>0.9.20</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit-core-js -->
    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>htmlunit-core-js</artifactId>
        <version>2.23</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit -->
    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>htmlunit</artifactId>
        <version>2.23</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/neko-htmlunit -->
    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>neko-htmlunit</artifactId>
        <version>2.23</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-io -->
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-io</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-util -->
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-util</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.eclipse.jetty.websocket/websocket-api -->
    <dependency>
        <groupId>org.eclipse.jetty.websocket</groupId>
        <artifactId>websocket-api</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.eclipse.jetty.websocket/websocket-client -->
    <dependency>
        <groupId>org.eclipse.jetty.websocket</groupId>
        <artifactId>websocket-client</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.eclipse.jetty.websocket/websocket-common -->
    <dependency>
        <groupId>org.eclipse.jetty.websocket</groupId>
        <artifactId>websocket-common</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/htmlunit-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>htmlunit-driver</artifactId>
        <version>2.23</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/jetty-repacked -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>jetty-repacked</artifactId>
        <version>9.2.13.v20160825</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-api -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-api</artifactId>
        <version>3.8.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-chrome-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-edge-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-edge-driver</artifactId>
        <version>3.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-firefox-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>3.8.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-ie-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-ie-driver</artifactId>
        <version>3.8.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.8.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-opera-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-opera-driver</artifactId>
        <version>3.8.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-remote-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-remote-driver</artifactId>
        <version>3.8.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-safari-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-safari-driver</artifactId>
        <version>3.0.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-support -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-support</artifactId>
        <version>3.8.1</version>
    </dependency>
</code>```

Still does nothing at all:

```<code>> C:\Users\sstaple\eclipse-workspace\MySel20Proj>mvn install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MySel20Proj 1.0
[INFO] ------------------------------------------------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/com/google/guava/guava/21.0/guava-21.0.jar
Downloaded from central: https://repo.maven.apache.org/maven2/com/google/guava/guava/21.0/guava-21.0.jar (2.5 MB at 2.6 MB/s)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MySel20Proj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ MySel20Proj ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ MySel20Proj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ MySel20Proj ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.20.1:test (default-test) @ MySel20Proj ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running Selenium2Example
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s - in Selenium2Example
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ MySel20Proj ---
[INFO] Building jar: C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ MySel20Proj ---
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.jar
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\pom.xml to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.032 s
[INFO] Finished at: 2017-12-11T13:56:34Z
[INFO] Final Memory: 19M/63M
[INFO] ------------------------------------------------------------------------
</code>```

答:
As per the code block you have shared everything looks fine. But again as you mentioned org.seleniumhq.selenium selenium-server 3.0.1 you have to mandatory download geckodriver binary from this repository and place it in your system. Next in your code block you need to mention as follows :

```<code>System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
</code>```

Execution Steps :

Save the Selenium2Example.java and the pom.xml file

In the Package Explorer, right click on pom.xml, select Run As and select Maven clean

In the Package Explorer, right click on pom.xml, select Run As and select Maven install.

In the Package Explorer, right click on pom.xml, select Run As and select Maven test.

Update 1

As you are seeing the error as selection does not contain a main type, ensure that your .java file is within \ProjectSpace\src\test\java\.

Update 2

As you still see No sources to compile, as a last resort, Clean all of your Projects within your IDE, Close the IDE, Delete the ~\.m2 (MAVEN_HOME) sub-directory from the system forcefully. Take a System Reboot and execute your Test. Additionally from the command line even you can do a mvn clean, mvn install and mvn test.

Body:
I am completely new to Selenium, and just want to install & run the example to begin with, as described here: http://www.seleniumhq.org/docs/03_webdriver.jsp
I have installed the Java SE 9.0.1 JDK, Eclipse IDE for Java Developers and Apache Maven.
Next I set up a pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>MySel20Proj</groupId>
        <artifactId>MySel20Proj</artifactId>
        <version>1.0</version>
        <dependencies>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-server</artifactId>
                <version>3.0.1</version>
            </dependency>
        </dependencies>
</project>

Then I did mvn clean install

Then I imported the Maven project into Eclipse.

I also installed the m2eclipse plugin.

I called the project MySel20Proj.

Here, I created a class: Selenium2Example.java

Here, i pasted the code from the manual:

package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium2Example {
     public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");
        // Alternatively the same thing can be done like this
        // driver.navigate().to("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });

        // Should see: "cheese! - Google Search"
        System.out.println("Page title is: " + driver.getTitle());

        //Close the browser
        driver.quit();
    }

}

The instructions seem to stop here. What do I do next? How do I run it?

Update 11/12/2017

I am now making some progress with this. The project is finally running, although it is not yet performing the test.

This is my latest POM file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
      </properties>
    <modelVersion>4.0.0</modelVersion>
    <groupId>MySel20Proj</groupId>
    <artifactId>MySel20Proj</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.8.1</version>
        </dependency>
    </dependencies>
     <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20.1</version>
            <configuration>
              <includes>
                <include>Selenium2Example.java</include>
              </includes>
            </configuration>
          </plugin>
        </plugins>
      </build>
</project>

This is the java code:

//package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium2Example {
 public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        System.out.println("Hello world!");
        System.setProperty("webdriver.gecko.driver",
"C:\\Users\\sstaple\\Downloads\\geckodriver\\geckodriver.exe");

        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");
        // Alternatively the same thing can be done like this
        // driver.navigate().to("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the
element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>
() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });

        // Should see: "cheese! - Google Search"
        System.out.println("Page title is: " + driver.getTitle());

        //Close the browser
        driver.quit();
    }

}

This was the result of running mvn install in the Command Prompt:

> C:\Users\sstaple\eclipse-workspace\MySel20Proj>mvn install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MySel20Proj 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MySel20Proj ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ MySel20Proj ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ MySel20Proj ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ MySel20Proj ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.20.1:test (default-test) @ MySel20Proj ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running Selenium2Example
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s - in Selenium2Example
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ MySel20Proj ---
[INFO] Building jar: C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ MySel20Proj ---
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.jar
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\pom.xml to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.089 s
[INFO] Finished at: 2017-12-11T11:31:42Z
[INFO] Final Memory: 16M/55M
[INFO] ------------------------------------------------------------------------

Update 2 - 11/12/2017

Had to add a bunch of Depencies to the pom file to get it to compile clean:

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.8.1</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>3.2.4</version>
    </dependency>
    <dependency>
        <groupId>com.codeborne</groupId>
        <artifactId>phantomjsdriver</artifactId>
        <version>1.3.0</version>
    </dependency>

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.3.1</version>
    </dependency>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty</artifactId>
        <version>3.5.7.Final</version>
    </dependency>

    <dependency>
        <groupId>net.java.dev.jna</groupId>
        <artifactId>jna-platform</artifactId>
        <version>4.1.0</version>
    </dependency>

    <dependency>
        <groupId>net.sourceforge.cssparser</groupId>
        <artifactId>cssparser</artifactId>
        <version>0.9.20</version>
    </dependency>

    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>htmlunit-core-js</artifactId>
        <version>2.23</version>
    </dependency>

    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>htmlunit</artifactId>
        <version>2.23</version>
    </dependency>

    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>neko-htmlunit</artifactId>
        <version>2.23</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.4</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.4</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.2</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-io</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-util</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jetty.websocket</groupId>
        <artifactId>websocket-api</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jetty.websocket</groupId>
        <artifactId>websocket-client</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jetty.websocket</groupId>
        <artifactId>websocket-common</artifactId>
        <version>9.2.15.v20160210</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>htmlunit-driver</artifactId>
        <version>2.23</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>jetty-repacked</artifactId>
        <version>9.2.13.v20160825</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-api</artifactId>
        <version>3.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-edge-driver</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>3.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-ie-driver</artifactId>
        <version>3.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-opera-driver</artifactId>
        <version>3.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-remote-driver</artifactId>
        <version>3.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-safari-driver</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-support</artifactId>
        <version>3.8.1</version>
    </dependency>

Still does nothing at all:

> C:\Users\sstaple\eclipse-workspace\MySel20Proj>mvn install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MySel20Proj 1.0
[INFO] ------------------------------------------------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/com/google/guava/guava/21.0/guava-21.0.jar
Downloaded from central: https://repo.maven.apache.org/maven2/com/google/guava/guava/21.0/guava-21.0.jar (2.5 MB at 2.6 MB/s)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MySel20Proj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ MySel20Proj ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ MySel20Proj ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ MySel20Proj ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.20.1:test (default-test) @ MySel20Proj ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running Selenium2Example
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s - in Selenium2Example
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ MySel20Proj ---
[INFO] Building jar: C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ MySel20Proj ---
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\target\MySel20Proj-1.0.jar to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.jar
[INFO] Installing C:\Users\sstaple\eclipse-workspace\MySel20Proj\pom.xml to C:\Users\sstaple\.m2\repository\MySel20Proj\MySel20Proj\1.0\MySel20Proj-1.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.032 s
[INFO] Finished at: 2017-12-11T13:56:34Z
[INFO] Final Memory: 19M/63M
[INFO] ------------------------------------------------------------------------

Body:
As per the code block you have shared everything looks fine. But again as you mentioned org.seleniumhq.selenium selenium-server 3.0.1 you have to mandatory download geckodriver binary from this repository and place it in your system. Next in your code block you need to mention as follows :

System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

Execution Steps :

Save the Selenium2Example.java and the pom.xml file

In the Package Explorer, right click on pom.xml, select Run As and select Maven clean

In the Package Explorer, right click on pom.xml, select Run As and select Maven install.

In the Package Explorer, right click on pom.xml, select Run As and select Maven test.

Update 1

As you are seeing the error as selection does not contain a main type, ensure that your .java file is within \ProjectSpace\src\test\java\.

Update 2

As you still see No sources to compile, as a last resort, Clean all of your Projects within your IDE, Close the IDE, Delete the ~\.m2 (MAVEN_HOME) sub-directory from the system forcefully. Take a System Reboot and execute your Test. Additionally from the command line even you can do a mvn clean, mvn install and mvn test.


来源: stackexchange

问:
Dynamic For Comprehensions
I'm relatively new to Scala so I'm not super confident with the language and I need your help to solve a problem. I know that the for-comprehension is just a syntactic sugar to simplify complex map/flatMap hierarchies.

Now, consider to have 3 different Range intervals, which should be combined in order to create all the possible combinations (respecting the intervals) of values.

Example:

Using the for-comprehension the problem can be solved as:

```<code>val intervalX = 1 to 5
val intervalY = 6 to 13
val intervalZ = 20 to 50
for {
  x <- intervalX;
  y <- intervalY;
  z <- intervalZ
} yield (x,y,z)
</code>```

Which is converted by the Scala compiler as:

```<code>intervalX.flatMap{x =>
    intervalY.flatMap{y =>
        intervalZ.map{z => (x,y,z)}
    }
}
</code>```

However, the problem is harder if you are given in input a variable number d of intervals. Is it possible to perform the same operation, obtaining all the possible d-tuples? I think that it could be solved using the foldLeft operation, but I am not able to write it correctly at the moment. Can you help me?

Thanks

答:
If you can live without tuples as a result then a version using foldLeft and returning lists representing combinations could be:</p>

```<code>val intervalX = 1 to 5
val intervalY = 6 to 13
val intervalZ = 20 to 50
val ranges = intervalZ :: intervalY :: intervalX :: Nil
val combos = ranges.foldLeft(Iterable[Seq[Int]](Nil)) { case (c, e) =>
   for {
      i <- e
      j <- c
   } yield i +: j
}
combos foreach { println(_) }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Dynamic For Comprehensions

Body:
I'm relatively new to Scala so I'm not super confident with the language and I need your help to solve a problem. I know that the for-comprehension is just a syntactic sugar to simplify complex map/flatMap hierarchies.

Now, consider to have 3 different Range intervals, which should be combined in order to create all the possible combinations (respecting the intervals) of values.

Example:

Using the for-comprehension the problem can be solved as:

val intervalX = 1 to 5
val intervalY = 6 to 13
val intervalZ = 20 to 50
for {
  x <- intervalX;
  y <- intervalY;
  z <- intervalZ
} yield (x,y,z)

Which is converted by the Scala compiler as:

intervalX.flatMap{x =>
    intervalY.flatMap{y =>
        intervalZ.map{z => (x,y,z)}
    }
}

However, the problem is harder if you are given in input a variable number d of intervals. Is it possible to perform the same operation, obtaining all the possible d-tuples? I think that it could be solved using the foldLeft operation, but I am not able to write it correctly at the moment. Can you help me?

Thanks

Body:
If you can live without tuples as a result then a version using foldLeft and returning lists representing combinations could be:

val intervalX = 1 to 5
val intervalY = 6 to 13
val intervalZ = 20 to 50
val ranges = intervalZ :: intervalY :: intervalX :: Nil
val combos = ranges.foldLeft(Iterable[Seq[Int]](Nil)) { case (c, e) =>
   for {
      i <- e
      j <- c
   } yield i +: j
}
combos foreach { println(_) }


问:
click event affects mouseenter and mouseleave on chrome, is it a bug?
after adding events both mouseenter and mouseleave,click the element(the times of click is uncertain)，the mouseenter and mouseleave will be triggered.

I try chrome 62.0.3202.94（32），firework，IE,and it only happened on chrome.Is it a bug of chrome，or just something wrong with my code?

The example online:http://runjs.cn/code/cbb0aw1a

the code follows there:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h4>click on the parent part,then see the console </h4>
<div class="parent" style="width: 100%;height: 100px;background-color: #ddd">
    <div class="children" style="width: 50px;height: 50px;background-color: #d9534f;cursor: pointer">
        test
    </div>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script>
    $(".parent").mouseenter(function () {
        console.log("enter")
    }).mouseleave(function () {
        console.log("leave")
    });

</script>
</html>
</code>```

答:
I can confirm the behaviour on chrome (Version 62.0.3202.94).

When clicking an element multiple times, occasionally mouseleave is fired with a relatedTarget/toElement property of "null" on the MouseEvent (screenX, screenY properties both 0).

The behaviour is random, sometimes it needs 2 subsequent clicks, sometimes more than 20. Clicking speed/rate seems irrelevant too.

By now I avoid the execution of unwanted code in my onMouseLeave(event) method by checking the relatedTarget property of the event(if "null" do nothing). Don't know if there is another useful case where relatedTarget could be null...

Body:
after adding events both mouseenter and mouseleave,click the element(the times of click is uncertain)，the mouseenter and mouseleave will be triggered.

I try chrome 62.0.3202.94（32），firework，IE,and it only happened on chrome.Is it a bug of chrome，or just something wrong with my code?

The example online:http://runjs.cn/code/cbb0aw1a

the code follows there:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

click on the parent part,then see the console

        test


问:
Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
This is the output of my gradle console please help me out to solve this error, I am unable to build my project </p>

```<code>Information:Gradle tasks [:facebook:generateDebugSources, :facebook:mockableAndroidJar, :facebook:prepareDebugUnitTestDependencies, :facebook:generateDebugAndroidTestSources, :lagaiKhai:generateDebugSources, :lagaiKhai:mockableAndroidJar, :lagaiKhai:prepareDebugUnitTestDependencies, :lagaiKhai:generateDebugAndroidTestSources]
Error:java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
Error:Execution failed for task ':lagaiKhai:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
Information:BUILD FAILED
Information:Total time: 23.24 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console
</code>```

答:
most of the time is a corrupt PNG image added recently to the project which cause this error. Check the git log and replace the file.

Sometimes menu : File > InvalidateCaches/Restart also helps

Body:
This is the output of my gradle console please help me out to solve this error, I am unable to build my project

Information:Gradle tasks [:facebook:generateDebugSources, :facebook:mockableAndroidJar, :facebook:prepareDebugUnitTestDependencies, :facebook:generateDebugAndroidTestSources, :lagaiKhai:generateDebugSources, :lagaiKhai:mockableAndroidJar, :lagaiKhai:prepareDebugUnitTestDependencies, :lagaiKhai:generateDebugAndroidTestSources]
Error:java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
Error:Execution failed for task ':lagaiKhai:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
Information:BUILD FAILED
Information:Total time: 23.24 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console


问:
Connect to Active MQ with golang
Amazon MQ (Active MQ) says it works with amqp, and there's a go package here https://github.com/streadway/amqp but when I try to Dial() I get this error

```<code>Exception (501) Reason: "Exception (501) Reason: \"frame could not be parsed\""
</code>```

I suspect it is because although this is an amqp package, and Amazon MQ accepts amqp, this is specifically a RabbitMQ amqp package... does this make sense?

Another option is STOMP, which I've tried using the example here https://github.com/go-stomp/stomp/blob/master/examples/client_test/main.go
But Dial() is giving me this super not helpful error: "invalid command"

It's embarrassing asking how to connect, but it's where I'm stuck. Thanks in advance

答:
You need an AMQP 1.0 client library.  The Qpid project at Apache maintains several different language bindings for AMQP 1.0 one of which is a Go client and is documented here and some examples here.

For the STOMP attempt it could be you are not attempting to connect to the correct port on the broker, which can lead to clients giving you that error.  The STOMP port is typically 61613, and AMQP is 5672.

Title: Connect to Active MQ with golang

Body:
Amazon MQ (Active MQ) says it works with amqp, and there's a go package here https://github.com/streadway/amqp but when I try to Dial() I get this error

Exception (501) Reason: "Exception (501) Reason: \"frame could not be parsed\""

I suspect it is because although this is an amqp package, and Amazon MQ accepts amqp, this is specifically a RabbitMQ amqp package... does this make sense?

Another option is STOMP, which I've tried using the example here https://github.com/go-stomp/stomp/blob/master/examples/client_test/main.go
But Dial() is giving me this super not helpful error: "invalid command"

It's embarrassing asking how to connect, but it's where I'm stuck. Thanks in advance


问:
In GWT I get could not get type signature for class Exception
I define a class with Generic type like below in GWT. when I extend this class with a type or specify a type for this class everything is okay, but at runtime I get "could not get type signature for class Filter" message.

```<code>@SuppressWarnings("serial")
public class Filter<T extends Serializable> implements Serializable {
     private FilterInfo<T> info;
     private T value;

     public Filter() { }

     public FilterInfo<T> getInfo() {return info;}
     public void setInfo(FilterInfo<T> info) { this.info = info; }
     public T getValue() { return value; }
     public void setValue(T value) {this.value = value;}
}
</code>```

I remove below code from above class, then class work correctly.

```<code>private FilterInfo<T> info;
</code>```

but FilterInfo has all prerequisite for use(Serializable, T extends Serializable, default Constructor)

```<code>@SuppressWarnings("serial")
public class FilterInfo<T extends Serializable> implements Serializable {
private String name;
private Class<?> type;

public FilterInfo() { }
public FilterInfo(String name, Class<?> type) {
    setName(name);  setType(type.getClass());
}

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

答:
Class<?> is not serializable by GWT, therefore neither is FilterInfo, and therefor neither is Filter. Consider that the compiler would need to leave in all possible class literals that are reachable by the compiler, in order to support this.

Instead, either find a different way to describe the type data, or build a CustomFieldSerialize for FilterInfo which can read from the stream and figure out which Class to use as a type, if there is a simple list you support, or an easy way to make a registry.

Body:
I define a class with Generic type like below in GWT. when I extend this class with a type or specify a type for this class everything is okay, but at runtime I get "could not get type signature for class Filter" message.

@SuppressWarnings("serial")
public class Filter<T extends Serializable> implements Serializable {
     private FilterInfo<T> info;
     private T value;

     public Filter() { }

     public FilterInfo<T> getInfo() {return info;}
     public void setInfo(FilterInfo<T> info) { this.info = info; }
     public T getValue() { return value; }
     public void setValue(T value) {this.value = value;}
}

I remove below code from above class, then class work correctly.

private FilterInfo<T> info;

but FilterInfo has all prerequisite for use(Serializable, T extends Serializable, default Constructor)

@SuppressWarnings("serial")
public class FilterInfo<T extends Serializable> implements Serializable {
private String name;
private Class<?> type;

public FilterInfo() { }
public FilterInfo(String name, Class<?> type) {
    setName(name);  setType(type.getClass());
}

public String getName() { return name; }
...


问:
Tradingview Calendar Javascript

$("#loadtv").on("click",function(myfunc23){
      var chart4 = new TradingView.widget({
        container_id: 'chart4',
       "width": "100%",
  "height": "100%",
  "locale": "en",
  "importanceFilter": "-1,0,1",
  "currencyFilter": "USD"
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loadpage">
  <button id="loadtv">Show Calendar Event</button>
      <div id= "tvaa" class= "tvcx tvapp row">
         <div  id="chart4"></div>
   <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-events.js"></script>
  </div>
</div></code>```

Hi,
I am trying to open the calendar widget of tradingview in a div, when a button is clicked. for some reason this same method worked with the charting widget but it isn't working for the calendar. Help appreciated!
Link to tradingview calendar widget script: https://www.tradingview.com/widget/economic-calendar/

答:
You need to use another script such that you can then use the TradingView constructor:

```<code><script src="//s3.tradingview.com/tv.js"></script>
</code>```

The calendar widget is only one component of the ensemble. If you want to disable stuff you should check with this cheatsheet which shows available options.

For some reason the WS in this SO snippet is disallowed (403).

 Therefore, you might want to check out this sample plunkr.

$("#loadtv").on("click", function() {
    new TradingView.widget({
        container_id: 'chart4',
        width: "100%",
        height: "1000px",
        locale: "en",
        importanceFilter: "-1,0,1",
        currencyFilter: "USD",
        symbol: "NASDAQ:AAPL",
        interval: "D",
        timezone: "America/New_York",
        theme: "White",
        style: 1,
        toolbar_bg: "rgba(0, 0, 196, 1)",
        withdateranges: true,
        hide_side_toolbar: false,
        allow_symbol_change: true,
        details: false,
        hotlist: false,
        calendar: true,
        news: [],
        hideideas: true,
        show_popup_button: true,
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//s3.tradingview.com/tv.js"></script>
<button id="loadtv">Show Calendar Event</button>
<div id="chart4"></div></code>```

Title: Tradingview Calendar Javascript

Body:
$("#loadtv").on("click",function(myfunc23){
      var chart4 = new TradingView.widget({
        container_id: 'chart4',
       "width": "100%",
  "height": "100%",
  "locale": "en",
  "importanceFilter": "-1,0,1",
  "currencyFilter": "USD"
    })

  <button id="loadtv">Show Calendar Event</button>

Hi,
I am trying to open the calendar widget of tradingview in a div, when a button is clicked. for some reason this same method worked with the charting widget but it isn't working for the calendar. Help appreciated!
Link to tradingview calendar widget script: https://www.tradingview.com/widget/economic-calendar/

Body:
You need to use another script such that you can then use the TradingView constructor:

<script src="//s3.tradingview.com/tv.js"></script>

The calendar widget is only one component of the ensemble. If you want to disable stuff you should check with this cheatsheet which shows available options.

For some reason the WS in this SO snippet is disallowed (403).

 Therefore, you might want to check out this sample plunkr.

$("#loadtv").on("click", function() {
    new TradingView.widget({
        container_id: 'chart4',
        width: "100%",
        height: "1000px",
        locale: "en",
        importanceFilter: "-1,0,1",
        currencyFilter: "USD",
        symbol: "NASDAQ:AAPL",
        interval: "D",
        timezone: "America/New_York",
        theme: "White",
        style: 1,
        toolbar_bg: "rgba(0, 0, 196, 1)",
        withdateranges: true,
        hide_side_toolbar: false,
        allow_symbol_change: true,
        details: false,
        hotlist: false,
        calendar: true,
        news: [],
        hideideas: true,
        show_popup_button: true,
    });
});

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//s3.tradingview.com/tv.js"></script>
<button id="loadtv">Show Calendar Event</button>
<div id="chart4"></div>


问:
Firebase Funcions missing logs
I have a simple function uploaded to Firebase Functions, that uses an external dependency (jimp). My code has some "console.log()" to trace what is happening when the function is triggered (by a 'write' action in Firstore).

According to the logs I can see in the firebase console,

every step of the function is running correctly, until it reaches the first call to the jimp object. At this point, no more logs on the console.

```<code>const Jimp  = require('jimp');
const os = require('os');
...
exports.manageImage2 = functions.firestore
    .document('/items/{docId}')
    .onWrite(event => {
        console.info('event triggered:', event);
        console.log('tmpDir', os.tmpdir());
        const originalUrl = data.original_file_url;
        const imageSize = data.size;

        if (imageSize > maxSize) {
            console.log(`Image is too big (${imageSize})`);
            Jimp.read(originalUrl, (err, image) => {
 ...
</code>```

I guess there is something wrong with the dependency, but I have no clue what it can be.

I obviously ran my code locally with any issue and also made sure the library is correctly listed in the dependencies of package.json

Any idea?

答:
Jimp.read is a callback styled asynchronous function. Use promise for adapt it to functions.

```<code>exports.manageImage2 = functions.firestore
    .document('/items/{docId}')
    .onWrite(event => {
        console.info('event triggered:', event);
        console.log('tmpDir', os.tmpdir());
        const originalUrl = data.original_file_url;
        const imageSize = data.size;

        if (imageSize > maxSize) {
            console.log(`Image is too big (${imageSize})`);
            return new Promise(resolve => Jimp.read(originalUrl, (err, image) => {
                // …
                // resolve(result);
            }));
        }
    });
</code>```

For explanation read this: https://firebase.google.com/docs/functions/terminate-functions.

Title: Firebase Funcions missing logs

Body:
I have a simple function uploaded to Firebase Functions, that uses an external dependency (jimp). My code has some "console.log()" to trace what is happening when the function is triggered (by a 'write' action in Firstore).

According to the logs I can see in the firebase console,

every step of the function is running correctly, until it reaches the first call to the jimp object. At this point, no more logs on the console.

const Jimp  = require('jimp');
const os = require('os');
...
exports.manageImage2 = functions.firestore
    .document('/items/{docId}')
    .onWrite(event => {
        console.info('event triggered:', event);
        console.log('tmpDir', os.tmpdir());
        const originalUrl = data.original_file_url;
        const imageSize = data.size;

        if (imageSize > maxSize) {
            console.log(`Image is too big (${imageSize})`);
            Jimp.read(originalUrl, (err, image) => {
 ...

I guess there is something wrong with the dependency, but I have no clue what it can be.

I obviously ran my code locally with any issue and also made sure the library is correctly listed in the dependencies of package.json

Any idea?

Body:
Jimp.read is a callback styled asynchronous function. Use promise for adapt it to functions.

exports.manageImage2 = functions.firestore
    .document('/items/{docId}')
    .onWrite(event => {
        console.info('event triggered:', event);
        console.log('tmpDir', os.tmpdir());
        const originalUrl = data.original_file_url;
        const imageSize = data.size;

        if (imageSize > maxSize) {
            console.log(`Image is too big (${imageSize})`);
            return new Promise(resolve => Jimp.read(originalUrl, (err, image) => {
                // …
                // resolve(result);
            }));
        }
    });

For explanation read this: https://firebase.google.com/docs/functions/terminate-functions.


问:
Format db.Datetime values automatically in Flask-SQLAlchemy
I'm in the process of migrating hosts, and the new hosts uses a newer version of MySQL which is stricter about the format of datetime values it accepts. I know that I can turn this off, but I'd like to find a solution to properly convert these values to the correct format. Preferably one that can be easily swapped out across the many models I need to update (100 or so).

If I can't find a way to update this on the model level, I may have to hunt down the thousands of locations where these values are set.

I've trimmed down an example model here:

```<code>class Timesheet(BaseModel, db.Model):
    __tablename__ = "timesheet"
    timesheet_id = db.Column(db.Integer, primary_key=True)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    updated = db.Column(db.DateTime)
    employee_id = db.Column(db.Integer, db.ForeignKey('user.employee_id'))
    description = db.Column(db.String(255))
    hours = db.Column(db.Numeric(9, 2))
    billable = db.Column(db.Boolean, default=False)
    retainer = db.Column(db.Boolean, default=False)
    client_id = db.Column(db.Integer, db.ForeignKey('client.client_id'), default=None)
    project_id = db.Column(db.Integer, db.ForeignKey('project.project_id'), default=None)
    task_id = db.Column(db.Integer, default=None)
    timesheet_date = db.Column(db.DateTime, default=datetime.utcnow)
</code>```

I'm hoping there is a way to modify db.Datetime so that it returns a true Python datetime object when provided with an ISO8601 datetime string ('YYYY-MM-DDT00:00:00.000Z')

Looking for something along the lines of:

```<code>class FormattedDateTime(db.DateTime):
    def self.__set__(self, value):
        return dateutil.parser.parse(value)
</code>```

The column definition would then be changed to:

```<code>updated = db.Column(FormattedDateTime)
</code>```

...so that it will automatically save with the correct format when SQLAlchemy sends to MySQL.

I've looked at Mixins and searched around for approaches that will accomplish this, but can't seem to find any good solutions. Help is much appreciated.

UPDATED:
This is a rough draft of what I've worked out so far... it seems to do well even when filtering/comparing on the field in a query but isn't well tested just yet.

```<code>class TFDateTime(TypeDecorator):
    impl = DATETIME

    def process_bind_param(self, value, dialect):
        if value is None:
            return None
        print("process_bind_param", value, type(value))
        if type(value) == datetime or type(value) == date:
            return value
        elif type(value) == str:
            return parse(value, ignoretz=True)
        else:
            return None

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        print("process_result_value", value, type(value))
        return value
</code>```

答:
I'm surprised the built-in DateTime type doesn't automatically give a valid value to the DB - it might be a bug in SQLAlchemy?

That said, creating a custom type will probably do what you want - there's a few examples in the SQLAlchemy docs, but something like this should get you started:

```<code>import datetime
from sqlalchemy.types import TypeDecorator, TIMESTAMP
import iso8601

class ISO8601DateTime(TypeDecorator):
    impl = TIMESTAMP

    def process_bind_param(self, value, dialect):
        if value is None:
            return None

        if isinstance(value, datetime.datetime):
            return value.strftime(<iso8601-format-string>)

        return value

    def process_result_value(self, value, dialect):
        if value is None:
            return None

        return iso8601.parse_date(value)
</code>```

Uses the iso8601 lib for brevity, date-util might be necessary. You may also need to use dialect-specific types for timestamp/datetime.

Body:
I'm in the process of migrating hosts, and the new hosts uses a newer version of MySQL which is stricter about the format of datetime values it accepts. I know that I can turn this off, but I'd like to find a solution to properly convert these values to the correct format. Preferably one that can be easily swapped out across the many models I need to update (100 or so).

If I can't find a way to update this on the model level, I may have to hunt down the thousands of locations where these values are set.

I've trimmed down an example model here:

class Timesheet(BaseModel, db.Model):
    __tablename__ = "timesheet"
    timesheet_id = db.Column(db.Integer, primary_key=True)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    updated = db.Column(db.DateTime)
    employee_id = db.Column(db.Integer, db.ForeignKey('user.employee_id'))
    description = db.Column(db.String(255))
    hours = db.Column(db.Numeric(9, 2))
    billable = db.Column(db.Boolean, default=False)
    retainer = db.Column(db.Boolean, default=False)
    client_id = db.Column(db.Integer, db.ForeignKey('client.client_id'), default=None)
    project_id = db.Column(db.Integer, db.ForeignKey('project.project_id'), default=None)
    task_id = db.Column(db.Integer, default=None)
    timesheet_date = db.Column(db.DateTime, default=datetime.utcnow)

I'm hoping there is a way to modify db.Datetime so that it returns a true Python datetime object when provided with an ISO8601 datetime string ('YYYY-MM-DDT00:00:00.000Z')

Looking for something along the lines of:

class FormattedDateTime(db.DateTime):
    def self.__set__(self, value):
        return dateutil.parser.parse(value)

The column definition would then be changed to:

updated = db.Column(FormattedDateTime)

...so that it will automatically save with the correct format when SQLAlchemy sends to MySQL.

I've looked at Mixins and searched around for approaches that will accomplish this, but can't seem to find any good solutions. Help is much appreciated.

UPDATED:
This is a rough draft of what I've worked out so far... it seems to do well even when filtering/comparing on the field in a query but isn't well tested just yet.

class TFDateTime(TypeDecorator):
    impl = DATETIME

    def process_bind_param(self, value, dialect):
        if value is None:
            return None
        print("process_bind_param", value, type(value))
        if type(value) == datetime or type(value) == date:
            return value
        elif type(value) == str:
            return parse(value, ignoretz=True)
        else:
            return None

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        print("process_result_value", value, type(value))
        return value

Body:
I'm surprised the built-in DateTime type doesn't automatically give a valid value to the DB - it might be a bug in SQLAlchemy?

That said, creating a custom type will probably do what you want - there's a few examples in the SQLAlchemy docs, but something like this should get you started:

import datetime
from sqlalchemy.types import TypeDecorator, TIMESTAMP
import iso8601

class ISO8601DateTime(TypeDecorator):
    impl = TIMESTAMP

    def process_bind_param(self, value, dialect):
        if value is None:
            return None

        if isinstance(value, datetime.datetime):
            return value.strftime(<iso8601-format-string>)

        return value

    def process_result_value(self, value, dialect):
        if value is None:
            return None

        return iso8601.parse_date(value)

Uses the iso8601 lib for brevity, date-util might be necessary. You may also need to use dialect-specific types for timestamp/datetime.


问:
Symfony Could not determine access type when using EntityType form builder
I have 2 entities Cars and Parts and I want to be able to create new Car with multiple parts. For this reason I made this form in CarsType

```<code>$builder->
        add('make')->
        add('model')->
        add('travelledDistance')->
        add('parts',EntityType::class,array(
            'class' => Parts::class,
            'choice_label'=>"name",
            'query_builder' => function(PartsRepository $partsRepository){
                return $partsRepository->getAllPartsForCarsForm();
            },
            'multiple' => true
        ));
</code>```

It gives me this error

Could not determine access type for property "parts" in class
  "AppBundle\Entity\Cars".

Here is my entity Cars

```<code>namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Cars
 *
 * @ORM\Table(name="cars")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
 */
class Cars
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Make", type="string", length=255)
     */
    private $make;

    /**
     * @var string
     *
     * @ORM\Column(name="Model", type="string", length=255)
     */
    private $model;

    /**
     * @var int
     *
     * @ORM\Column(name="TravelledDistance", type="bigint")
     */
    private $travelledDistance;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
     * @ORM\JoinTable(
     *  name="Parts_Cars",
     *  joinColumns={
     *      @ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
     *  })
     */
    private $parts;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set make
     *
     * @param string $make
     *
     * @return Cars
     */
    public function setMake($make)
    {
        $this->make = $make;

        return $this;
    }

    /**
     * Get make
     *
     * @return string
     */
    public function getMake()
    {
        return $this->make;
    }

    /**
     * Set model
     *
     * @param string $model
     *
     * @return Cars
     */
    public function setModel($model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Get model
     *
     * @return string
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set travelledDistance
     *
     * @param integer $travelledDistance
     *
     * @return Cars
     */
    public function setTravelledDistance($travelledDistance)
    {
        $this->travelledDistance = $travelledDistance;

        return $this;
    }

    /**
     * Get travelledDistance
     *
     * @return int
     */
    public function getTravelledDistance()
    {
        return $this->travelledDistance;
    }

    /**
     * @return mixed
     */
    public function getParts()
    {
        return $this->parts;
    }

}
</code>```

And in case it matters here is my Parts entity

```<code>namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Parts
 *
 * @ORM\Table(name="parts")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PartsRepository")
 */
class Parts
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="Price", type="decimal", precision=10, scale=2)
     */
    private $price;

    /**
     * @var int
     *
     * @ORM\Column(name="Quantity", type="integer")
     */
    private $quantity;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Suppliers", inversedBy="parts")
     * @ORM\JoinColumn(name="Supplier_Id", referencedColumnName="id")
     */
    private $supplier;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
     */
    private $cars;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Parts
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param string $price
     *
     * @return Parts
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return string
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set quantity
     *
     * @param integer $quantity
     *
     * @return Parts
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;

        return $this;
    }

    /**
     * Get quantity
     *
     * @return int
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * @return mixed
     */
    public function getSupplier()
    {
        return $this->supplier;
    }

    /**
     * @return mixed
     */
    public function getCars()
    {
        return $this->cars;
    }
    public function __toString()
    {
       return $this->getName();
    }

}
</code>```

To save time here is the mapping between the 2 entities as well as the property parts in Cars

```<code>/**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
     * @ORM\JoinTable(
     *  name="Parts_Cars",
     *  joinColumns={
     *      @ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
     *  })
     */
    private $parts;
</code>```

and In Parts

```<code> /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
     */
    private $cars;
</code>```

Here is the newAction in CarsController

```<code>/**
     * Creates a new car entity.
     *
     * @Route("/new", name="cars_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $carsRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Cars');
        $car = new Cars();
        $form = $this->createForm('AppBundle\Form\CarsType', $car);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($car);
            $em->flush();

            return $this->redirectToRoute('cars_show', array('id' => $car->getId()));
        }

        return $this->render('cars/new.html.twig', array(
            'car' => $car,
            'form' => $form->createView(),
        ));
    }
</code>```

My question is - How can I make it so that I can create new Car with several Parts and to save the relationship in the database so that when I retrieve the Car I can get the parts as well?

Basically how to make it so when I create a new car the relationship is saved in the parts_cars table which holds the id's?

答:
Let Doctrine do the JOIN work

Since you're doing a ManyToMany (EntityToEntity), the @JoinColumn directives are not needed.

Try removing it from the Cars entity.

Cars

```<code>/**
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
 */
$parts
</code>```

The only cases in which you need to specify the JoinColumns are:

Joining against self

Joining where the primary key is not the Entity ID.

Need to define fields in the join_table

Would be MUCH easier in this case to do A OneToMany J ManyToOne B

Since you're doing none of the above, Doctrine is having trouble accessing the Entities' IDENTITY fields for the join.

Body:
I have 2 entities Cars and Parts and I want to be able to create new Car with multiple parts. For this reason I made this form in CarsType

$builder->
        add('make')->
        add('model')->
        add('travelledDistance')->
        add('parts',EntityType::class,array(
            'class' => Parts::class,
            'choice_label'=>"name",
            'query_builder' => function(PartsRepository $partsRepository){
                return $partsRepository->getAllPartsForCarsForm();
            },
            'multiple' => true
        ));

It gives me this error

Could not determine access type for property "parts" in class
  "AppBundle\Entity\Cars".

Here is my entity Cars

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Cars
 *
 * @ORM\Table(name="cars")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
 */
class Cars
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Make", type="string", length=255)
     */
    private $make;

    /**
     * @var string
     *
     * @ORM\Column(name="Model", type="string", length=255)
     */
    private $model;

    /**
     * @var int
     *
     * @ORM\Column(name="TravelledDistance", type="bigint")
     */
    private $travelledDistance;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
     * @ORM\JoinTable(
     *  name="Parts_Cars",
     *  joinColumns={
     *      @ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
     *  })
     */
    private $parts;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set make
     *
     * @param string $make
     *
     * @return Cars
     */
    public function setMake($make)
    {
        $this->make = $make;

        return $this;
    }

    /**
     * Get make
     *
     * @return string
     */
    public function getMake()
    {
        return $this->make;
    }

    /**
     * Set model
     *
     * @param string $model
     *
     * @return Cars
     */
    public function setModel($model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Get model
     *
     * @return string
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set travelledDistance
     *
     * @param integer $travelledDistance
     *
     * @return Cars
     */
    public function setTravelledDistance($travelledDistance)
    {
        $this->travelledDistance = $travelledDistance;

        return $this;
    }

    /**
     * Get travelledDistance
     *
     * @return int
     */
    public function getTravelledDistance()
    {
        return $this->travelledDistance;
    }

    /**
     * @return mixed
     */
    public function getParts()
    {
        return $this->parts;
    }

}

And in case it matters here is my Parts entity

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Parts
 *
 * @ORM\Table(name="parts")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PartsRepository")
 */
class Parts
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="Price", type="decimal", precision=10, scale=2)
     */
    private $price;

    /**
     * @var int
     *
     * @ORM\Column(name="Quantity", type="integer")
     */
    private $quantity;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Suppliers", inversedBy="parts")
     * @ORM\JoinColumn(name="Supplier_Id", referencedColumnName="id")
     */
    private $supplier;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
     */
    private $cars;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Parts
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param string $price
     *
     * @return Parts
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return string
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set quantity
     *
     * @param integer $quantity
     *
     * @return Parts
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;

        return $this;
    }

    /**
     * Get quantity
     *
     * @return int
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * @return mixed
     */
    public function getSupplier()
    {
        return $this->supplier;
    }

    /**
     * @return mixed
     */
    public function getCars()
    {
        return $this->cars;
    }
    public function __toString()
    {
       return $this->getName();
    }

}

To save time here is the mapping between the 2 entities as well as the property parts in Cars

/**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
     * @ORM\JoinTable(
     *  name="Parts_Cars",
     *  joinColumns={
     *      @ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
     *  })
     */
    private $parts;

and In Parts

 /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Cars", mappedBy="parts")
     */
    private $cars;

Here is the newAction in CarsController

/**
     * Creates a new car entity.
     *
     * @Route("/new", name="cars_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $carsRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Cars');
        $car = new Cars();
        $form = $this->createForm('AppBundle\Form\CarsType', $car);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($car);
            $em->flush();

            return $this->redirectToRoute('cars_show', array('id' => $car->getId()));
        }

        return $this->render('cars/new.html.twig', array(
            'car' => $car,
            'form' => $form->createView(),
        ));
    }

My question is - How can I make it so that I can create new Car with several Parts and to save the relationship in the database so that when I retrieve the Car I can get the parts as well?

Basically how to make it so when I create a new car the relationship is saved in the parts_cars table which holds the id's?

Body:
Let Doctrine do the JOIN work

Since you're doing a ManyToMany (EntityToEntity), the @JoinColumn directives are not needed.

Try removing it from the Cars entity.

Cars

/**
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
 */
$parts

The only cases in which you need to specify the JoinColumns are:

Joining against self

Joining where the primary key is not the Entity ID.

Need to define fields in the join_table

Would be MUCH easier in this case to do A OneToMany J ManyToOne B

Since you're doing none of the above, Doctrine is having trouble accessing the Entities' IDENTITY fields for the join.


问:
w3wp.exe crash - ThreadAbortException
we have a problem that we can't reproduce, it happens randomly on our web server (Windows Server 2008 Datacenter 64-bit, hosted on Amazon EC2) running ASP.NET 4.

It starts with a ASP.NET warning in the error log (a strange GET request with a really long URL):

Exception information:

     Exception type: HttpException

     Exception message: The length of the URL for this request exceeds the configured maxUrlLength value.

    at System.Web.HttpRequest.ValidateInputIfRequiredByConfig()

    at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)

Then an error:

Application ID: /LM/W3SVC/2/ROOT

  Process ID: 4604

  Exception: System.Threading.ThreadAbortException

  Message: Thread was being aborted.

  StackTrace:    at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)

    at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)

    at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)

Then another error:

Application ID: DefaultDomain

  Process ID: 4604

  Exception: System.Threading.ThreadAbortException

  Message: Thread was being aborted.

  StackTrace:

And then the application error:

Faulting application w3wp.exe, version 7.0.6002.18005, time stamp 0x49e03238, faulting module kernel32.dll, version 6.0.6002.18005, time stamp 0x49e041d1, exception code 0xe0434352, fault offset 0x00000000000176fd, process id 0x%9, application start time 0x%10.

Windbg

I managed to get a dump for a crash with adplus, but I really don't know what to look for. I've troubleshooted some stackoverflows with Windbg before, but I don't know which approach to use for this error.

!pe on the thread with the error:

Exception object: 00000001c323d948

  Exception type:   System.Threading.ThreadAbortException

  Message:          Thread was being aborted.

  InnerException:

  StackTrace (generated):

  StackTraceString:

  HResult: 80131530

!clrstack

Child SP         IP               Call Site

  0000000015f7f078 0000000076c176fd [GCFrame: 0000000015f7f078]

  0000000015f7f258 0000000076c176fd [GCFrame: 0000000015f7f258]

k

Child-SP          RetAddr           Call Site

  0000000015f7edf0 000007fef2826e39 kernel32!RaiseException+0x39

  0000000015f7eec0 000007fef2bbbfb4 clr!RaiseTheExceptionInternalOnly+0x363

  0000000015f7eff0 000007fef2bbc906 clr!RaiseTheException+0xa4

  0000000015f7f020 000007fef2c3b99b clr!BStrFromString+0x66

  0000000015f7f050 000007fef2c3b9a9 clr!RealCOMPlusThrow+0x3b

  0000000015f7f0c0 000007fef2c93156 clr!RealCOMPlusThrow+0x9

  0000000015f7f0f0 000007fef2b229f3 clr!Thread::RaiseCrossContextException+0x2a7

  0000000015f7f310 000007fef2830886 clr! ?? ::FNODOBFM::string'+0xafb03

  0000000015f7f4c0 000007fef27fcce3 clr!UM2MDoADCallBack+0x9e

  0000000015f7f530 000007fef845ba59 clr!UMThunkStubAMD64+0x273

  0000000015f7f5c0 000007fef8458f02 webengine4!W3_MGD_HANDLER::ProcessNotification+0x79

  0000000015f7f5f0 000007fef27d4595 webengine4!ProcessNotificationCallback+0x43

  0000000015f7f620 000007fef27d3ac8 clr!UnManagedPerAppDomainTPCount::DispatchWorkItem+0x181

  0000000015f7f6d0 000007fef294658f clr!ThreadpoolMgr::NewWorkerThreadStart+0x2e5

  0000000015f7f770 000007fef29447c6 clr!ThreadpoolMgr::WorkerThreadStart+0x3b

  0000000015f7f810 0000000076c1be3d clr!Thread::intermediateThreadProc+0x7d

  0000000015f7fbd0 0000000076d56a51 kernel32!BaseThreadInitThunk+0xd

  0000000015f7fc00 00000000`00000000 ntdll!RtlUserThreadStart+0x1d

Anybody have a clue what this could be? Or can point me in the right direction for analyzing it with Windbg?

Edit:
The incoming urls usually looks like this:
foo.bar.com/wEPDwULLTE1MTk5MzIzMTFkGAMFFmN0bDAwJGRiMSRkZGxEYXRhYmFzZXMPFCsAAmRkZAU7Y3RsMDAkU2VhcmNoQ2xvdWQxJF9SaWdodENvbHVtbiRfU2VhcmNoQ2xvdWQkbHN2U2VhcmNoVGVybXMPFCsADmRkZGRkZGQ8KwAUAAIUZGRkZgL/D2QFK2N0bDAwJHN1cnZleTEkX1JpZ2h0Q29sdW1uJF9JUiR1c2VyQ29tbWVudHMPFCsAA2VnZGQeuUcvQDsShDIp1k7YjJw70Ry 9/Q1B9Sd1egrovYgkw==/

but I found in the event log that this happen for this urls like this aswell:
foo.bar.com/&
("dangerous request" in .NET 4)

答:
You should at least load symbols and then see the correct strings displayed in call stack.

If you are not capable of handling such analysis, I think opening a support case via http://support.microsoft.com is good for you.

ContentLicense: CC BY-SA 2.5

Title: w3wp.exe crash - ThreadAbortException


问:
TypeError: 'numpy.float32' object is not iterable
I have an array of probabilities:

```<code>proba =  :[[0.254 0.556 0.025] [0.898 0567 .112]]
</code>```

want max value from each as [[0.556] [0.898]]

How i can do it?
Tried 2 methods:

```<code> 1. max(sublist) for sublist in proba
 2. proba = map(max,proba)
</code>```

and getting error "TypeError: 'numpy.float32' object is not iterable"

Any suggestion?

答:
I can notice some problems in your code,
first of all, your data list is not in the correct format,
commas are missing and there is an extra ':' at the right of the equal sign

```<code>proba = [[0.254, 0.556, 0.025], [0.898, 0.567, .112]]
</code>```

And then you can get the answer like this :

```<code>max_ = [max(i) for i in proba]
</code>```

Body:
I have an array of probabilities:

proba =  :[[0.254 0.556 0.025] [0.898 0567 .112]]

want max value from each as [[0.556] [0.898]]

How i can do it?
Tried 2 methods:

 1. max(sublist) for sublist in proba
 2. proba = map(max,proba)

and getting error "TypeError: 'numpy.float32' object is not iterable"

Any suggestion?

Body:
I can notice some problems in your code,
first of all, your data list is not in the correct format,
commas are missing and there is an extra ':' at the right of the equal sign

proba = [[0.254, 0.556, 0.025], [0.898, 0.567, .112]]

And then you can get the answer like this :

max_ = [max(i) for i in proba]


问:
How to do reverse search and find particular character in nth place and delete characters after that
Actual:

```<code>ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml
</code>```

Need:

```<code>ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01.xml
</code>```

Want to delete everything upto .xml from 11th "_" from reverse.

This is a sample file name format. I have like 10-15K files in a directory. And I need to rename/change all the files. Basically need to delete from "_"(after L01) to ".".

答:
Nice challenge...

You have to involve a little bit of mathematics (probably much simpler, if you'd use a language with REGEX support)

```<code>@echo off
setlocal enabledelayedexpansion
set count=11
set "string=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"
echo %string%
call :remove "%string%" 11
echo %return%
goto :eof

:remove [String] [Integer]
set "name=%~n1"
set n=0
for /l %%i in (150,-1,0) do (
  if "!name:~%%i,1!" equ "_" set /a n+=1, p[!n!]=%%i
)
set /a x=%2-1
set pos=!p[%x%]!
set return=!name:~0,%pos%!%~x1
</code>```

The called subroutine counts the _ and remembers each position. So we can "easily" calculate the position where the string should be cut.

Not a beautiful or obvious code, but - well, we are in batch...

You may have to adapt the 150 to a number greater than the longest possible string (filename, as your example suggests).

Edit: to process all filenames in the folder, just put another for around:

```<code>@echo off
setlocal enabledelayedexpansion
set count=11
for %%f in (*.xml) do (
  echo %%f
  call :remove "%%f" 11
  echo !return!
)
goto :eof

:remove [String] [Integer]
set "name=%~n1"
set n=0
for /l %%i in (150,-1,0) do (
  if "!name:~%%i,1!" equ "_" set /a n+=1, p[!n!]=%%i
)
set /a x=%2-1
set pos=!p[%x%]!
set return=!name:~0,%pos%!%~x1
</code>```

Body:
Actual:

ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml

Need:

ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01.xml

Want to delete everything upto .xml from 11th "_" from reverse.

This is a sample file name format. I have like 10-15K files in a directory. And I need to rename/change all the files. Basically need to delete from "_"(after L01) to ".".

Body:
Nice challenge...

You have to involve a little bit of mathematics (probably much simpler, if you'd use a language with REGEX support)

@echo off
setlocal enabledelayedexpansion
set count=11
set "string=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"
echo %string%
call :remove "%string%" 11
echo %return%
goto :eof

:remove [String] [Integer]
set "name=%~n1"
set n=0
for /l %%i in (150,-1,0) do (
  if "!name:~%%i,1!" equ "_" set /a n+=1, p[!n!]=%%i
)
set /a x=%2-1
set pos=!p[%x%]!
set return=!name:~0,%pos%!%~x1

The called subroutine counts the _ and remembers each position. So we can "easily" calculate the position where the string should be cut.

Not a beautiful or obvious code, but - well, we are in batch...

You may have to adapt the 150 to a number greater than the longest possible string (filename, as your example suggests).

Edit: to process all filenames in the folder, just put another for around:

@echo off
setlocal enabledelayedexpansion
set count=11
for %%f in (*.xml) do (
  echo %%f
  call :remove "%%f" 11
  echo !return!
)
goto :eof

:remove [String] [Integer]
set "name=%~n1"
set n=0
for /l %%i in (150,-1,0) do (
  if "!name:~%%i,1!" equ "_" set /a n+=1, p[!n!]=%%i
)
set /a x=%2-1
set pos=!p[%x%]!
set return=!name:~0,%pos%!%~x1


问:
Use Fiddler with Basic Authentication to access RESTful WebAPI
I have a WebAPI that works without issue.  I have tested locally and deployed to my server and configured this service in IIS to use Basic Authentication.  I am able to browse to my service and I receive the Authentication challenge I expect and all works swimmingly!  Now I want to use Fiddler to test this and I have constructed a POST to a specific url and I got a 401 (Unauthorized) error.  So I decided to add a base64 string in my Request Header and I am now getting a 500 error.

What I would like to know is, does my Request Header look correct?  I am obviously going to obfuscate my Host and base64 string which contains the format username:password for the Authentication challenge.

```<code>User-Agent: Fiddler
Host: xxx.xxx.xxx.xxx:xxxx
Content-Length: 185
Content-Type: text/json
Authorization: Basic jskadjfhlksadjhdflkjhiu9813ryiu34
</code>```

答: I found that in Fiddler 4, all I had to do was check the Automatically Authenticate option that is on the Rules menu.</p>

Body:
I have a WebAPI that works without issue.  I have tested locally and deployed to my server and configured this service in IIS to use Basic Authentication.  I am able to browse to my service and I receive the Authentication challenge I expect and all works swimmingly!  Now I want to use Fiddler to test this and I have constructed a POST to a specific url and I got a 401 (Unauthorized) error.  So I decided to add a base64 string in my Request Header and I am now getting a 500 error.

What I would like to know is, does my Request Header look correct?  I am obviously going to obfuscate my Host and base64 string which contains the format username:password for the Authentication challenge.

User-Agent: Fiddler
Host: xxx.xxx.xxx.xxx:xxxx
Content-Length: 185
Content-Type: text/json
Authorization: Basic jskadjfhlksadjhdflkjhiu9813ryiu34


问:
android.util.Pair container purpose
I need to make available two Lists of the same type, let's say List<Argument>, pros and cons.

I created a custom Object for that purpose, this way:

```<code>    public class Decision  {
        private List<Argument> pros;
        private List<Argument> cons;
}
</code>```

and a colleague came across with this solution:

```<code>Pair<List<Argument>,List<Argument>> decision = new Pair<>(pros,cons);
</code>```

What is the purpose of Pair if not wrapping up two different objects?

My guess would be something like:

1- Key, value

2- X,Y (coordinates)

3- Something like the example above (pros - cons)

答:
From the documentation:

Container to ease passing around a tuple of two objects. This object
  provides a sensible implementation of equals(), returning true if
  equals() is true on each of the contained objects.

The benefits of Pair VS custom wrapper class:

You don't have to define a class

Don't have to create equals/hashcode

The drawbacks are:

Less clarity with the name Decision VS Pair

Less clarity in the fields -> first VS pros and second VS cons

Depending on your use case you can choose to use Pair or create your own wrapper class.

Title: android.util.Pair container purpose

Body:
I need to make available two Lists of the same type, let's say List<Argument>, pros and cons.

I created a custom Object for that purpose, this way:

    public class Decision  {
        private List<Argument> pros;
        private List<Argument> cons;
}

and a colleague came across with this solution:

Pair<List<Argument>,List<Argument>> decision = new Pair<>(pros,cons);

What is the purpose of Pair if not wrapping up two different objects?

My guess would be something like:

1- Key, value

2- X,Y (coordinates)

3- Something like the example above (pros - cons)