问:
Selenium Getting Started Guide, What did I do Wrong?
I tried to follow the "Getting Started Guide" for Selenium as closely as I could, however I get many warnings and errors in console when I try to run the
code.

 I also imported all of the jars in selenium-java-2.48.2 from here.

 Thank you so much to anyone willing to look through this and try to help me!

 Here are my classes, that I copied and pasted from the guide.

 Example.java

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

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

        // And now use this to visit Google
        driver.get("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());

        driver.quit();
    }
}
</code>```

GoogleSuggest.java

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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSuggest {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript
        WebDriver driver = new FirefoxDriver();

        // Go to the Google Suggest home page
        driver.get("http://www.google.com/webhp?complete=1&hl=en");

        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Cheese");

        // Sleep until the div we want is visible or 5 seconds is over
        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
            WebElement resultsDiv = driver.findElement(By.className("gssb_e"));

            // If results have been returned, the results are displayed in a drop down.
            if (resultsDiv.isDisplayed()) {
              break;
            }
        }

        // And now list the suggestions
        List<WebElement> allSuggestions = driver.findElements(By.xpath("//td[@class='gssb_a gbqfsf']"));

        for (WebElement suggestion : allSuggestions) {
            System.out.println(suggestion.getText());
        }

        driver.quit();
    }
}
</code>```

What appears in the console when I run 'Example.java'

```<code>Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement addBehavior
WARNING: Unimplemented behavior: #default#userdata
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1419] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1467] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1478] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1488] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1499] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1510] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1601] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1613] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1626] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1639] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1653] Error in expression. (Invalid token "}". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2203] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2543] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2616] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3194] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3701] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3761] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:4196] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:4960] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6103] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6338] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6781] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6938] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:7010] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:7352] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:199] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:1691] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:2949] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:3481] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:3969] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:4480] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [3:117] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:685] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1235] Error in expression; ':' found after identifier "progid".
Page title is: Cheese! - Google Search
</code>```

This class does what its supposed to do, even if it displays a bunch warnings...

 What appears in the console when I run GoogleSuggest.java

```<code>Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"gssb_e"}
Command duration or timeout: 9 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.0', revision: 'b7b081a', time: '2015-10-07 15:45:39'
System info: host: 'Zeus', ip: '192.168.7.103', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_20'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=40.0.3, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: f90cec4e-f47c-4306-9491-3248e836dd7c
*** Element info: {Using=class name, value=gssb_e}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:467)
    at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
    at GoogleSuggest.main(GoogleSuggest.java:23)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"gssb_e"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.0', revision: 'b7b081a', time: '2015-10-07 15:45:39'
System info: host: 'Zeus', ip: '192.168.7.103', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_20'
Driver info: driver.version: unknown
    at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10659)
    at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10668)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12534)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12539)
    at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12481)
</code>```

Along with all that in the console, the class also opens FireFox, waits for Google to load, types cheese, searches, and then stops and all the errors appear.

答:
It just warnings, you can ignore them.

Use another WEB driver instead of default. For instance it could be CHROME (you can chose between different browsers like CHROME, FIREFOX_31, FIREFOX_31, INTERNET_EXPLORER_8, INTERNET_EXPLORER_11 ).

HtmlUnitDriver unitDriver = new HtmlUnitDriver(BrowserVersion.CHROME);
I suppose it should fix your problem.

Body:
I tried to follow the "Getting Started Guide" for Selenium as closely as I could, however I get many warnings and errors in console when I try to run the
code.

 I also imported all of the jars in selenium-java-2.48.2 from here.

 Thank you so much to anyone willing to look through this and try to help me!

 Here are my classes, that I copied and pasted from the guide.

 Example.java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

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

        // And now use this to visit Google
        driver.get("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());

        driver.quit();
    }
}

GoogleSuggest.java

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSuggest {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript
        WebDriver driver = new FirefoxDriver();

        // Go to the Google Suggest home page
        driver.get("http://www.google.com/webhp?complete=1&hl=en");

        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Cheese");

        // Sleep until the div we want is visible or 5 seconds is over
        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
            WebElement resultsDiv = driver.findElement(By.className("gssb_e"));

            // If results have been returned, the results are displayed in a drop down.
            if (resultsDiv.isDisplayed()) {
              break;
            }
        }

        // And now list the suggestions
        List<WebElement> allSuggestions = driver.findElements(By.xpath("//td[@class='gssb_a gbqfsf']"));

        for (WebElement suggestion : allSuggestions) {
            System.out.println(suggestion.getText());
        }

        driver.quit();
    }
}

What appears in the console when I run 'Example.java'

Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement addBehavior
WARNING: Unimplemented behavior: #default#userdata
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1419] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1467] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1478] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1488] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1499] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1510] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1601] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1613] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1626] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1639] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1653] Error in expression. (Invalid token "}". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, "-", <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <RESOLUTION_DPI>, <RESOLUTION_DPCM>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>.)
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2203] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2543] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:2616] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3194] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3701] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:3761] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:4196] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:4960] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6103] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6338] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6781] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:6938] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:7010] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:7352] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:199] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:1691] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:2949] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:3481] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:3969] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [2:4480] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [3:117] Error in declaration. '*' is not allowed as first char of a property.
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:685] Error in expression; ':' found after identifier "progid".
Jan 07, 2016 6:15:36 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNING: CSS error: 'http://www.google.com/' [1:1235] Error in expression; ':' found after identifier "progid".
Page title is: Cheese! - Google Search

This class does what its supposed to do, even if it displays a bunch warnings...

 What appears in the console when I run GoogleSuggest.java

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"gssb_e"}
Command duration or timeout: 9 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.0', revision: 'b7b081a', time: '2015-10-07 15:45:39'
System info: host: 'Zeus', ip: '192.168.7.103', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_20'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=40.0.3, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: f90cec4e-f47c-4306-9491-3248e836dd7c
*** Element info: {Using=class name, value=gssb_e}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:467)
    at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
    at GoogleSuggest.main(GoogleSuggest.java:23)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"gssb_e"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.0', revision: 'b7b081a', time: '2015-10-07 15:45:39'
System info: host: 'Zeus', ip: '192.168.7.103', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_20'
Driver info: driver.version: unknown
    at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10659)
    at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10668)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12534)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12539)
    at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/Bill/AppData/Local/Temp/anonymous6644175254170304178webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12481)

Along with all that in the console, the class also opens FireFox, waits for Google to load, types cheese, searches, and then stops and all the errors appear.


来源: stackexchange

问:
Center All Elements to a Certain Width
I'm trying to get everything to center and to about 80% of the page. Everything seems fine, except for my two main divs extend over my banner and nav bar by about 1px, even though they are set to 80%.

Here is the CSS: https://pastebin.com/HM7PLqX0

body {
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height: 120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;
}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='logo'>
  The Realm MC
</div>

<div class="topnav" id="myTopnav">
  <i class="fa fa-home" aria-hidden="true"></i>
     Home
  <i class="fa fa-play" aria-hidden="true"></i>
     Play
  <i class="fa fa-comment-o" aria-hidden="true"></i>
     Forums
  <i class="fa fa-heart-o" aria-hidden="true"></i>
     Donate
</div>

<div class='banner'>
  There are 7 out of 10 players online!
</div>
<br />

<div id='wrapper' style='text-align:center;'>
  <div class='about'>
    Lorem ipsum<br /> dolor sit amet
  </div>

  <div class='stats'>
    Lorem ipsum<br /> dolor sit amet
  </div>
</div></code>```

答:
You haven't mention any with for wrapper div, therefore it is assigned 100% of the width available and div inside it will take width accordingly.

Try reducing the width of about div to 59% as shown below, this will make both divs lie inside 80% of width scope :

```<code>.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 59%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}
</code>```

Here is the fiddle for that : https://jsfiddle.net/rp1shr4t/

or you can set width of wrapper div as you have done topnav div and then set width of inner divs accordingly.

ContentLicense: CC BY-SA 3.0

Title: Center All Elements to a Certain Width

Body:
I'm trying to get everything to center and to about 80% of the page. Everything seems fine, except for my two main divs extend over my banner and nav bar by about 1px, even though they are set to 80%.

Here is the CSS: https://pastebin.com/HM7PLqX0

body {
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height: 120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;
}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}

  The Realm MC

     Home

     Play

     Forums

     Donate

  There are 7 out of 10 players online!

    Lorem ipsum
 dolor sit amet

    Lorem ipsum
 dolor sit amet

Body:
You haven't mention any with for wrapper div, therefore it is assigned 100% of the width available and div inside it will take width accordingly.

Try reducing the width of about div to 59% as shown below, this will make both divs lie inside 80% of width scope :

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 59%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

Here is the fiddle for that : https://jsfiddle.net/rp1shr4t/

or you can set width of wrapper div as you have done topnav div and then set width of inner divs accordingly.


问:
How I can load a font file with PIL.ImageFont.truetype without specifying the absolute path?
When I write the code in Windows, this code can load the font file just fine:

```<code>ImageFont.truetype(filename='msyhbd.ttf', size=30);
</code>```

I guess the font location is registered in Windows registry.
But when I move the code to Ubuntu, and copy the font file over to /usr/share/fonts/, the code cannot locate the font:

```<code> self.font = core.getfont(font, size, index, encoding)
 IOError: cannot open resource
</code>```

How can I get PIL to find the ttf file without specifying the absolute path?

答: On mac, I simply copy the font file Arial.ttf to the project directory and everything works.</p>

Body:
When I write the code in Windows, this code can load the font file just fine:

ImageFont.truetype(filename='msyhbd.ttf', size=30);

I guess the font location is registered in Windows registry.
But when I move the code to Ubuntu, and copy the font file over to /usr/share/fonts/, the code cannot locate the font:

 self.font = core.getfont(font, size, index, encoding)
 IOError: cannot open resource

How can I get PIL to find the ttf file without specifying the absolute path?


答:
This seems working fine.

body{
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height:120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}
.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;

}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='logo'>The Realm MC</div>

<div class="topnav" id="myTopnav">
  <i class="fa fa-home" aria-hidden="true"></i>Home
  <i class="fa fa-play" aria-hidden="true"></i>Play
  <i class="fa fa-comment-o" aria-hidden="true"></i>Forums
  <i class="fa fa-heart-o" aria-hidden="true"></i>Donate
</div>
<div class='banner'>
    There are <?php echo $ServerStatus['numplayers'] . " out of " . $ServerStatus['maxplayers'] . " players online!"; ?>
</div>
<br/>
<div id='wrapper' style='text-align:center;'>
  <div class='about'>
    Lorem ipsum<br />
    dolor sit amet
  </div>

  <div class='stats'>
    Lorem ipsum<br />
    dolor sit amet
  </div>
</div></code>```

Title: Center All Elements to a Certain Width

Body:
This seems working fine.

body{
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height:120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}
.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;

}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}

<div class='logo'>The Realm MC</div>

<div class="topnav" id="myTopnav">
  <a href="#home" class='active'><i class="fa fa-home" aria-hidden="true"></i>Home</a>
  <a href="#play"><i class="fa fa-play" aria-hidden="true"></i>Play</a>
  <a href="/forum"><i class="fa fa-comment-o" aria-hidden="true"></i>Forums</a>
  <a href="#donate" style="float: right; margin-right: 30px;"><i class="fa fa-heart-o" aria-hidden="true"></i>Donate</a>
</div>
<div class='banner'>
    There are <?php echo $ServerStatus['numplayers'] . " out of " . $ServerStatus['maxplayers'] . " players online!"; ?>
</div>
<br/>
<div id='wrapper' style='text-align:center;'>
  <div class='about'>
    Lorem ipsum<br />
    dolor sit amet
  </div>

  <div class='stats'>
    Lorem ipsum<br />
    dolor sit amet
  </div>
</div>


问:
How do I filter through an associated resource column using a named_scope?
I have built a Ruby on Rails application that allows users to track their workouts.

User has_many :workouts

Workout belongs_to :user

I am attempting to call only workouts from male users. How do I write a named scope for Workout.rb to call only workouts from male users?

In my case, the user.sex column is a string that collects either Male or Female.

I am using rails 2.3.8 for this particular application.

答:
Try this:

```<code>class Workout

  belongs_to :user
  named_scope :all_male,   :joins => :user,
                           :conditions => ["users.sex = ?", "Male"]

  named_scope :all_female, :joins => :user,
                           :conditions => ["users.sex = ?", "Female"]

end
</code>```

Now you can use the scope as:

```<code>Workout.all_male
Workout.all_female
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try this:

class Workout

  belongs_to :user
  named_scope :all_male,   :joins => :user,
                           :conditions => ["users.sex = ?", "Male"]

  named_scope :all_female, :joins => :user,
                           :conditions => ["users.sex = ?", "Female"]

end

Now you can use the scope as:

Workout.all_male
Workout.all_female


问:
Change 'temperature' in RNN to generate text
I recently followed a tutorial to make a RNN to generate text:
I copied the python code exactly and sort of understand it as well.
My model has been trained for 20 epochs and it produces a long repetitive loop of 3 words:

```<code>"and the wour and the wour and the wour..."
</code>```

I have read in Andrej Kaparthy's blog that changing the temperature of the RNN changes its confidence:

Decreasing the temperature from 1 to some lower number (e.g. 0.5) makes the RNN more confident, but also more conservative in its samples.

I want to change this temperature level to reduce the confidence of the RNN in order for it to create new patterns, but as this is my first Machine Learning project I don't know how.

Here is my Python/keras code:

Generating Text File:

```<code># Generate Text
import sys
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils

filename = "king_lear.txt"
raw_text = open(filename).read()
raw_text = raw_text.lower()

chars = sorted(list(set(raw_text)))
char_to_int = dict((c, i) for i, c in enumerate(chars))
int_to_char = dict((i, c) for i, c in enumerate(chars))

n_chars = len(raw_text)
n_vocab = len(chars)
print "Total Characters: ", n_chars
print "Total Vocab: ", n_vocab

seq_length = 100
dataX = []
dataY = []
for i in range(0, n_chars - seq_length, 1):
    seq_in = raw_text[i:i + seq_length]
    seq_out = raw_text[i + seq_length]
    dataX.append([char_to_int[char] for char in seq_in])
    dataY.append(char_to_int[seq_out])
n_patterns = len(dataX)
print "Total Patterns: ", n_patterns

X = numpy.reshape(dataX, (n_patterns, seq_length, 1))

X = X / float(n_vocab)

y = np_utils.to_categorical(dataY)

model = Sequential()
model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))

filename = "weights-improvement-08-2.0298-bigger.hdf5"
model.load_weights(filename)
model.compile(loss='categorical_crossentropy', optimizer='adam')

start = numpy.random.randint(0, len(dataX)-1)
pattern = dataX[start]
print "Seed:"
print "\"", ''.join([int_to_char[value] for value in pattern]), "\""

for i in range(60):
    x = numpy.reshape(pattern, (1, len(pattern), 1))
    x = x / float(n_vocab)
    prediction = model.predict(x, verbose=0)
    index = numpy.argmax(prediction)
    result = int_to_char[index]
    seq_in = [int_to_char[value] for value in pattern]
    sys.stdout.write(result)
    pattern.append(index)
    pattern = pattern[1:len(pattern)]

print "\nDone."
</code>```

Learning File:

```<code># Learn Sentences
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils

filename = "king_lear.txt"
raw_text = open(filename).read()
raw_text = raw_text.lower()

chars = sorted(list(set(raw_text)))
char_to_int = dict((c, i) for i, c in enumerate(chars))

n_chars = len(raw_text)
n_vocab = len(chars)
print "Total Characters: ", n_chars
print "Total Vocab: ", n_vocab

seq_length = 100
dataX = []
dataY = []
for i in range(0, n_chars - seq_length, 1):
    seq_in = raw_text[i:i + seq_length]
    seq_out = raw_text[i + seq_length]
    dataX.append([char_to_int[char] for char in seq_in])
    dataY.append(char_to_int[seq_out])
n_patterns = len(dataX)
print "Total Patterns: ", n_patterns

X = numpy.reshape(dataX, (n_patterns, seq_length, 1))

X = X / float(n_vocab)

y = np_utils.to_categorical(dataY)

model = Sequential()
model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')

filepath="weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]

model.fit(X, y, epochs=50, batch_size=64, callbacks=callbacks_list)
</code>```

Please help me to do this. If there is anything wrong with this post, don't hesitate to correct me as it is my first question.
Thank you very much.

答:
Check out this issue on the Keras GitHub. You can add a Lambda layer before the softmax to divide by the temperature:

```<code>model.add(Lambda(lambda x: x / temp))
</code>```

According to Wiki:

For high temperatures, all actions have nearly the same probability and the lower the temperature, the more expected rewards affect the probability. For a low temperature, the probability of the action with the highest expected reward tends to 1.

Body:
I recently followed a tutorial to make a RNN to generate text:
I copied the python code exactly and sort of understand it as well.
My model has been trained for 20 epochs and it produces a long repetitive loop of 3 words:

"and the wour and the wour and the wour..."

I have read in Andrej Kaparthy's blog that changing the temperature of the RNN changes its confidence:

Decreasing the temperature from 1 to some lower number (e.g. 0.5) makes the RNN more confident, but also more conservative in its samples.

I want to change this temperature level to reduce the confidence of the RNN in order for it to create new patterns, but as this is my first Machine Learning project I don't know how.

Here is my Python/keras code:

Generating Text File:

# Generate Text
import sys
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils

filename = "king_lear.txt"
raw_text = open(filename).read()
raw_text = raw_text.lower()

chars = sorted(list(set(raw_text)))
char_to_int = dict((c, i) for i, c in enumerate(chars))
int_to_char = dict((i, c) for i, c in enumerate(chars))

n_chars = len(raw_text)
n_vocab = len(chars)
print "Total Characters: ", n_chars
print "Total Vocab: ", n_vocab

seq_length = 100
dataX = []
dataY = []
for i in range(0, n_chars - seq_length, 1):
    seq_in = raw_text[i:i + seq_length]
    seq_out = raw_text[i + seq_length]
    dataX.append([char_to_int[char] for char in seq_in])
    dataY.append(char_to_int[seq_out])
n_patterns = len(dataX)
print "Total Patterns: ", n_patterns

X = numpy.reshape(dataX, (n_patterns, seq_length, 1))

X = X / float(n_vocab)

y = np_utils.to_categorical(dataY)

model = Sequential()
model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))

filename = "weights-improvement-08-2.0298-bigger.hdf5"
model.load_weights(filename)
model.compile(loss='categorical_crossentropy', optimizer='adam')

start = numpy.random.randint(0, len(dataX)-1)
pattern = dataX[start]
print "Seed:"
print "\"", ''.join([int_to_char[value] for value in pattern]), "\""

for i in range(60):
    x = numpy.reshape(pattern, (1, len(pattern), 1))
    x = x / float(n_vocab)
    prediction = model.predict(x, verbose=0)
    index = numpy.argmax(prediction)
    result = int_to_char[index]
    seq_in = [int_to_char[value] for value in pattern]
    sys.stdout.write(result)
    pattern.append(index)
    pattern = pattern[1:len(pattern)]

print "\nDone."

Learning File:

# Learn Sentences
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils

filename = "king_lear.txt"
raw_text = open(filename).read()
raw_text = raw_text.lower()

chars = sorted(list(set(raw_text)))
char_to_int = dict((c, i) for i, c in enumerate(chars))

n_chars = len(raw_text)
n_vocab = len(chars)
print "Total Characters: ", n_chars
print "Total Vocab: ", n_vocab

seq_length = 100
dataX = []
dataY = []
for i in range(0, n_chars - seq_length, 1):
    seq_in = raw_text[i:i + seq_length]
    seq_out = raw_text[i + seq_length]
    dataX.append([char_to_int[char] for char in seq_in])
    dataY.append(char_to_int[seq_out])
n_patterns = len(dataX)
print "Total Patterns: ", n_patterns

X = numpy.reshape(dataX, (n_patterns, seq_length, 1))

X = X / float(n_vocab)

y = np_utils.to_categorical(dataY)

model = Sequential()
model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')

filepath="weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]

model.fit(X, y, epochs=50, batch_size=64, callbacks=callbacks_list)

Please help me to do this. If there is anything wrong with this post, don't hesitate to correct me as it is my first question.
Thank you very much.

Body:
Check out this issue on the Keras GitHub. You can add a Lambda layer before the softmax to divide by the temperature:

model.add(Lambda(lambda x: x / temp))

According to Wiki:

For high temperatures, all actions have nearly the same probability and the lower the temperature, the more expected rewards affect the probability. For a low temperature, the probability of the action with the highest expected reward tends to 1.


问:
json data not working on server
I retreived my json data using Jquery ajax. My data is:

```<code>[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"support","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]
</code>```

On Jquery Success i hold the data in a variable

```<code>var jsonData = JSON.parse(JSON.stringify(data));
</code>```

when i am trying to access checkNo. using jsonData[0].checkNo it yields undefined but when i check it using

```<code>console.log(jsonData)
</code>```

It outputs data which is same as top.

Note: This problem yields only on server but it is working fine on my localhost.

Edit:

Here is my ajax call:

```<code>jQuery.ajax({
url: postUrl,
data:queryString,
type: "POST",
success:function(data){
    switch(action) {
      case "edit":
      jsonData = JSON.parse(data); console.log(jsonData);
      //var jsssss = JSON.parse(JSON.stringify(data)); console.log(jsssss);
      $("#custEmail").val(jsonData[0].custEmail);
      $("#custName").val(jsonData[0].custName);
      $("#custCheckNo").val(jsonData[0].checkNo);
      $("#edit_model").modal();
        break;
     //some more code
}
});
</code>```

答:
Possibly your are stringifying your data two times

You don't have to var jsonData = JSON.parse(JSON.stringify(data));

else do this

```<code>var jsonData = JSON.parse(data);
</code>```

SNIPPET

var data  ='[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"Geeks Help","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]';

var jsonData = JSON.parse(data); // remove your stringify

console.log(jsonData[0].checkNo)```
</div>
</div>
</p>

<p>Also, if you are doing anything like this in your ajax call</p>

```$.ajax({
      type: "POST",
      contentType: "application/json",
      url: '/Hello',
      data: { name: 'norm' },
      dataType: "json"
      success: function(data){
        //Here your data is already a parsed object
        var jsonData = data;
        console.log(jsonData[0].checkNo)
      }
   });
```

Title: json data not working on server

Body:
I retreived my json data using Jquery ajax. My data is:

[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"support","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]

On Jquery Success i hold the data in a variable

var jsonData = JSON.parse(JSON.stringify(data));

when i am trying to access checkNo. using jsonData[0].checkNo it yields undefined but when i check it using

console.log(jsonData)

It outputs data which is same as top.

Note: This problem yields only on server but it is working fine on my localhost.

Edit:

Here is my ajax call:

jQuery.ajax({
url: postUrl,
data:queryString,
type: "POST",
success:function(data){
    switch(action) {
      case "edit":
      jsonData = JSON.parse(data); console.log(jsonData);
      //var jsssss = JSON.parse(JSON.stringify(data)); console.log(jsssss);
      $("#custEmail").val(jsonData[0].custEmail);
      $("#custName").val(jsonData[0].custName);
      $("#custCheckNo").val(jsonData[0].checkNo);
      $("#edit_model").modal();
        break;
     //some more code
}
});

Body:
Possibly your are stringifying your data two times

You don't have to var jsonData = JSON.parse(JSON.stringify(data));

else do this

var jsonData = JSON.parse(data);

SNIPPET

var data  ='[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"Geeks Help","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]';

var jsonData = JSON.parse(data); // remove your stringify

console.log(jsonData[0].checkNo)

Also, if you are doing anything like this in your ajax call

$.ajax({
      type: "POST",
      contentType: "application/json",
      url: '/Hello',
      data: { name: 'norm' },
      dataType: "json"
      success: function(data){
        //Here your data is already a parsed object
        var jsonData = data;
        console.log(jsonData[0].checkNo)
      }
   });


问:
Search form has an Enum dropdown field whose value may be null (none selected) once it reaches my lambda Linq query
Basically, if the user selected no option from the dropdown combo, I want it to be left out from my Linq query that looks something like this:

```<code>// this is how I manage the form post data, please
// propose a better way if you know one
Dictionary<string, string> formdata = new Dictionary<string, string>();

foreach(string key in Request.Form.AllKeys)
{
    formdata.Add(key, Request.Form[key]);
}

// getting the title
string title = "";
formdata.TryGetValue("postedTitle", out title);

// getting the level
string levelString = "";
formdata.TryGetValue("postedLevel", out levelString );

int level = -1;
if(levelString != "")
{
    Int32.TryParse(levelString , out level);
}

var model = new FooIndexVM
{
    Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title) && w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....
</code>```

Since I'm getting either 0 or -1 for the level -- I need a way to gracefully leave the Enum part from the query completely. I will also later add some additional fields similar to this one (may be unselected) so the solution will also work for those, I guess.

答:
You can chain Where commands so this line:

```<code>Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title) && w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....
</code>```

Could be rewritten to be this without changing its behaviour (multiple Wheres effectively become combined with &&s):

```<code>Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title)).Where(w => w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....
</code>```

This then means that you can add some logic around whether to apply the second Where or not like this, for example:

```<code>var query = _ctx.SomeDbSet.Where(w => w.Title.Contains(title));
if (level != -1)
{
  query = query.Where(w => w.Level == (Level?)level.Value)
}

Foos = query.Select(x => new FooBarRow
            {
                FooBarId = x.Id,
</code>```

Body:
Basically, if the user selected no option from the dropdown combo, I want it to be left out from my Linq query that looks something like this:

// this is how I manage the form post data, please
// propose a better way if you know one
Dictionary<string, string> formdata = new Dictionary<string, string>();

foreach(string key in Request.Form.AllKeys)
{
    formdata.Add(key, Request.Form[key]);
}

// getting the title
string title = "";
formdata.TryGetValue("postedTitle", out title);

// getting the level
string levelString = "";
formdata.TryGetValue("postedLevel", out levelString );

int level = -1;
if(levelString != "")
{
    Int32.TryParse(levelString , out level);
}

var model = new FooIndexVM
{
    Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title) && w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....

Since I'm getting either 0 or -1 for the level -- I need a way to gracefully leave the Enum part from the query completely. I will also later add some additional fields similar to this one (may be unselected) so the solution will also work for those, I guess.

Body:
You can chain Where commands so this line:

Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title) && w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....

Could be rewritten to be this without changing its behaviour (multiple Wheres effectively become combined with &&s):

Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title)).Where(w => w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....

This then means that you can add some logic around whether to apply the second Where or not like this, for example:

var query = _ctx.SomeDbSet.Where(w => w.Title.Contains(title));
if (level != -1)
{
  query = query.Where(w => w.Level == (Level?)level.Value)
}

Foos = query.Select(x => new FooBarRow
            {
                FooBarId = x.Id,


问:
Removing 'Back' button
I'm using React-Navigation and I'm having trouble with the navigation bar.
I have a page called LoginScreen which moves the user to the HomeScreen after logging in.
The problem I have is that I have a 'back' button in the homescreen so I can go back to the loginscreen (which I don't want) this is the code:

LoginScreen (where I navigate to the home screen):

```<code>handlePress(navigate){
    firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(firebaseUser){
      //Success, move to homepage.
      navigate("Home");
    }).catch(function(error){
      //Failed to log in, print error.
    });
}
</code>```

navigate is inside render():

```<code>const { navigate } = this.props.navigation;
</code>```

this is where I call handlePress:

```<code><TouchableOpacity style={styles.logBtn} onPress={()=>this.handlePress(navigate)}>
  <Text style={styles.logTxt}>
  Login
  </Text>
</TouchableOpacity>
</code>```

I searched a little and tried writing navigate.replace("Home"); in handlePress but it just won't navigate then.

What am I doing wrong?

答:
I think the best thing for you to do is to reset the navigation which you can do with the reset:

```<code>import { NavigationActions } from 'react-navigation';

    const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'Home'})
      ]
    })
    this.props.navigation.dispatch.(resetAction);
</code>```

You can find this or read more about it here react-navigation-doc

or you can change the back button icon with its function in your HomeScreen navigation configuration

```<code>static navigationOptions  = {
        title: 'Home',
        header: ({ navigate }) => {
        {/* left here refers to the left back button */}
            let left = (
                <TouchableOpacity onPress={() => navigate('Profile')} >
                    <Icon name="ios-menu-outline"
                    size={25} style={{ paddingRight: 5, paddingLeft: 20 }}
                    color="#ffffff" />
                </TouchableOpacity>
            );
            let style = { backgroundColor: '#00AFEF',elevation: 0,shadowOpacity: 0,};
            let titleStyle = { color: '#ffff', fontSize: 25, fontFamily: 'Arial' };
            return { left, style, titleStyle }
        },
    }
</code>```

Title: Removing 'Back' button

Body:
I'm using React-Navigation and I'm having trouble with the navigation bar.
I have a page called LoginScreen which moves the user to the HomeScreen after logging in.
The problem I have is that I have a 'back' button in the homescreen so I can go back to the loginscreen (which I don't want) this is the code:

LoginScreen (where I navigate to the home screen):

handlePress(navigate){
    firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(firebaseUser){
      //Success, move to homepage.
      navigate("Home");
    }).catch(function(error){
      //Failed to log in, print error.
    });
}

navigate is inside render():

const { navigate } = this.props.navigation;

this is where I call handlePress:

<TouchableOpacity style={styles.logBtn} onPress={()=>this.handlePress(navigate)}>
  <Text style={styles.logTxt}>
  Login
  </Text>
</TouchableOpacity>

I searched a little and tried writing navigate.replace("Home"); in handlePress but it just won't navigate then.

What am I doing wrong?

Body:
I think the best thing for you to do is to reset the navigation which you can do with the reset:

import { NavigationActions } from 'react-navigation';

    const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'Home'})
      ]
    })
    this.props.navigation.dispatch.(resetAction);

You can find this or read more about it here react-navigation-doc

or you can change the back button icon with its function in your HomeScreen navigation configuration

static navigationOptions  = {
        title: 'Home',
        header: ({ navigate }) => {
        {/* left here refers to the left back button */}
            let left = (
                <TouchableOpacity onPress={() => navigate('Profile')} >
                    <Icon name="ios-menu-outline"
                    size={25} style={{ paddingRight: 5, paddingLeft: 20 }}
                    color="#ffffff" />
                </TouchableOpacity>
            );
            let style = { backgroundColor: '#00AFEF',elevation: 0,shadowOpacity: 0,};
            let titleStyle = { color: '#ffff', fontSize: 25, fontFamily: 'Arial' };
            return { left, style, titleStyle }
        },
    }


问:
dpdk-pdump "no driver found for net_pcap_rx_0"
Ubuntu 16, DPDK 16

I have a couple of DPDK-based applications sending packets between two machines and want to capture them with dpdk-pdump. I'm running it with sudo ./build/app/pdump/dpdk-pdump -c 0x00f -- --pdump 'port=0,queue=*,rx-dev=/tmp/rx.pcap', and I see this output and a crash:

EAL: no driver found for eth_pcap_rx_0
EAL: Driver, cannot attach the device
EAL: Error - exiting with code: 1
Cause: vdev creation failed:create_mp_ring_vdev:736

My DPDK was compiled like this: hostname:~/dpdk-stable-16.07.1/x86_64-native-linuxapp-gcc# CONFIG_RTE_LIBRTE_PMD_PCAP=y make (also did export CONFIG_RTE_LIBRTE_PMD_PCAP=y before) so that it builds with libpcap support, as the documentation said to do. And my system has libpcap installed. The make script output shows == Build lib/librte_pdump. Looking around online, I've only found one person with a similar issue, and the suggested fix was what I tried. Is there something else I have to do?

I tried installing the DPDK Ubuntu package's version of the tool and using the dpdk-pdump command, same result.

答:
Unfortunately, setting CONFIG_RTE_LIBRTE_PMD_PCAP=y in command line does not work, so the compiled dpdk-pdump have no pcap support.

In config/common_base set CONFIG_RTE_LIBRTE_PMD_PCAP=y, remove your build directory and recompile the DPDK.

Make sure the .config file you your build directory has CONFIG_RTE_LIBRTE_PMD_PCAP=y


问:
Jquery accordion
I have set up jQuery accordion in my page as

```<code>$(document).ready(function() {
        $("#MGH").accordion('activate', 1);
    });
</code>```

Now inside this div I have one button onclick of which I will validate and show some alert.
My problem is whenever I am clicking ok in the alert this accordion is getting fired.How to prevent this?

答:
Try to avoid page re-loading, because while you are clicking on the button, page gets re-loaded and the accordion gets fired. You can overcome this by declaring retrun false while you click on the button.
Hope this works for you.</p>

Title: Jquery accordion

Body:
I have set up jQuery accordion in my page as

$(document).ready(function() {
        $("#MGH").accordion('activate', 1);
    });

Now inside this div I have one button onclick of which I will validate and show some alert.
My problem is whenever I am clicking ok in the alert this accordion is getting fired.How to prevent this?


问:
Android mosby Access to view from presenter
I would like to access to view widgets such as TextView or EditText from presenter, how can i do that,

in my activity main i want to change scheduleDateTimeNotify text from presenter

```<code>public class ActivityChannelContent extends MvpActivity<ActivityChannelContentView, ActivityChannelContentPresenter>
        implements ActivityChannelContentView{

    @BindView(R.id.scheduleDateTimeNotify)
    TextView scheduleDateTimeNotify;

    @NonNull
    @Override
    public ActivityChannelContentPresenter createPresenter() {
        return new ActivityChannelContentPresenterImpl(getApplicationContext());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_channel_content);
        ButterKnife.bind(this);
    }
}
</code>```

Presenter:

```<code>public interface ActivityChannelContentPresenter extends MvpPresenter<ActivityChannelContentView> {
}
</code>```

ActivityChannelContentPresenterImpl:

```<code>public class ActivityChannelContentPresenterImpl extends MvpBasePresenter<ActivityChannelContentView> implements ActivityChannelContentPresenter {
    private final ActivityChannelContentModel model;

    public ActivityChannelContentPresenterImpl(Context context) {
        model = new ActivityChannelContentModel(context);
    }
}
</code>```

ActivityChannelContentViewModel:

```<code>public class ActivityChannelContentViewModel {
    private final Context context;

    public ActivityChannelContentViewModel(Context mContext) {
        context = mContext;
    }
}
</code>```

ActivityChannelContentView interface:

```<code>public interface ActivityChannelContentView extends MvpView {
}
</code>```

答:
I have worked on MVP design pattern and you can set text on TextView in View with using Presenter logic. For example:</p>

```<code>public interface MContract {

    interface View{
        void setText(String value)
    }

    interface Presenter extends BasePresenter {
        void addData(String value);
    }
}

public class MPresenter implements MContract.Presenter {
    private MContract.View mView;

    @Override
    public void addData(String value) {
            mView.setText(value);
    }
}

public class Activity extends AppCompatActivity  implements MContract.View {

 @Override
    public void setText(String value) {textview.setText(value);}
}
</code>```

Body:
I would like to access to view widgets such as TextView or EditText from presenter, how can i do that,

in my activity main i want to change scheduleDateTimeNotify text from presenter

public class ActivityChannelContent extends MvpActivity<ActivityChannelContentView, ActivityChannelContentPresenter>
        implements ActivityChannelContentView{

    @BindView(R.id.scheduleDateTimeNotify)
    TextView scheduleDateTimeNotify;

    @NonNull
    @Override
    public ActivityChannelContentPresenter createPresenter() {
        return new ActivityChannelContentPresenterImpl(getApplicationContext());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_channel_content);
        ButterKnife.bind(this);
    }
}

Presenter:

public interface ActivityChannelContentPresenter extends MvpPresenter<ActivityChannelContentView> {
}

ActivityChannelContentPresenterImpl:

public class ActivityChannelContentPresenterImpl extends MvpBasePresenter<ActivityChannelContentView> implements ActivityChannelContentPresenter {
    private final ActivityChannelContentModel model;

    public ActivityChannelContentPresenterImpl(Context context) {
        model = new ActivityChannelContentModel(context);
    }
}

ActivityChannelContentViewModel:

public class ActivityChannelContentViewModel {
    private final Context context;

    public ActivityChannelContentViewModel(Context mContext) {
        context = mContext;
    }
}

ActivityChannelContentView interface:

public interface ActivityChannelContentView extends MvpView {
}

Body:
I have worked on MVP design pattern and you can set text on TextView in View with using Presenter logic. For example:

public interface MContract {

    interface View{
        void setText(String value)
    }

    interface Presenter extends BasePresenter {
        void addData(String value);
    }
}

public class MPresenter implements MContract.Presenter {
    private MContract.View mView;

    @Override
    public void addData(String value) {
            mView.setText(value);
    }
}

public class Activity extends AppCompatActivity  implements MContract.View {

 @Override
    public void setText(String value) {textview.setText(value);}
}


问:
Value is undefined returning model in JS Odoo POS
I'm trying to overwrite Orderline price in POS Odoo

My price.js

```<code>get_unit_display_price: function(){
    var self = this;
    var line = self.export_as_JSON();
    var product = this.pos.db.get_product_by_id(line.product_id);
    fields.product_id  = line.product_id;
    fields.pricelist_id   = this.pos.config.pricelist_id[0];
    fields.uom = product.uom_id;
    fields.line_qty = line.qty;
    fields.price_unit = line.price_unit;
    var model = new Model('pos.order');
     this.total_price = model.call('calculate_price',
            [0, fields]).done(function(result){
                 total_price = result['total_price'];
                 return  result['total_price'];
            });

}
</code>```

price.xml

```<code>    <t t-jquery=".price" t-operation="append">
        <t t-esc="widget.format_currency(line.get_unit_display_price)"/>
    </t>
</code>```

I'm getting value total_price from Model (price.py)
But returning is undefined in get_unit_display_price in xml file.

How to set value in xml from js after execution of new model function (js value from model) ?.

答:
```<code>get_orderline: function() {
    var order = this.pos.get_order();
    var orderlines = order.orderlines.models;
    var all_lines = [];
    for (var i = 0; i < orderlines.length; i++) {
        var line = orderlines[i]
        if (line) {
            all_lines.push({
                'product_id': line.product.id,
                'qty': line.quantity,
                'price': line.get_display_price(),
            })
        }
    }
    return all_lines
},
</code>```

Body:
I'm trying to overwrite Orderline price in POS Odoo

My price.js

get_unit_display_price: function(){
    var self = this;
    var line = self.export_as_JSON();
    var product = this.pos.db.get_product_by_id(line.product_id);
    fields.product_id  = line.product_id;
    fields.pricelist_id   = this.pos.config.pricelist_id[0];
    fields.uom = product.uom_id;
    fields.line_qty = line.qty;
    fields.price_unit = line.price_unit;
    var model = new Model('pos.order');
     this.total_price = model.call('calculate_price',
            [0, fields]).done(function(result){
                 total_price = result['total_price'];
                 return  result['total_price'];
            });

}

price.xml

    <t t-jquery=".price" t-operation="append">
        <t t-esc="widget.format_currency(line.get_unit_display_price)"/>
    </t>

I'm getting value total_price from Model (price.py)
But returning is undefined in get_unit_display_price in xml file.

How to set value in xml from js after execution of new model function (js value from model) ?.


问:
How to automate pie charts and bar graphs using selenium?
I just want to automate the chart action in Selenium? Web-driver/Java
(Kendo Ui)

how can i click on the chart segments??

My graph is exactly same link in the below link

http://demos.telerik.com/kendo-ui/pie-charts/index

答:
Finding xpath of the elements inside the svg tag is bit different than finding xpath of other elements.

Suppose your URL is:

https://developers.google.com/chart/interactive/docs/gallery/piechart

If you have to find the text of the element in the pie-chart then you can use the code mentioned below:

driver.findElement(By.xpath(" //[@id='piechart']/div/div[1]/div/[name()='svg']/[name()='g'][4]/[name()='text']")).getText();


问:
I want to get inner tag value for the md-autocomplete but I am not able to get text valu , Find code below
HTML:

```<code><md-virtual-repeat-container role="presentation" ng-class="{ 'md-not-found': $mdAutocompleteCtrl.notFoundVisible() }" class="md-autocomplete-suggestions-container md-whiteframe-z1 md-virtual-repeat-container md-orient-vertical ng-hide" ng-hide="$mdAutocompleteCtrl.hidden" ng-mouseup="$mdAutocompleteCtrl.mouseUp()" ng-mouseleave="$mdAutocompleteCtrl.listLeave()" ng-mouseenter="$mdAutocompleteCtrl.listEnter()" md-auto-shrink-min="1" md-auto-shrink="" aria-hidden="true" style="left: 676.483px; min-width: 270.717px; max-width: 941.2px; top: auto; bottom: -147.917px; max-height: 240px; height: 96px;">
<div class="md-virtual-repeat-scroller">
    <div class="md-virtual-repeat-sizer" style="height: 96px;"></div>
    <div class="md-virtual-repeat-offsetter">
        <ul id="ul-3" ng-class="::menuClass" class="md-autocomplete-suggestions">
            <!-- mdVirtualRepeat: item in $mdAutocompleteCtrl.matches -->
            <li md-extra-name="$mdAutocompleteCtrl.itemName" ng-click="$mdAutocompleteCtrl.select($index)" ng-class="{ selected: $index === $mdAutocompleteCtrl.index }" md-virtual-repeat="item in $mdAutocompleteCtrl.matches" class="ng-scope" role="button" tabindex="0">
                <!-- mdAutocompleteParentScope: -->
                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    <span md-highlight-text="searchText1" id="pincodeCity"><span class="highlight">110081</span>,Delhi</span>
                </md-autocomplete-parent-scope>
            </li>
            <li md-extra-name="$mdAutocompleteCtrl.itemName" ng-click="$mdAutocompleteCtrl.select($index)" ng-class="{ selected: $index === $mdAutocompleteCtrl.index }" md-virtual-repeat="item in $mdAutocompleteCtrl.matches" class="ng-scope" role="button" tabindex="0">
                <!-- mdAutocompleteParentScope: -->
                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    <span md-highlight-text="searchText1" id="pincodeCity"><span class="highlight">110081</span>,Nizampur</span>
                </md-autocomplete-parent-scope>
            </li>
            <!-- ngIf: $mdAutocompleteCtrl.notFoundVisible() -->
        </ul>
    </div>
</div>
</code>```

Protractor code:

```<code>let foo = $$('.md-autocomplete-suggestions').$$('.highlight');
    expect(foo.getText()).toEqual([',Delhi', ',Nizampur']);
</code>```

I have tried with above code, but it didn't work.

Is there any way I can find/Select text field in a span tag.

答:
In Protractor, getText() returns a promise that you need to resolve. So when you're using your expect, you need to do that post you've resolved the promise.

I suppose you can do something like

```<code>     let foo = $$('.md-autocomplete-suggestions').$$('.highlight>span[1]');
      foo.getText().then(function(text){
       expect(text).toEqual('Delhi');

       })
</code>```

Body:
HTML:

<md-virtual-repeat-container role="presentation" ng-class="{ 'md-not-found': $mdAutocompleteCtrl.notFoundVisible() }" class="md-autocomplete-suggestions-container md-whiteframe-z1 md-virtual-repeat-container md-orient-vertical ng-hide" ng-hide="$mdAutocompleteCtrl.hidden" ng-mouseup="$mdAutocompleteCtrl.mouseUp()" ng-mouseleave="$mdAutocompleteCtrl.listLeave()" ng-mouseenter="$mdAutocompleteCtrl.listEnter()" md-auto-shrink-min="1" md-auto-shrink="" aria-hidden="true" style="left: 676.483px; min-width: 270.717px; max-width: 941.2px; top: auto; bottom: -147.917px; max-height: 240px; height: 96px;">

                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    110081,Delhi
                </md-autocomplete-parent-scope>

                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    110081,Nizampur
                </md-autocomplete-parent-scope>

Protractor code:

let foo = $$('.md-autocomplete-suggestions').$$('.highlight');
    expect(foo.getText()).toEqual([',Delhi', ',Nizampur']);

I have tried with above code, but it didn't work.

Is there any way I can find/Select text field in a span tag.

Body:
In Protractor, getText() returns a promise that you need to resolve. So when you're using your expect, you need to do that post you've resolved the promise.

I suppose you can do something like

     let foo = $$('.md-autocomplete-suggestions').$$('.highlight>span[1]');
      foo.getText().then(function(text){
       expect(text).toEqual('Delhi');

       })


问:
How to debug EXC_BREAKPOINT (SIGTRAP) in Xcode
I know this question might sound stupid but I hope to understand what is the problem in this crash report that generated in Xcode. I have no idea which view controller/page or which feature it crashes at. How to study a crash report? Anyone please help..</p>

```<code>Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001000ba1d8
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [0]
Triggered by Thread:  0

Thread 0 name:
Thread 0 Crashed:
0   myfirstapp                  0x00000001000ba1d8 0x1000b0000 + 41432
1   myfirstapp                  0x00000001000ba208 0x1000b0000 + 41480
2   UIKit                           0x0000000197b3e754 -[UIViewController _setViewAppearState:isAnimating:] + 624 (UIViewController.m:3801)
3   UIKit                           0x0000000197b3e4cc -[UIViewController __viewWillAppear:] + 156 (UIViewController.m:3911)
4   UIKit                           0x0000000197bdf760 -[UINavigationController _startTransition:fromViewController:toViewController:] + 784 (UINavigationController.m:4824)
5   UIKit                           0x0000000197bdef28 -[UINavigationController _startDeferredTransitionIfNeeded:] + 856 (UINavigationController.m:4971)
6   UIKit                           0x0000000197bdeadc -[UINavigationController __viewWillLayoutSubviews] + 64 (UINavigationController.m:5224)
7   UIKit                           0x0000000197bdea40 -[UILayoutContainerView layoutSubviews] + 188 (UILayoutContainerView.m:86)
8   UIKit                           0x0000000197b23a80 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1196 (UIView.m:14198)
9   QuartzCore                      0x0000000194fd19d8 -[CALayer layoutSublayers] + 148 (CALayer.mm:8926)
10  QuartzCore                      0x0000000194fc64cc CA::Layer::layout_if_needed(CA::Transaction*) + 292 (CALayer.mm:8806)
11  QuartzCore                      0x0000000194fc638c CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32 (CALayer.mm:2345)
12  QuartzCore                      0x0000000194f433e0 CA::Context::commit_transaction(CA::Transaction*) + 252 (CAContextInternal.mm:1683)
13  QuartzCore                      0x0000000194f6aa68 CA::Transaction::commit() + 512 (CATransactionInternal.mm:419)
14  QuartzCore                      0x0000000194f6b488 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 120 (CATransactionInternal.mm:778)
15  CoreFoundation                  0x0000000191c1e0c0 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32 (CFRunLoop.c:1802)
16  CoreFoundation                  0x0000000191c1bcf0 __CFRunLoopDoObservers + 372 (CFRunLoop.c:1898)
17  CoreFoundation                  0x0000000191c1c180 __CFRunLoopRun + 1024 (CFRunLoop.c:2849)
18  CoreFoundation                  0x0000000191b4a2b8 CFRunLoopRunSpecific + 444 (CFRunLoop.c:3113)
19  GraphicsServices                0x00000001935fe198 GSEventRunModal + 180 (GSEvent.c:2245)
20  UIKit                           0x0000000197b917fc -[UIApplication _run] + 684 (UIApplication.m:2650)
21  UIKit                           0x0000000197b8c534 UIApplicationMain + 208 (UIApplication.m:4092)
22  myfirstapp                  0x00000001000b7b54 0x1000b0000 + 31572
23  libdyld.dylib                   0x0000000190b2d5b8 start + 4
</code>```

答: You can use the po command in the debugger console or add na exception breakpoint in Xcode breakpoint setting section.

Body:
I know this question might sound stupid but I hope to understand what is the problem in this crash report that generated in Xcode. I have no idea which view controller/page or which feature it crashes at. How to study a crash report? Anyone please help..

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001000ba1d8
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [0]
Triggered by Thread:  0

Thread 0 name:
Thread 0 Crashed:
0   myfirstapp                  0x00000001000ba1d8 0x1000b0000 + 41432
1   myfirstapp                  0x00000001000ba208 0x1000b0000 + 41480
2   UIKit                           0x0000000197b3e754 -[UIViewController _setViewAppearState:isAnimating:] + 624 (UIViewController.m:3801)
3   UIKit                           0x0000000197b3e4cc -[UIViewController __viewWillAppear:] + 156 (UIViewController.m:3911)
4   UIKit                           0x0000000197bdf760 -[UINavigationController _startTransition:fromViewController:toViewController:] + 784 (UINavigationController.m:4824)
5   UIKit                           0x0000000197bdef28 -[UINavigationController _startDeferredTransitionIfNeeded:] + 856 (UINavigationController.m:4971)
6   UIKit                           0x0000000197bdeadc -[UINavigationController __viewWillLayoutSubviews] + 64 (UINavigationController.m:5224)
7   UIKit                           0x0000000197bdea40 -[UILayoutContainerView layoutSubviews] + 188 (UILayoutContainerView.m:86)
8   UIKit                           0x0000000197b23a80 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1196 (UIView.m:14198)
9   QuartzCore                      0x0000000194fd19d8 -[CALayer layoutSublayers] + 148 (CALayer.mm:8926)
10  QuartzCore                      0x0000000194fc64cc CA::Layer::layout_if_needed(CA::Transaction*) + 292 (CALayer.mm:8806)
11  QuartzCore                      0x0000000194fc638c CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32 (CALayer.mm:2345)
12  QuartzCore                      0x0000000194f433e0 CA::Context::commit_transaction(CA::Transaction*) + 252 (CAContextInternal.mm:1683)
13  QuartzCore                      0x0000000194f6aa68 CA::Transaction::commit() + 512 (CATransactionInternal.mm:419)
14  QuartzCore                      0x0000000194f6b488 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 120 (CATransactionInternal.mm:778)
15  CoreFoundation                  0x0000000191c1e0c0 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32 (CFRunLoop.c:1802)
16  CoreFoundation                  0x0000000191c1bcf0 __CFRunLoopDoObservers + 372 (CFRunLoop.c:1898)
17  CoreFoundation                  0x0000000191c1c180 __CFRunLoopRun + 1024 (CFRunLoop.c:2849)
18  CoreFoundation                  0x0000000191b4a2b8 CFRunLoopRunSpecific + 444 (CFRunLoop.c:3113)
19  GraphicsServices                0x00000001935fe198 GSEventRunModal + 180 (GSEvent.c:2245)
20  UIKit                           0x0000000197b917fc -[UIApplication _run] + 684 (UIApplication.m:2650)
21  UIKit                           0x0000000197b8c534 UIApplicationMain + 208 (UIApplication.m:4092)
22  myfirstapp                  0x00000001000b7b54 0x1000b0000 + 31572
23  libdyld.dylib                   0x0000000190b2d5b8 start + 4

ContentLicense: CC BY-SA 4.0


问:
how to correctly sort labels on axis?
I'm trying to create a waterfall chart using ggplot2. My data:

```<code>> PctCtr
   Index Volatility sign id        end      start
1    WMT 0.04894867  pos  1 0.04894867 0.00000000
2    MMM 0.09225684  pos  2 0.14120551 0.04894867
3    AIG 0.18997607  pos  3 0.33118159 0.14120551
4   AAPL 0.11067473  pos  4 0.44185632 0.33118159
5     KO 0.05972203  pos  5 0.50157835 0.44185632
6   COST 0.06088945  pos  6 0.56246780 0.50157835
7      C 0.16428627  pos  7 0.72675407 0.56246780
8   AMZN 0.12803944  pos  8 0.85479351 0.72675407
9    ICE 0.09104894  pos  9 0.94584245 0.85479351
10   VTR 0.05415755  pos 10 1.00000000 0.94584245
11 Total 1.00000000  pos 11 0.00000000 1.00000000
</code>```

And my code:

```<code>GF = ggplot(PctCtr, aes(Volatility, fill = sign)) +
  geom_rect(aes(Index,
                xmin = id - 0.475,
                xmax = id + 0.475,
                ymin = end,
                ymax = start)) +
  scale_y_continuous(labels = percent)
  scale_x_discrete("", breaks = levels(PctCtr$Index), labels = levels(PctCtr$Index))

GF
</code>```

The resulting chart:

As you can see, the names on x-axis are messed up. I think it is because of levels() function as when I look at it, it returns alphabetically sorted values:

```<code>> levels(PctCtr$Index)
 [1] "AAPL"  "AIG"   "AMZN"  "C"     "COST"  "ICE"   "KO"    "MMM"   "Total"
[10] "VTR"   "WMT"
</code>```

Please help me fix this. Thanks.

答:
You can just factor and change the levels of the Index column before the plot</p>

```<code>PctCtr$Index <- factor(PctCtr$Index, levels=unique(PctCtr[,"Index"]))
</code>```

Title: how to correctly sort labels on axis?

Body:
I'm trying to create a waterfall chart using ggplot2. My data:

> PctCtr
   Index Volatility sign id        end      start
1    WMT 0.04894867  pos  1 0.04894867 0.00000000
2    MMM 0.09225684  pos  2 0.14120551 0.04894867
3    AIG 0.18997607  pos  3 0.33118159 0.14120551
4   AAPL 0.11067473  pos  4 0.44185632 0.33118159
5     KO 0.05972203  pos  5 0.50157835 0.44185632
6   COST 0.06088945  pos  6 0.56246780 0.50157835
7      C 0.16428627  pos  7 0.72675407 0.56246780
8   AMZN 0.12803944  pos  8 0.85479351 0.72675407
9    ICE 0.09104894  pos  9 0.94584245 0.85479351
10   VTR 0.05415755  pos 10 1.00000000 0.94584245
11 Total 1.00000000  pos 11 0.00000000 1.00000000

And my code:

GF = ggplot(PctCtr, aes(Volatility, fill = sign)) +
  geom_rect(aes(Index,
                xmin = id - 0.475,
                xmax = id + 0.475,
                ymin = end,
                ymax = start)) +
  scale_y_continuous(labels = percent)
  scale_x_discrete("", breaks = levels(PctCtr$Index), labels = levels(PctCtr$Index))

GF

The resulting chart:

As you can see, the names on x-axis are messed up. I think it is because of levels() function as when I look at it, it returns alphabetically sorted values:

> levels(PctCtr$Index)
 [1] "AAPL"  "AIG"   "AMZN"  "C"     "COST"  "ICE"   "KO"    "MMM"   "Total"
[10] "VTR"   "WMT"

Please help me fix this. Thanks.

Body:
You can just factor and change the levels of the Index column before the plot

PctCtr$Index <- factor(PctCtr$Index, levels=unique(PctCtr[,"Index"]))


问:
Angular2 - Router navigate with param (RC.4)
I'm working on the new router with RC.4, on the http error codes. I'm trying to send a parameter through the URL but I have a "character issue"...

Here is my call : this._router.navigate(['/error', { errorCode: '401' }]);

And this is the URL, which contains a ";" instead of a "?" : http://localhost:3000/error;errorCode=401

What I want : http://localhost:3000/error?errorCode=401

Because when I am reading this URL, it only works with this "?" :

```<code>this._router.routerState.queryParams.subscribe(params => {
        let errorCode = params['errorCode'];
        ...
</code>```

(Optional - app.routes.ts) :

```<code>{
    path: 'error',
    component: ErrorComponent
},
</code>```

I searched on internet but didn't find anything about it, how can I change the ";" or maybe how can I read error;errorCode=401 ?

答:
```<code>let queryParams = {
  status: 1,
  string: 'abc',
};
this._router.navigate(['/path'], { queryParams: queryParams });
</code>```

Body:
I'm working on the new router with RC.4, on the http error codes. I'm trying to send a parameter through the URL but I have a "character issue"...

Here is my call : this._router.navigate(['/error', { errorCode: '401' }]);

And this is the URL, which contains a ";" instead of a "?" : http://localhost:3000/error;errorCode=401

What I want : http://localhost:3000/error?errorCode=401

Because when I am reading this URL, it only works with this "?" :

this._router.routerState.queryParams.subscribe(params => {
        let errorCode = params['errorCode'];
        ...

(Optional - app.routes.ts) :

{
    path: 'error',
    component: ErrorComponent
},

I searched on internet but didn't find anything about it, how can I change the ";" or maybe how can I read error;errorCode=401 ?


问:
WordPress adds paragraphs around shortcode
I'm trying to create an enclosing shortcode that should be inline with regular text. So I would like to use it like this:

Vestibulum ac diam sit amet quam vehicula [caption]elementum sed sit amet dui[/caption]. Proin eget tortor risus. Vivamus suscipit tortor eget felis porttitor volutpat.

When doing this and saving the post, WordPress will automatically wrap paragraph tags around the shortcode. Like this:

Vestibulum ac diam sit amet quam vehicula

[caption]elementum sed sit amet dui[/caption]

. Proin eget tortor risus. Vivamus suscipit tortor eget felis porttitor volutpat.

What's the best way to disable this behaviour? Multiple people suggested moving the wp_autop filter to after the execution of the shortcode, but I believe this will only work for content in the shortcode, not for the wrapping of the shortcode itself.

Also, there's the shortcode_unautop function that should stop WordPress from wrapping the shortcodes, but I'm not sure if it works right, at least I can't seem to get it to work.

My shortcode now looks like this:

function caption_shortcode( $atts, $content = null ) {
    return '' . $content . '';
}
add_shortcode( 'caption', 'caption_shortcode' );

答:
You can use shortcode_unautop() function. For details check here.

Try like this:

```<code>function caption_shortcode( $atts, $content = null ) {
    return '<span class="caption">' . shortcode_unautop($content) . '</span>';
}
add_shortcode( 'caption', 'caption_shortcode' );
</code>```

Body:
You can use shortcode_unautop() function. For details check here.

Try like this:

function caption_shortcode( $atts, $content = null ) {
    return '<span class="caption">' . shortcode_unautop($content) . '</span>';
}
add_shortcode( 'caption', 'caption_shortcode' );


答:
Remove the JSON.stringify.its already a json  string from php .try with

```<code>var jsonData = JSON.parse(data);
</code>```

var data ='[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"Geeks Help","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]';
var jsonData = JSON.parse(data);

console.log(jsonData[0].checkNo)```

Title: json data not working on server

Body:
I retreived my json data using Jquery ajax. My data is:

[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"support","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]

On Jquery Success i hold the data in a variable

var jsonData = JSON.parse(JSON.stringify(data));

when i am trying to access checkNo. using jsonData[0].checkNo it yields undefined but when i check it using

console.log(jsonData)

It outputs data which is same as top.

Note: This problem yields only on server but it is working fine on my localhost.

Edit:

Here is my ajax call:

jQuery.ajax({
url: postUrl,
data:queryString,
type: "POST",
success:function(data){
    switch(action) {
      case "edit":
      jsonData = JSON.parse(data); console.log(jsonData);
      //var jsssss = JSON.parse(JSON.stringify(data)); console.log(jsssss);
      $("#custEmail").val(jsonData[0].custEmail);
      $("#custName").val(jsonData[0].custName);
      $("#custCheckNo").val(jsonData[0].checkNo);
      $("#edit_model").modal();
        break;
     //some more code
}
});

Body:
Remove the JSON.stringify.its already a json  string from php .try with

var jsonData = JSON.parse(data);

var data ='[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"Geeks Help","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]';
var jsonData = JSON.parse(data);

console.log(jsonData[0].checkNo)


问:
Can a PrintDialog be modified?
I am working at a print module and I use a PrintDialog to set the printer settings and then to print. The problem is that I have to do that before each print operation.

I want to select the printer settings (all the options provided by PrintDialog) and then to store them somewhere (not to print the document directly from the PrintDialog). Then, when I want to print something, it should print using the stored options.

So my question is the following: can I modify the PrintDialog by changing the name of the "Print" button into "Store Settings"? Or should I rewrite completely the functionality of that Dialog? (I hope not).

I want to change that button name in order to transform it from a print window into a print settings window.

Also, is there an existing implementation of a similar PrintDialog, other than the default one?

Thank you!

答:
@CosminIoniță

If I were you I would do this.

Save all the options of the printdialog in a serialized bin file. Read the file the next time and populate all options of the printdialog from there the next time onward.

Hope it helps

Title: Can a PrintDialog be modified?