问:
BDD Gherkin Selenium Java - Error Trouble shooting
```<code>    package cucumberselelniumgherkin;

    import java.util.concurrent.TimeUnit;

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

    import cucumber.api.java.After;
    import cucumber.api.java.Before;
    import cucumber.api.java.en.Given;
    import cucumber.api.java.en.Then;
    import cucumber.api.java.en.When;

    public class test {

        public WebDriver driver;

         @Before
            public void setup() {
                driver = new FirefoxDriver();
        }

        @Given("^I open google$")
        public void I_open_google() {
            //Set implicit wait of 10 seconds and launch google
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            driver.get("https://www.google.co.in");
        }

        @When("^I enter \"([^\"]*)\" in search textbox$")
        public void I_enter_in_search_textbox(String additionTerms) {
            //Write term in google textbox
            WebElement googleTextBox = driver.findElement(By.id("gbqfq"));
            googleTextBox.sendKeys(additionTerms);

            //Click on searchButton
            WebElement searchButton = driver.findElement(By.id("gbqfb"));
            searchButton.click();
        }

        @Then("^I should get result as \"([^\"]*)\"$")
        public void I_should_get_correct_result(String expectedResult) {
            //Get result from calculator
            WebElement calculatorTextBox = driver.findElement(By.id("cwos"));
            String result = calculatorTextBox.getText();

            //Verify that result of 2+2 is 4
            Assert.assertEquals(result, expectedResult);

            driver.close();
        }

         @After
          public void closeBrowser() {
          driver.quit();
         }

    }
</code>```

When I am trying to run it as maven test getting the below mentioned    error, please help this is my first attempt in getting into BDD    stuff, whats wrong in the code. Please suggest what can i do to fix this its been bothering my mind so much !

```<code>        [INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building bddSel 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-api/maven-metadata.xml
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-api/maven-metadata.xml (3 KB at 1.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-support/maven-metadata.xml
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-support/maven-metadata.xml (4 KB at 6.7 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.pom (3 KB at 5.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.jar (22 KB at 27.4 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ bddSel ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\workspace\bddSel\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ bddSel ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 2 source files to E:\workspace\bddSel\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] error reading C:\Users\Avinash\.m2\repository\org\apache\commons\commons-lang3\3.5\commons-lang3-3.5.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\cssparser\cssparser\0.9.22\cssparser-0.9.22.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\htmlunit\htmlunit\2.26\htmlunit-2.26.jar; invalid CEN header (bad signature)
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[6,17] package org.junit does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[12,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[13,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[14,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[15,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[16,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[23,11] cannot find symbol
  symbol:   class Before
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[28,10] cannot find symbol
  symbol:   class Given
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[35,10] cannot find symbol
  symbol:   class When
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[46,10] cannot find symbol
  symbol:   class Then
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[58,11] cannot find symbol
  symbol:   class After
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[53,17] cannot find symbol
  symbol:   variable Assert
  location: class cucumberselelniumgherkin.test
[INFO] 15 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.233 s
[INFO] Finished at: 2017-07-05T09:45:37+10:00
[INFO] Final Memory: 19M/152M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project bddSel: Compilation failure: Compilation failure:
[ERROR] error reading C:\Users\Avinash\.m2\repository\org\apache\commons\commons-lang3\3.5\commons-lang3-3.5.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\cssparser\cssparser\0.9.22\cssparser-0.9.22.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\htmlunit\htmlunit\2.26\htmlunit-2.26.jar; invalid CEN header (bad signature)
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[6,17] package org.junit does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[12,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[13,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[14,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[15,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[16,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[23,11] cannot find symbol
[ERROR] symbol:   class Before
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[28,10] cannot find symbol
[ERROR] symbol:   class Given
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[35,10] cannot find symbol
[ERROR] symbol:   class When
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[46,10] cannot find symbol
[ERROR] symbol:   class Then
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[58,11] cannot find symbol
[ERROR] symbol:   class After
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[53,17] cannot find symbol
[ERROR] symbol:   variable Assert
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

Below is the POM from the project - Thank you so much for your reply. I am so stuck :( help please. I have tried almost everything cant seem to figure it out. I am new to Selenium and bdd so trying to learn. So grateful for your response.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>CucumberJavaProject</groupId>
  <artifactId>bddSel</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.1.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
</code>```

答:
Use the same version for cucumber-junit and cucumber-java (1.2.5). The version 1.1.2 is from 30-Jan-2013.

Update:
Your test.java class is located at src/main/java. However your dependencies are set to scope test. This means they are only used for test compilation and execution. So when your maven project tries to compile the test.java class it did not have the needed classes in the classpath.

So move your test.java class into the src/test/java folder and try again.
You can also check my example project which shows the minimal setup to use most BDD frameworks to check where which file or class is located:
https://github.com/mszalbach/BDD/tree/master/cucumber

Body:
    package cucumberselelniumgherkin;

    import java.util.concurrent.TimeUnit;

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

    import cucumber.api.java.After;
    import cucumber.api.java.Before;
    import cucumber.api.java.en.Given;
    import cucumber.api.java.en.Then;
    import cucumber.api.java.en.When;

    public class test {

        public WebDriver driver;

         @Before
            public void setup() {
                driver = new FirefoxDriver();
        }

        @Given("^I open google$")
        public void I_open_google() {
            //Set implicit wait of 10 seconds and launch google
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            driver.get("https://www.google.co.in");
        }

        @When("^I enter \"([^\"]*)\" in search textbox$")
        public void I_enter_in_search_textbox(String additionTerms) {
            //Write term in google textbox
            WebElement googleTextBox = driver.findElement(By.id("gbqfq"));
            googleTextBox.sendKeys(additionTerms);

            //Click on searchButton
            WebElement searchButton = driver.findElement(By.id("gbqfb"));
            searchButton.click();
        }

        @Then("^I should get result as \"([^\"]*)\"$")
        public void I_should_get_correct_result(String expectedResult) {
            //Get result from calculator
            WebElement calculatorTextBox = driver.findElement(By.id("cwos"));
            String result = calculatorTextBox.getText();

            //Verify that result of 2+2 is 4
            Assert.assertEquals(result, expectedResult);

            driver.close();
        }

         @After
          public void closeBrowser() {
          driver.quit();
         }

    }

When I am trying to run it as maven test getting the below mentioned    error, please help this is my first attempt in getting into BDD    stuff, whats wrong in the code. Please suggest what can i do to fix this its been bothering my mind so much !

        [INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building bddSel 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-api/maven-metadata.xml
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-api/maven-metadata.xml (3 KB at 1.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-support/maven-metadata.xml
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/seleniumhq/selenium/selenium-support/maven-metadata.xml (4 KB at 6.7 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.pom (3 KB at 5.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/info/cukes/cucumber-junit/1.2.5/cucumber-junit-1.2.5.jar (22 KB at 27.4 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ bddSel ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\workspace\bddSel\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ bddSel ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 2 source files to E:\workspace\bddSel\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] error reading C:\Users\Avinash\.m2\repository\org\apache\commons\commons-lang3\3.5\commons-lang3-3.5.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\cssparser\cssparser\0.9.22\cssparser-0.9.22.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\htmlunit\htmlunit\2.26\htmlunit-2.26.jar; invalid CEN header (bad signature)
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[6,17] package org.junit does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[12,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[13,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[14,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[15,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[16,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[23,11] cannot find symbol
  symbol:   class Before
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[28,10] cannot find symbol
  symbol:   class Given
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[35,10] cannot find symbol
  symbol:   class When
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[46,10] cannot find symbol
  symbol:   class Then
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[58,11] cannot find symbol
  symbol:   class After
  location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[53,17] cannot find symbol
  symbol:   variable Assert
  location: class cucumberselelniumgherkin.test
[INFO] 15 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.233 s
[INFO] Finished at: 2017-07-05T09:45:37+10:00
[INFO] Final Memory: 19M/152M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project bddSel: Compilation failure: Compilation failure:
[ERROR] error reading C:\Users\Avinash\.m2\repository\org\apache\commons\commons-lang3\3.5\commons-lang3-3.5.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\cssparser\cssparser\0.9.22\cssparser-0.9.22.jar; invalid LOC header (bad signature)
[ERROR] error reading C:\Users\Avinash\.m2\repository\net\sourceforge\htmlunit\htmlunit\2.26\htmlunit-2.26.jar; invalid CEN header (bad signature)
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[6,17] package org.junit does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[12,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[13,25] package cucumber.api.java does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[14,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[15,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[16,28] package cucumber.api.java.en does not exist
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[23,11] cannot find symbol
[ERROR] symbol:   class Before
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[28,10] cannot find symbol
[ERROR] symbol:   class Given
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[35,10] cannot find symbol
[ERROR] symbol:   class When
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[46,10] cannot find symbol
[ERROR] symbol:   class Then
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[58,11] cannot find symbol
[ERROR] symbol:   class After
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] /E:/workspace/bddSel/src/main/java/cucumberselelniumgherkin/test.java:[53,17] cannot find symbol
[ERROR] symbol:   variable Assert
[ERROR] location: class cucumberselelniumgherkin.test
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Below is the POM from the project - Thank you so much for your reply. I am so stuck :( help please. I have tried almost everything cant seem to figure it out. I am new to Selenium and bdd so trying to learn. So grateful for your response.

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>CucumberJavaProject</groupId>
  <artifactId>bddSel</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.1.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


来源: stackexchange

问:
Capture Request and Capture Session in Android
I am working with the Camera2 API and I am following a tutorial. I have the TextureView set up and I have the SurfaceTextureListener on that TextureView. When the listener is invoked, I use the CameraManager to fetch the camera id I want to use and use the width and height provided to me to set the Preview Size. I also use the CameraManager to open the camera specifying the camera id and the Camera Device State Callback. On the onOpened override method, I invoke a method called startPreview():

```<code>private void startPreview() {
    SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
    surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface previewSurface = new Surface(surfaceTexture);

    try {
        mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mCaptureRequestBuilder.addTarget(previewSurface);

        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(CameraCaptureSession session) {
                        Log.d(TAG, "onConfigured: startPreview");
                        mPreviewCaptureSession = session;
                        try {
                            mPreviewCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    null, mBackgroundHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(CameraCaptureSession session) {
                        Log.d(TAG, "onConfigureFailed: startPreview");

                    }
                }, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
</code>```

What is a Capture Request and Capture Session? The Android documentation states createCaptureRequest:

Create a CaptureRequest.Builder for new capture requests

Ok, so what is a CaptureRequest.Builder? The documentation:

A builder for capture requests.

Both definitions reference the others without giving any meaning.

答:
A CaptureRequest defines the parameters for camera device (e.g. exposition, resolution). The Camera2 API provides templates to make it easier to prepare the best CaptureRequest, fine tuned for the specific camera and for the purpose.

To pass a CaptureRequest to the camera device, we use a CameraCaptureSession, which provides the context for single (e.g. taking a photo) or repeated (e.g. displaying live preview) requests.

Creating a session is an expensive operation and can take several hundred milliseconds, since it requires configuring the camera device's internal pipelines and allocating memory buffers for sending images to the desired targets.

ContentLicense: CC BY-SA 3.0

Body:
I am working with the Camera2 API and I am following a tutorial. I have the TextureView set up and I have the SurfaceTextureListener on that TextureView. When the listener is invoked, I use the CameraManager to fetch the camera id I want to use and use the width and height provided to me to set the Preview Size. I also use the CameraManager to open the camera specifying the camera id and the Camera Device State Callback. On the onOpened override method, I invoke a method called startPreview():

private void startPreview() {
    SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
    surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface previewSurface = new Surface(surfaceTexture);

    try {
        mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mCaptureRequestBuilder.addTarget(previewSurface);

        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(CameraCaptureSession session) {
                        Log.d(TAG, "onConfigured: startPreview");
                        mPreviewCaptureSession = session;
                        try {
                            mPreviewCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    null, mBackgroundHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(CameraCaptureSession session) {
                        Log.d(TAG, "onConfigureFailed: startPreview");

                    }
                }, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

What is a Capture Request and Capture Session? The Android documentation states createCaptureRequest:

Create a CaptureRequest.Builder for new capture requests

Ok, so what is a CaptureRequest.Builder? The documentation:

A builder for capture requests.

Both definitions reference the others without giving any meaning.


问:
I want to display my data on another page to click a button
I am developing a app (Online Vehicle Sales Management System), I inserted data in DB and display all record on single page, but I have a problem, I want select a single record by clicking on button and show it another page ...

Here is code:

```<code><html>
    <head>
        <title>New Purchase</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <script src="js/jquery.js"></script>
        <script src="js/bootstrap.min.js"></script>

        <?php
        session_start();

        if (isset($_POST['logout'])) {
            session_destroy();
            header("location: ovsms.php");
        }
        ?>
    </head>
    <body>
        <div class="jumbotron container-fluid" style="background-color:#4E4A49;
             padding-top:10px; padding-bottom:0px;" >

            <a href="home.php" ><img src="ovsms.jpg" style="width:100px;"></a>

            <a href="ovsms.php" name="logout" style="margin-left:925px;  padding-
               right:10px; color:#F7008C;"><span class="glyphicon glyphicon-log-out">
                </span> LogOut</a>

            <h1 style="text-align:center; padding-bottom:20px; margin-top:10px;
                margin-bottom:20px; font-family:Lucida Calligraphy; color:#0566c3;">Online
                Vehicle Sales Management System</h1>
        </div>
        <div  style="color:black; "class="btn-group btn-group-justified" >
            <a href="home.php" class="btn btn-primary" ><span class="glyphicon
                                                              glyphicon-home"></span> Home</a>
            <a href="about.php" class="btn btn-primary"><span class="glyphicon
                                                              glyphicon-education"></span> About Us</a>
            <a  href="contact.php" class="btn btn-primary"> <span class="glyphicon
                                                                  glyphicon-envelope"></span> Contact Us</a>
        </div>

        <div class="list-group" style="width:250px; margin-left:10px;">
            <h3 style="text-align:center; color:#0566c3;">Vehicles for...?</h3>
            <a style=" color:#0566c3;" href="newpurchase.php" class="list-group-item
               ">new purchase</a>
            <a style=" color:#0566c3;" href="rent.php" class="list-group-item">Rent</a>

        </div>

        <div class="container-fluid">
            <form action="" method="post" >
                <div class="form-group">
                    <input type="text"  name="srno" placeholder="Select by Sr.No  ....">

                </div>
                <div class="form-group">
                    <button type="submit" name="view" class="btn btn-default"
                            style="color:#F7008C; background-color:#0566c3;" ><span class="glyphicon
                                                                            glyphicon-ok"></span> Select</button>
                </div>
            </form>
        </div>

        <div>
            <h1 class="container" style="color:#0566c3;"><span class="glyphicon glyphicon-bed"></span> Vehicles for New Purchase</h1>
            <?php
            include('DbConnect.php');

            $sql = mysql_query("select * from vehicledata");
            while ($row = mysql_fetch_array($sql)) {
                ?>

                <table class="table table-striped" class="container-fluid" style="margin:10;">
                    <form action="newpurchase.php" method="post" enctype="multipart/form-data" >
                        <tbody>
                            <tr>
                        <div class="form-group">

                            <thead><img width='250' src="<?php echo $row['image']; ?>" /></thead>
                        </div>
                        </tr>
                        <tr><div class="form-group" >

                            <td>Sr.No <b><?php echo $row['id']; ?></b>
                            </td><td></td>
                        </div></tr>
                        <tr><div class="form-group" >
                            <td>Company</td>
                            <td><b><?php echo $row['company']; ?></b>
                            </td>
                        </div></tr>

                        <tr><div class="form-group">
                            <td>Vehicle Name</td>
                            <td><b><?php echo $row['vehiclename']; ?></b></td>
                        </div>
                        </tr>
                        <tr><div class="form-group">
                            <td>Model</td>
                            <td><b><?php echo $row['model']; ?></b></td>
                        </div></tr>
                        <tr>
                        <div class="form-group">
                            <td>Fuel Type</td>
                            <td><b><?php echo $row['fuel']; ?></b></td>
                        </div></tr>
                        <tr>
                        <div class="form-group">
                            <td>Transmission Type</td>
                            <td><b><?php echo $row['tranmission']; ?></b></td></div></tr>
                        <tr><div class="form-group">
                            <td>Engine</td>
                            <td><b><?php echo $row['engine']; ?></b></td></div></tr>
                        <tr><div class="form-group">
                            <td>Driving Type</td>
                            <td><b><?php echo $row['drive']; ?></b></td></div></tr>
                        <tr><div class="form-group">
                            <td>Mileage (Km/L)</td>
                            <td><b><?php echo $row['mileage']; ?></b> </td></div></tr>
                        <tr><div class="form-group">
                            <td>Price in Rs =/</td>
                            <td><b><?php echo $row['price']; ?></b></td></div></tr>
                        <tr><div class="form-group">

                            <td><br>
                                <button type="submit" name="add" class="btn btn-default" style="color:#F7008C; background-color:#0566c3;" ><span class="glyphicon glyphicon-ok"></span> Select</button>

                            </td><td></td>
                        </div></tr>
                        </tbody>
                    </form>
                </table>
                <?php
            }
            ?>
        </div>
        <?php
        if (isset($_POST['view'])) {

            $srno = $_POST['srno'];
            $select = mysql_query("select * from vehicledata where id='$srno' ");
            if ($ro = mysql_fetch_array($select)) {
                ?>
                <div class="container-fluid"><h1>Your dream car is here...</h1>

                    <h2>You have to pay <?php echo $ro['price']; ?></h2></div>
                <div>   <table class="table table-striped" class="container-fluid" style="margin:10;">
                        <form action="newpurchase.php" method="post" enctype="multipart/form-data" >
                            <tbody>
                                <tr>
                            <div class="form-group">

                                <thead><img width='250' src="<?php echo $ro['image']; ?>" /></thead>
                            </div>
                            </tr>
                            <tr><div class="form-group" >

                                <td></b>
                                </td><td></td>
                            </div></tr>
                            <tr><div class="form-group" >

                                <td>Sr.No <b><?php echo $ro['id']; ?></b>
                                </td><td></td>
                            </div></tr>
                            <tr><div class="form-group" >
                                <td>Company</td>
                                <td><b><?php echo $ro['company']; ?></b>
                                </td>
                            </div></tr>

                            <tr><div class="form-group">
                                <td>Vehicle Name</td>
                                <td><b><?php echo $ro['vehiclename']; ?></b></td>
                            </div>
                            </tr>
                            <tr><div class="form-group">
                                <td>Model</td>
                                <td><b><?php echo $ro['model']; ?></b></td>
                            </div></tr>
                            <tr>
                            <div class="form-group">
                                <td>Fuel Type</td>
                                <td><b><?php echo $ro['fuel']; ?></b></td>
                            </div></tr>
                            <tr>
                            <div class="form-group">
                                <td>Transmission Type</td>
                                <td><b><?php echo $ro['tranmission']; ?></b></td></div></tr>
                            <tr><div class="form-group">
                                <td>Engine</td>
                                <td><b><?php echo $ro['engine']; ?></b></td></div></tr>
                            <tr><div class="form-group">
                                <td>Driving Type</td>
                                <td><b><?php echo $ro['drive']; ?></b></td></div></tr>
                            <tr><div class="form-group">
                                <td>Mileage (Km/L)</td>
                                <td><b><?php echo $ro['mileage']; ?></b> </td></div></tr>
                            <tr><div class="form-group">
                                <td>Price in Rs =/</td>
                                <td><b><?php echo $ro['price']; ?></b></td></div></tr>

                            </tbody>
                        </form>
                    </table></div>

                <?php
            }
        }
        ?>
    </body>
</html>
</code>```

答:
Try This:</p>

```<code><td>
  <a href='other page url?view=<?php echo  $row['id']; ?>'>View</a>
</td>
</code>```

Body:
I am developing a app (Online Vehicle Sales Management System), I inserted data in DB and display all record on single page, but I have a problem, I want select a single record by clicking on button and show it another page ...

Here is code:

        <title>New Purchase</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">

        <?php
        session_start();

        if (isset($_POST['logout'])) {
            session_destroy();
            header("location: ovsms.php");
        }
        ?>

                 LogOut

Online
                Vehicle Sales Management System

             Home
             About Us
              Contact Us

Vehicles for...?

            new purchase
            Rent

            <form action="" method="post" >

                    <input type="text"  name="srno" placeholder="Select by Sr.No  ....">

                    <button type="submit" name="view" class="btn btn-default"
                            style="color:#F7008C; background-color:#0566c3;" > Select</button>

            </form>

 Vehicles for New Purchase

            <?php
            include('DbConnect.php');

            $sql = mysql_query("select * from vehicledata");
            while ($row = mysql_fetch_array($sql)) {
                ?>

                    <form action="newpurchase.php" method="post" enctype="multipart/form-data" >

<img width='250' src="<?php echo $row['image']; ?>" />

                            Sr.No <?php echo $row['id']; ?>

                            Company
                            <?php echo $row['company']; ?>

                            Vehicle Name
                            <?php echo $row['vehiclename']; ?>

                            Model
                            <?php echo $row['model']; ?>

                            Fuel Type
                            <?php echo $row['fuel']; ?>

                            Transmission Type
                            <?php echo $row['tranmission']; ?>

                            Engine
                            <?php echo $row['engine']; ?>

                            Driving Type
                            <?php echo $row['drive']; ?>

                            Mileage (Km/L)
                            <?php echo $row['mileage']; ?>

                            Price in Rs =/
                            <?php echo $row['price']; ?>

                                <button type="submit" name="add" class="btn btn-default" style="color:#F7008C; background-color:#0566c3;" > Select</button>

                    </form>

                <?php
            }
            ?>

        <?php
        if (isset($_POST['view'])) {

            $srno = $_POST['srno'];
            $select = mysql_query("select * from vehicledata where id='$srno' ");
            if ($ro = mysql_fetch_array($select)) {
                ?>

Your dream car is here...

You have to pay <?php echo $ro['price']; ?>

                        <form action="newpurchase.php" method="post" enctype="multipart/form-data" >

<img width='250' src="<?php echo $ro['image']; ?>" />

                                Sr.No <?php echo $ro['id']; ?>

                                Company
                                <?php echo $ro['company']; ?>

                                Vehicle Name
                                <?php echo $ro['vehiclename']; ?>

                                Model
                                <?php echo $ro['model']; ?>

                                Fuel Type
                                <?php echo $ro['fuel']; ?>

                                Transmission Type
                                <?php echo $ro['tranmission']; ?>

                                Engine
                                <?php echo $ro['engine']; ?>

                                Driving Type
                                <?php echo $ro['drive']; ?>

                                Mileage (Km/L)
                                <?php echo $ro['mileage']; ?>

                                Price in Rs =/
                                <?php echo $ro['price']; ?>

                        </form>

                <?php
            }
        }
        ?>

Body:
Try This:

<td>
  <a href='other page url?view=<?php echo  $row['id']; ?>'>View</a>
</td>


问:
Solving 3x3 Sudoku with SPARQL and OWL
I'm trying to solve simple 3x3 Sudoku game inside query.wikidata.org using SPARQL and OWL.

```<code>PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?a12 ?a13 ?a21 ?a23 ?a31 ?a32 WHERE{

:Zahl a owl:Class;
        owl:oneOf (:1 :2 :3) .

?a12 a :Zahl.
?a13 a :Zahl.
?a21 a :Zahl.
?a23 a :Zahl.
?a31 a :Zahl.
?a32 a :Zahl.

?a11 owl:sameAs :1.
?a22 owl:sameAs :2.
?a33 owl:sameAs :3.

?a12 owl:differentFrom ?a11 ?a13 ?a22 ?a32.
?a13 owl:differentFrom ?a11 ?a12 ?a23 ?a33.
?a21 owl:differentFrom ?a22 ?a23 ?a11 ?a31.
?a23 owl:differentFrom ?a22 ?a21 ?a13 ?a33.
?a31 owl:differentFrom ?a11 ?a21 ?a32 ?a33.
?a32 owl:differentFrom ?a12 ?a22 ?a31 ?a33.
}
</code>```

But i get this error:

```<code>Query is malformed: Encountered " <PNAME_LN> "owl:oneOf "" at line 5, column 19.
</code>```

Could somebody please point out my mistake?

答:
Hello my fellow friend from Karlsruhe,

your basic mistake is that you try to define objects in your query -
:Zahl a owl:Class;
        owl:oneOf (:1 :2 :3) .

The query is not the place for that. This can only be done in the rdf document - which should not be changed in the exercise.
Another mistake is a wrong understanding of objects and literals:
...owl:oneOf (:1 :2 :3) .
...
?a11 owl:sameAs :1.
?a22 owl:sameAs :2.
?a33 owl:sameAs :3.

owl:sameAs does not wirk on literals, so these are objects named 1, 2, and 3. You could work with objects named 1,2,3, but it is a lot easier to work with numbers (literals) and use filters (FILTER (?a11 = 1)).

Based on our source rdf, i think this is the way things should be done, as these are defined literals:
ex:field ex:allowed "1"^^xsd:int,
"2"^^xsd:int,
"3"^^xsd:int.
Cheers!

ContentLicense: CC BY-SA 4.0

Title: Solving 3x3 Sudoku with SPARQL and OWL

Body:
I'm trying to solve simple 3x3 Sudoku game inside query.wikidata.org using SPARQL and OWL.

PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?a12 ?a13 ?a21 ?a23 ?a31 ?a32 WHERE{

:Zahl a owl:Class;
        owl:oneOf (:1 :2 :3) .

?a12 a :Zahl.
?a13 a :Zahl.
?a21 a :Zahl.
?a23 a :Zahl.
?a31 a :Zahl.
?a32 a :Zahl.

?a11 owl:sameAs :1.
?a22 owl:sameAs :2.
?a33 owl:sameAs :3.

?a12 owl:differentFrom ?a11 ?a13 ?a22 ?a32.
?a13 owl:differentFrom ?a11 ?a12 ?a23 ?a33.
?a21 owl:differentFrom ?a22 ?a23 ?a11 ?a31.
?a23 owl:differentFrom ?a22 ?a21 ?a13 ?a33.
?a31 owl:differentFrom ?a11 ?a21 ?a32 ?a33.
?a32 owl:differentFrom ?a12 ?a22 ?a31 ?a33.
}

But i get this error:

Query is malformed: Encountered " <PNAME_LN> "owl:oneOf "" at line 5, column 19.

Could somebody please point out my mistake?


问:
Selenium web driver scraper
i posted question same question due to not able to post it properly i am again posting my question, i have created a scraper using selenium for the website https://maharerait.mahaonline.gov.in/searchlist/searchlist

whenever i run this it goes through every drop down and when it finds useful data to be scraped in csv it gives certain error:

```<code>Traceback (most recent call last):
 File "C:\Users\prince.bhatia\Desktop\maharera\Maha_Rera.py", line 66, in
<module>
    selectVillage.select_by_index(villageElement)
  File
"C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\support\select.py", line 103, in select_by_index
raise NoSuchElementException("Could not locate element with index %d" %
index)
selenium.common.exceptions.NoSuchElementException: Message: Could not locate
element with index 33
</code>```

Below are my codes:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import os
import time
import csv
import sys

driver = webdriver.Chrome("./chromedriver")

driver.get('https://maharerait.mahaonline.gov.in/searchlist/searchlist')

# try:
#     element = WebDriverWait(driver, 100).until(
#         EC.presence_of_element_located((By.ID, "Promoter"))
#     )
# finally:
#     print('0000000000000000000000')
#     driver.quit()

time.sleep(1)

driver.find_element_by_id('Promoter').click()

divisionLength = len(Select(driver.find_element_by_id('Division')).options)
print('*********{}'.format(divisionLength))

firstRow = 0
titleRow = []
contentRows = []

    for divisionElement in range(1,divisionLength):
    selectDivision = Select(driver.find_element_by_id('Division'))
    selectDivision.options
selectDivision.select_by_index(divisionElement)
time.sleep(1)
districtLength = len(Select(driver.find_element_by_id('District')).options)
while districtLength == 1:
    pass
print(districtLength)
for districtElement in range(1,districtLength):
    selectDistrict = Select(driver.find_element_by_id('District'))
    selectDistrict.options

    selectDistrict.select_by_index(districtElement)

    time.sleep(1)

    talukaLength = len(Select(driver.find_element_by_id('Taluka')).options)
    print('/-----taluka numbers: {}-------/'.format(talukaLength))
    for talukaElement in range(1, talukaLength):
        selectTaluka = Select(driver.find_element_by_id('Taluka'))
        selectTaluka.options
        selectTaluka.select_by_index(talukaElement)
        time.sleep(1)

        villageLength = len(Select(driver.find_element_by_id('Village')).options)
        print('/-----village numbers: {}-------/'.format(talukaLength))
        for villageElement in range(1, villageLength):
            selectVillage = Select(driver.find_element_by_id('Village'))
            selectVillage.options
            selectVillage.select_by_index(villageElement)
            time.sleep(2)
            projectLength = len(Select(driver.find_element_by_id('Project')).options)

            print('/------------------------------/')
            print('/-----project number: {}-------/'.format(projectLength))
            print('/------------------------------/')
            if projectLength == 1:
                continue

            for projectElement in range(1,projectLength):
                selectProject = Select(driver.find_element_by_id('Project'))
                selectProject.options

                while len(selectProject.options) == 1:
                    pass
                # c = len(select.options)
                # print('---------------{}'.format(c))

                # titleRow = []
                # contentRows = []
                # firstRow = 0

                # for i in range(1,c):
                #     select = Select(driver.find_element_by_id('Project'))
                #     while len(select.options) == 1:
                #         pass
                time.sleep(1)
                selectProject.select_by_index(projectElement)

                driver.find_element_by_id('btnSearch').click()
                tableRows = driver.find_element_by_class_name('table').find_elements_by_tag_name('tr')

                if firstRow == 0:
                    headRow = tableRows[0].find_elements_by_tag_name('th')
                    for headRowData in range(0,len(headRow)):
                        text = headRow[headRowData].find_element_by_tag_name('span').text
                        titleRow.append(text)
                    firstRow = firstRow + 1

                for dataRowsNumbers in range(1,len(tableRows)):
                    dataRow = tableRows[dataRowsNumbers].find_elements_by_tag_name('td')
                    tempList = []
                    for dataRowContents in range(0,len(dataRow)):
                        try:
                            a_link = dataRow[dataRowContents].find_element_by_tag_name('a').get_attribute('href')
                            tempList.append(str(a_link))
                        except:
                            tempList.append(str(dataRow[dataRowContents].text))
                        # if dataRow[dataRowContents].text == 'View':
                        #     a_link = dataRow[dataRowContents].find_element_by_tag_name('a').get_attribute('href')
                        #     tempList.append(str(a_link))
                        # else:
                        #     tempList.append(str(dataRow[dataRowContents].text))
                        print(dataRow[dataRowContents].text)
                    print(tempList)
                    contentRows.append(tempList)
# print('Automated check is over')
# print('Stored data in programs is as below:')
# print(contentRows)
if sys.version_info[0] <= 2:
    with open("./data.csv",'w') as csvfile:
    csvfile = csv.writer(csvfile, delimiter=',')
    csvfile.writerow(titleRow)
    csvfile.writerow("")
    for i in range(0,len(contentRows)):
        csvfile.writerow(contentRows[i])
else:
    with open("./data.csv",'w',newline='') as csvfile:
        csvfile = csv.writer(csvfile, delimiter=',')
        csvfile.writerow(titleRow)
        csvfile.writerow("")
        for i in range(0,len(contentRows)):
        csvfile.writerow(contentRows[i])
driver.close()
</code>```

If someone can please tell, where i doing wrong? i am using python 3.6
i have closed the previous question
i had to give 4 spaces here , but in originals are good written except the error.

答:
Your error pops up on line:

```<code>selectVillage.select_by_index(villageElement)
</code>```

According to the documentation:

This is done by examining the "index" attribute of an element, and not merely by counting.

Therefore, you need to change the code to iterate through the elements themselves rather that range(1,projectLength).

Update:

According to this, the solution might be as simple as starting your range from 0 instead of 1:

```<code>for villageElement in range(0, villageLength - 1):
</code>```

Note: If this works, then you'll need to change the other loops accordingly.

Title: Selenium web driver scraper

Body:
i posted question same question due to not able to post it properly i am again posting my question, i have created a scraper using selenium for the website https://maharerait.mahaonline.gov.in/searchlist/searchlist

whenever i run this it goes through every drop down and when it finds useful data to be scraped in csv it gives certain error:

Traceback (most recent call last):
 File "C:\Users\prince.bhatia\Desktop\maharera\Maha_Rera.py", line 66, in
<module>
    selectVillage.select_by_index(villageElement)
  File
"C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\support\select.py", line 103, in select_by_index
raise NoSuchElementException("Could not locate element with index %d" %
index)
selenium.common.exceptions.NoSuchElementException: Message: Could not locate
element with index 33

Below are my codes:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import os
import time
import csv
import sys

driver = webdriver.Chrome("./chromedriver")

driver.get('https://maharerait.mahaonline.gov.in/searchlist/searchlist')

# try:
#     element = WebDriverWait(driver, 100).until(
#         EC.presence_of_element_located((By.ID, "Promoter"))
#     )
# finally:
#     print('0000000000000000000000')
#     driver.quit()

time.sleep(1)

driver.find_element_by_id('Promoter').click()

divisionLength = len(Select(driver.find_element_by_id('Division')).options)
print('*********{}'.format(divisionLength))

firstRow = 0
titleRow = []
contentRows = []

    for divisionElement in range(1,divisionLength):
    selectDivision = Select(driver.find_element_by_id('Division'))
    selectDivision.options
selectDivision.select_by_index(divisionElement)
time.sleep(1)
districtLength = len(Select(driver.find_element_by_id('District')).options)
while districtLength == 1:
    pass
print(districtLength)
for districtElement in range(1,districtLength):
    selectDistrict = Select(driver.find_element_by_id('District'))
    selectDistrict.options

    selectDistrict.select_by_index(districtElement)

    time.sleep(1)

    talukaLength = len(Select(driver.find_element_by_id('Taluka')).options)
    print('/-----taluka numbers: {}-------/'.format(talukaLength))
    for talukaElement in range(1, talukaLength):
        selectTaluka = Select(driver.find_element_by_id('Taluka'))
        selectTaluka.options
        selectTaluka.select_by_index(talukaElement)
        time.sleep(1)

        villageLength = len(Select(driver.find_element_by_id('Village')).options)
        print('/-----village numbers: {}-------/'.format(talukaLength))
        for villageElement in range(1, villageLength):
            selectVillage = Select(driver.find_element_by_id('Village'))
            selectVillage.options
            selectVillage.select_by_index(villageElement)
            time.sleep(2)
            projectLength = len(Select(driver.find_element_by_id('Project')).options)

            print('/------------------------------/')
            print('/-----project number: {}-------/'.format(projectLength))
            print('/------------------------------/')
            if projectLength == 1:
                continue

            for projectElement in range(1,projectLength):
                selectProject = Select(driver.find_element_by_id('Project'))
                selectProject.options

                while len(selectProject.options) == 1:
                    pass
                # c = len(select.options)
                # print('---------------{}'.format(c))

                # titleRow = []
                # contentRows = []
                # firstRow = 0

                # for i in range(1,c):
                #     select = Select(driver.find_element_by_id('Project'))
                #     while len(select.options) == 1:
                #         pass
                time.sleep(1)
                selectProject.select_by_index(projectElement)

                driver.find_element_by_id('btnSearch').click()
                tableRows = driver.find_element_by_class_name('table').find_elements_by_tag_name('tr')

                if firstRow == 0:
                    headRow = tableRows[0].find_elements_by_tag_name('th')
                    for headRowData in range(0,len(headRow)):
                        text = headRow[headRowData].find_element_by_tag_name('span').text
                        titleRow.append(text)
                    firstRow = firstRow + 1

                for dataRowsNumbers in range(1,len(tableRows)):
                    dataRow = tableRows[dataRowsNumbers].find_elements_by_tag_name('td')
                    tempList = []
                    for dataRowContents in range(0,len(dataRow)):
                        try:
                            a_link = dataRow[dataRowContents].find_element_by_tag_name('a').get_attribute('href')
                            tempList.append(str(a_link))
                        except:
                            tempList.append(str(dataRow[dataRowContents].text))
                        # if dataRow[dataRowContents].text == 'View':
                        #     a_link = dataRow[dataRowContents].find_element_by_tag_name('a').get_attribute('href')
                        #     tempList.append(str(a_link))
                        # else:
                        #     tempList.append(str(dataRow[dataRowContents].text))
                        print(dataRow[dataRowContents].text)
                    print(tempList)
                    contentRows.append(tempList)
# print('Automated check is over')
# print('Stored data in programs is as below:')
# print(contentRows)
if sys.version_info[0] <= 2:
    with open("./data.csv",'w') as csvfile:
    csvfile = csv.writer(csvfile, delimiter=',')
    csvfile.writerow(titleRow)
    csvfile.writerow("")
    for i in range(0,len(contentRows)):
        csvfile.writerow(contentRows[i])
else:
    with open("./data.csv",'w',newline='') as csvfile:
        csvfile = csv.writer(csvfile, delimiter=',')
        csvfile.writerow(titleRow)
        csvfile.writerow("")
        for i in range(0,len(contentRows)):
        csvfile.writerow(contentRows[i])
driver.close()

If someone can please tell, where i doing wrong? i am using python 3.6
i have closed the previous question
i had to give 4 spaces here , but in originals are good written except the error.

Body:
Your error pops up on line:

selectVillage.select_by_index(villageElement)

According to the documentation:

This is done by examining the "index" attribute of an element, and not merely by counting.

Therefore, you need to change the code to iterate through the elements themselves rather that range(1,projectLength).

Update:

According to this, the solution might be as simple as starting your range from 0 instead of 1:

for villageElement in range(0, villageLength - 1):

Note: If this works, then you'll need to change the other loops accordingly.


问:
Standard process for creating complex xpath in protractor
I am looking for standard ways to arrive at complex xpath expressions in protractor.

For e.g. I have a complex xpath as follows:

```<code>(//*[contains(@class,'day')][normalize-space(text())='2'])[1]
</code>```

Here I have to get first access to elements matching xpath

```<code>//*[contains(@class,'day')][normalize-space(text())='2']
</code>```

and then pick the first from the matching ones. Any pointers?

答:
Firstly, you shouldn't use XPath except as a last resort. I second the recommendation by @Kacper to read the style guide he posted.

However, if you're dead set on using XPath, (sometimes it is unavoidable), you can pick the first element that matches like so:

```<code>element.all(by.xpath("//*[contains(@class,'day')][normalize-space(text())='2']")).first();
</code>```

Body:
I am looking for standard ways to arrive at complex xpath expressions in protractor.

For e.g. I have a complex xpath as follows:

(//*[contains(@class,'day')][normalize-space(text())='2'])[1]

Here I have to get first access to elements matching xpath

//*[contains(@class,'day')][normalize-space(text())='2']

and then pick the first from the matching ones. Any pointers?

Body:
Firstly, you shouldn't use XPath except as a last resort. I second the recommendation by @Kacper to read the style guide he posted.

However, if you're dead set on using XPath, (sometimes it is unavoidable), you can pick the first element that matches like so:

element.all(by.xpath("//*[contains(@class,'day')][normalize-space(text())='2']")).first();


问:
ReactNative - Redux not immediately update
I know this.setState is asynchronous.

But now, I use Redux and in reducer there is no this.setState. I can use callbacks for setState but in redux I don't know where to put the callbacks and how. In action? (no) in Reducer? in Component? in Container? in Store? (no).

I'm new to redux and reactnative, so I hope you understand my question.

My data is updating but with one step late.

exemple :

tap: 'a',   state = ''

tap: 'ab, state = 'a'

tap: 'abc', state = 'ab'

In component, I call function like this :

```<code>let { myFunction1, myFunction2 } = this.props;
myFunction1();
</code>```

So setting state works but I need to handle this late.

答:
You should use setState for storing value onChange, once user done with the input you can call your reducer function to save value to your store. It will reduce the number of call to reducer function.

Example:

```<code><TextInput
    underlineColorAndroid='transparent'
    onSubmitEditing={() => this.onNextPress()}
    onChangeText={(text) => this.onChangeText(text)}
/>
</code>```

Use have onChangeText(text) to handle your setState and once submitted (or your event triggered), use another function to handle reducer call. In my example it is onNextPress()

Body:
I know this.setState is asynchronous.

But now, I use Redux and in reducer there is no this.setState. I can use callbacks for setState but in redux I don't know where to put the callbacks and how. In action? (no) in Reducer? in Component? in Container? in Store? (no).

I'm new to redux and reactnative, so I hope you understand my question.

My data is updating but with one step late.

exemple :

tap: 'a',   state = ''

tap: 'ab, state = 'a'

tap: 'abc', state = 'ab'

In component, I call function like this :

let { myFunction1, myFunction2 } = this.props;
myFunction1();

So setting state works but I need to handle this late.

Body:
You should use setState for storing value onChange, once user done with the input you can call your reducer function to save value to your store. It will reduce the number of call to reducer function.

Example:

<TextInput
    underlineColorAndroid='transparent'
    onSubmitEditing={() => this.onNextPress()}
    onChangeText={(text) => this.onChangeText(text)}
/>

Use have onChangeText(text) to handle your setState and once submitted (or your event triggered), use another function to handle reducer call. In my example it is onNextPress()


问:
Truncate string in Laravel blade templates
Is there a truncate modifier for the blade templates in Laravel, pretty much like Smarty?

I know I could just write out the actual php in the template but i'm looking for something a little nicer to write (let's not get into the whole PHP is a templating engine debate).

So for example i'm looking for something like:

```<code>{{ $myVariable|truncate:"10":"..." }}
</code>```

I know I could use something like Twig via composer but I'm hoping for built in functionality in Laravel itself.

If not is it possible to create your own reusable modifiers like Smarty provides. I like the fact that Blade doesn’t overkill with all the syntax but I think truncate is a real handy function to have.

I'm using Laravel 4.

答:
You can Set the namespace like:</p>

```<code>{!! \Illuminate\Support\Str::words($item->description, 10,'....')  !!}
</code>```

Body:
Is there a truncate modifier for the blade templates in Laravel, pretty much like Smarty?

I know I could just write out the actual php in the template but i'm looking for something a little nicer to write (let's not get into the whole PHP is a templating engine debate).

So for example i'm looking for something like:

{{ $myVariable|truncate:"10":"..." }}

I know I could use something like Twig via composer but I'm hoping for built in functionality in Laravel itself.

If not is it possible to create your own reusable modifiers like Smarty provides. I like the fact that Blade doesn’t overkill with all the syntax but I think truncate is a real handy function to have.

I'm using Laravel 4.

Body:
You can Set the namespace like:

{!! \Illuminate\Support\Str::words($item->description, 10,'....')  !!}


问:
Laravel and vue.js template: javascript handled as literal instead of being executed
I've a home.blade.php that ends with

```<code>@section('page_specific_scripts')
    <script type="text/javascript">
        const slider_base_img_url = '{{ $slider_base_img_url }}'
    </script>
    <script src="{{ mix('js/home.js') }}"></script>
@endsection
</code>```

This is the relevant part of home.js

```<code>Vue.component('slide', Vue.Slide);
Vue.component('carousel', Vue.Carousel);

const slider_app = new Vue({
    el: '#home-page-slider',
    template: `
        <carousel :perPage="1" :autoplay="true"  :autoplayLoop="true" >

            <slide v-for="n in 3">
                <IMG
                    class='autosize'
                    src="{{ slider_base_img_url + '0' + n + '.png' }}"
            />
            </slide>
        </carousel>
    `
});
</code>```

And this is my mix config file

```<code>mix
    .js('resources/assets/js/home.js', 'public/js')
    .js('resources/assets/js/app.js', 'public/js')
    .extract(['vue', 'lodash', 'vue-resource', 'vue-carousel'])
    .sass('resources/assets/sass/app.scss', 'public/css')
    .sass('node_modules/font-awesome/scss/font-awesome.scss', 'public/css/vendor')
    .version();
</code>```

The problem is that vue templates is rendered but the src of the image remain the textual javascript. This is the generated HTML

```<code><div class="VueCarousel-inner" style="transform: translateX(-3806px); transition: transform 0.5s ease; flex-basis: 1903px; visibility: visible;">

<div class="VueCarousel-slide">
<img src="{{ slider_base_img_url + '0' + n + '.png' }}" class="autosize"></div>

... [cut] ...
</code>```

What am I doing wrong?

For reference, this is the home.js file after mix as loaded from the browser

```<code>Vue.component('slide', Vue.Slide);
Vue.component('carousel', Vue.Carousel);

var slider_app = new Vue({
    el: '#home-page-slider',
    //language=HTML
    template: "\n        <carousel :perPage=\"1\" :autoplay=\"true\"  :autoplayLoop=\"true\" >\n           \n            <slide v-for=\"n in 3\">\n                <IMG\n                    class='autosize'\n                    src=\"{{ slider_base_img_url + '0' + n + '.png' }}\"\n                />\n            </slide>\n        </carousel>\n    "
});
</code>```

The template itself is working, because the for loop creates 3 slides.

But why the inner javascript is not being executed?

Is there a specific Vue-way that actually I don't know yet?

答:
done this 2 modifications, and now works:

this in home.blade.php

```<code>@section('page_specific_scripts')
    <script type="text/javascript">
        window.slider_base_img_url = '{{ $slider_base_img_url }}'
    </script>
    <script src="{{ mix('js/home.js') }}"></script>
@endsection
</code>```

and this is home.js

```<code>const slider_app = new Vue({
    el: '#home-page-slider',
    //language=HTML
    computed: {
        slider_base_img_url: function () { return window.slider_base_img_url; }
    },
    template: `
        <carousel :perPage="1" :autoplay="true"  :autoplayLoop="true" >

            <slide v-for="n in 3" :key="n">
                <IMG
                    class='autosize'
                    :src="slider_base_img_url + '0' + n + '.png'"
                />
            </slide>
        </carousel>
    `
});
</code>```

Body:
I've a home.blade.php that ends with

@section('page_specific_scripts')

@endsection

This is the relevant part of home.js

Vue.component('slide', Vue.Slide);
Vue.component('carousel', Vue.Carousel);

const slider_app = new Vue({
    el: '#home-page-slider',
    template: `
        <carousel :perPage="1" :autoplay="true"  :autoplayLoop="true" >

            <slide v-for="n in 3">

            </slide>
        </carousel>
    `
});

And this is my mix config file

mix
    .js('resources/assets/js/home.js', 'public/js')
    .js('resources/assets/js/app.js', 'public/js')
    .extract(['vue', 'lodash', 'vue-resource', 'vue-carousel'])
    .sass('resources/assets/sass/app.scss', 'public/css')
    .sass('node_modules/font-awesome/scss/font-awesome.scss', 'public/css/vendor')
    .version();

The problem is that vue templates is rendered but the src of the image remain the textual javascript. This is the generated HTML

... [cut] ...

What am I doing wrong?

For reference, this is the home.js file after mix as loaded from the browser

Vue.component('slide', Vue.Slide);
Vue.component('carousel', Vue.Carousel);

var slider_app = new Vue({
    el: '#home-page-slider',
    //language=HTML
    template: "\n        <carousel :perPage=\"1\" :autoplay=\"true\"  :autoplayLoop=\"true\" >\n           \n            <slide v-for=\"n in 3\">\n                \n            </slide>\n        </carousel>\n    "
});

The template itself is working, because the for loop creates 3 slides.

But why the inner javascript is not being executed?

Is there a specific Vue-way that actually I don't know yet?

Body:
done this 2 modifications, and now works:

this in home.blade.php

@section('page_specific_scripts')
    <script type="text/javascript">
        window.slider_base_img_url = '{{ $slider_base_img_url }}'
    </script>
    <script src="{{ mix('js/home.js') }}"></script>
@endsection

and this is home.js

const slider_app = new Vue({
    el: '#home-page-slider',
    //language=HTML
    computed: {
        slider_base_img_url: function () { return window.slider_base_img_url; }
    },
    template: `
        <carousel :perPage="1" :autoplay="true"  :autoplayLoop="true" >

            <slide v-for="n in 3" :key="n">
                <IMG
                    class='autosize'
                    :src="slider_base_img_url + '0' + n + '.png'"
                />
            </slide>
        </carousel>
    `
});


问:
Router.js won't route
I want to route an URL formatted with slashes in nodeJS. I want this:

http://localhost/a

But, when I goto the page, I got a 404 not found, why ?

Here is my code:

```<code>router.get('/a'), function(req, res, next) {
    res.send('Whatever you wish to send \n');
}
</code>```

答:
Without knowing the framework you are using, I think your syntax is wrong. </p>

<p>IMHO it should be: </p>

```<code>router.get('/a', function(req, res, next) {
  res.send('Whatever you wish to send \n');
})
</code>```

Title: Router.js won't route

Body:
I want to route an URL formatted with slashes in nodeJS. I want this:

http://localhost/a

But, when I goto the page, I got a 404 not found, why ?

Here is my code:

router.get('/a'), function(req, res, next) {
    res.send('Whatever you wish to send \n');
}

Body:
Without knowing the framework you are using, I think your syntax is wrong.

IMHO it should be:

router.get('/a', function(req, res, next) {
  res.send('Whatever you wish to send \n');
})


问:
Tls handshake fails even though ciphersuites in common
I am experiencing some trouble while making a secure connection to www.howsmyssl.com/a/check. I am using wolfSSL to connect, however, the handshake always fails (FATAL ERROR alert 40). I tried to sniff the network to look into the packets to see what exactly is sent and which ciphersuites are supported, and I see that according to a test from ssllabs, howsmyssl.com and my client have ciphersuites in common. So I don't really know where the mistake is taken place.
This is trace of the client:

And this is a link to the ssllabs analysation of www.howsmyssl.com. Here you can see that they have ciphersuites in common (for example 0xc02f), so I think that the connection should succeed, or am I missing something?

EDIT:
Here are the debug logs of wolfssl

```<code>[0;32mI (6565) openssl_example: OpenSSL demo thread start OK[0m
[0;33mW (6565) openssl_example: Size of long = 4, Size of longlong = 8
[0m
[0;32mI (6565) openssl_example: get target IP address[0m
[0;32mI (6595) openssl_example: OK[0m
[0;32mI (6595) openssl_example: 104.196.190.195[0m
wolfSSL Entering wolfSSL_Init
wolfSSL Entering wolfCrypt_Init
[0;32mI (6595) openssl_example: create SSL context ......[0m
wolfSSL Entering WOLFSSL_CTX_new_ex
wolfSSL Entering wolfSSL_CertManagerNew
wolfSSL Leaving WOLFSSL_CTX_new, return 0
[0;32mI (6615) openssl_example: OK[0m
wolfSSL Entering wolfSSL_CTX_set_verify
wolfSSL Entering wolfSSL_CTX_load_verify_buffer
Getting into SSL_FILETYPE_PEM if
Processing CA PEM file
wolfSSL Entering PemToDer
Adding a CA
wolfSSL Entering GetExplicitVersion
wolfSSL Entering GetSerialNumber
Got Cert Header
wolfSSL Entering GetAlgoId
wolfSSL Entering GetObjectId()
Got Algo ID
Getting Cert Name
Getting Cert Name
Got Subject Name
wolfSSL Entering GetAlgoId
wolfSSL Entering GetObjectId()
Got Key
Parsed Past Key
wolfSSL Entering DecodeCertExtensions
wolfSSL Entering GetObjectId()
wolfSSL Entering DecodeSubjKeyId
wolfSSL Entering GetObjectId()
wolfSSL Entering DecodeAuthKeyId
wolfSSL Entering GetObjectId()
wolfSSL Entering DecodeBasicCaConstraint
wolfSSL Entering GetAlgoId
wolfSSL Entering GetObjectId()
    Parsed new CA
    Freeing Parsed CA
    Freeing der CA
        OK Freeing der CA
wolfSSL Leaving AddCA, return 0
1
   Processed a CA
wolfSSL Entering PemToDer
Couldn't find PEM header
-372
CA Parse failed, no progress in file.
Do not continue search for other certs in file
Processed at least one valid CA. Other stuff OK
[0;32mI (6715) openssl_example: create socket ......[0m
[0;32mI (6725) openssl_example: OK[0m
[0;32mI (6725) openssl_example: bind socket ......[0m
[0;32mI (6735) openssl_example: OK[0m
[0;32mI (6735) openssl_example: socket connect to remote www.howsmyssl.com ......[0m
[0;32mI (6865) openssl_example: OK[0m
[0;32mI (6865) openssl_example: create SSL ......[0m
wolfSSL Entering SSL_new
wolfSSL Leaving SSL_new, return 0
[0;32mI (6865) openssl_example: OK[0m
wolfSSL Entering SSL_set_fd
wolfSSL Entering SSL_set_read_fd
wolfSSL Leaving SSL_set_read_fd, return 1
wolfSSL Entering SSL_set_write_fd
wolfSSL Leaving SSL_set_write_fd, return 1
[0;32mI (6885) openssl_example: SSL connected to www.howsmyssl.com port 443 ......[0m
wolfSSL Entering SSL_connect()
growing output buffer

Shrinking output buffer

connect state: CLIENT_HELLO_SENT
received record layer msg
got ALERT!
Got alert
wolfSSL error occurred, error = 40
wolfSSL error occurred, error = -313
[0;32mI (7065) openssl_example: OK[0m
wolfSSL Entering wolfSSL_get_cipher
wolfSSL Entering SSL_get_current_cipher
wolfSSL Entering SSL_CIPHER_get_name
wolfSSL Entering wolfSSL_get_cipher_name_from_suite
READ USED CIPHERSUITE: NONE
[0;32mI (7085) openssl_example: send https request to www.howsmyssl.com port 443 ......[0m
wolfSSL Entering SSL_write()
handshake not complete, trying to finish
wolfSSL Entering wolfSSL_negotiate
wolfSSL Entering SSL_connect()
ProcessReply retry in error state, not allowed
wolfSSL error occurred, error = -313
wolfSSL Leaving wolfSSL_negotiate, return -1
wolfSSL Leaving SSL_write(), return -1
[0;32mI (7115) openssl_example: failed[0m
wolfSSL Entering SSL_shutdown()
wolfSSL Leaving SSL_shutdown(), return -1
wolfSSL Entering SSL_free
CTX ref count not 0 yet, no free
wolfSSL Leaving SSL_free, return 0
wolfSSL Entering SSL_CTX_free
CTX ref count down to 0, doing full free
wolfSSL Entering wolfSSL_CertManagerFree
wolfSSL Leaving SSL_CTX_free, return 0
I (14055) wifi: pm start, type:0
</code>```

UPDATE
I tried connecting to www.google.com and this succeeds. No changes were made to my code, so I think this will be a server issue. However, when I connect to www.howsmyssl.com with mbedtls, the request also succeeds and after comparing the packets by sniffing the network, I cannot see any major differences.

答:
Merely sharing the Client Hello from the client won't help here. You would need to gather some SSL related logs. I am not an wolfssl expert, but looks like it exposes additional logs when you compile it using --enable-debug. I refered this: WolfSL - SSL Alert fatal error

Cipher Suites is the not the only thing that can go wrong. If the server expected a certain TLS extension in the Client Hello in a certain format and if it was not accepted even in this case, the Server can terminate the handshake.

See this thread for reference: SSL handshake_failure after clientHello

Without the debug logs, it will be like shooting in the dark.

UPDATE:

So these are the errors in the logs:

```<code>wolfSSL error occurred, error = 40
wolfSSL error occurred, error = -313
</code>```

313 means the server either didn't like one of the following sent by the client:

Cipher suites

TLS Extensions

Since you have already specified supported curves, you might try enabling static key cipher suites. These seem to be disabled by default in WolfSSL. WolfSSL - Supported Cipher Suites

Body:
I am experiencing some trouble while making a secure connection to www.howsmyssl.com/a/check. I am using wolfSSL to connect, however, the handshake always fails (FATAL ERROR alert 40). I tried to sniff the network to look into the packets to see what exactly is sent and which ciphersuites are supported, and I see that according to a test from ssllabs, howsmyssl.com and my client have ciphersuites in common. So I don't really know where the mistake is taken place.
This is trace of the client:

And this is a link to the ssllabs analysation of www.howsmyssl.com. Here you can see that they have ciphersuites in common (for example 0xc02f), so I think that the connection should succeed, or am I missing something?

EDIT:
Here are the debug logs of wolfssl

[0;32mI (6565) openssl_example: OpenSSL demo thread start OK[0m
[0;33mW (6565) openssl_example: Size of long = 4, Size of longlong = 8
[0m
[0;32mI (6565) openssl_example: get target IP address[0m
[0;32mI (6595) openssl_example: OK[0m
[0;32mI (6595) openssl_example: 104.196.190.195[0m
wolfSSL Entering wolfSSL_Init
wolfSSL Entering wolfCrypt_Init
[0;32mI (6595) openssl_example: create SSL context ......[0m
wolfSSL Entering WOLFSSL_CTX_new_ex
wolfSSL Entering wolfSSL_CertManagerNew
wolfSSL Leaving WOLFSSL_CTX_new, return 0
[0;32mI (6615) openssl_example: OK[0m
wolfSSL Entering wolfSSL_CTX_set_verify
wolfSSL Entering wolfSSL_CTX_load_verify_buffer
Getting into SSL_FILETYPE_PEM if
Processing CA PEM file
wolfSSL Entering PemToDer
Adding a CA
wolfSSL Entering GetExplicitVersion
wolfSSL Entering GetSerialNumber
Got Cert Header
wolfSSL Entering GetAlgoId
wolfSSL Entering GetObjectId()
Got Algo ID
Getting Cert Name
Getting Cert Name
Got Subject Name
wolfSSL Entering GetAlgoId
wolfSSL Entering GetObjectId()
Got Key
Parsed Past Key
wolfSSL Entering DecodeCertExtensions
wolfSSL Entering GetObjectId()
wolfSSL Entering DecodeSubjKeyId
wolfSSL Entering GetObjectId()
wolfSSL Entering DecodeAuthKeyId
wolfSSL Entering GetObjectId()
wolfSSL Entering DecodeBasicCaConstraint
wolfSSL Entering GetAlgoId
wolfSSL Entering GetObjectId()
    Parsed new CA
    Freeing Parsed CA
    Freeing der CA
        OK Freeing der CA
wolfSSL Leaving AddCA, return 0
1
   Processed a CA
wolfSSL Entering PemToDer
Couldn't find PEM header
-372
CA Parse failed, no progress in file.
Do not continue search for other certs in file
Processed at least one valid CA. Other stuff OK
[0;32mI (6715) openssl_example: create socket ......[0m
[0;32mI (6725) openssl_example: OK[0m
[0;32mI (6725) openssl_example: bind socket ......[0m
[0;32mI (6735) openssl_example: OK[0m
[0;32mI (6735) openssl_example: socket connect to remote www.howsmyssl.com ......[0m
[0;32mI (6865) openssl_example: OK[0m
[0;32mI (6865) openssl_example: create SSL ......[0m
wolfSSL Entering SSL_new
wolfSSL Leaving SSL_new, return 0
[0;32mI (6865) openssl_example: OK[0m
wolfSSL Entering SSL_set_fd
wolfSSL Entering SSL_set_read_fd
wolfSSL Leaving SSL_set_read_fd, return 1
wolfSSL Entering SSL_set_write_fd
wolfSSL Leaving SSL_set_write_fd, return 1
[0;32mI (6885) openssl_example: SSL connected to www.howsmyssl.com port 443 ......[0m
wolfSSL Entering SSL_connect()
growing output buffer

Shrinking output buffer

connect state: CLIENT_HELLO_SENT
received record layer msg
got ALERT!
Got alert
wolfSSL error occurred, error = 40
wolfSSL error occurred, error = -313
[0;32mI (7065) openssl_example: OK[0m
wolfSSL Entering wolfSSL_get_cipher
wolfSSL Entering SSL_get_current_cipher
wolfSSL Entering SSL_CIPHER_get_name
wolfSSL Entering wolfSSL_get_cipher_name_from_suite
READ USED CIPHERSUITE: NONE
[0;32mI (7085) openssl_example: send https request to www.howsmyssl.com port 443 ......[0m
wolfSSL Entering SSL_write()
handshake not complete, trying to finish
wolfSSL Entering wolfSSL_negotiate
wolfSSL Entering SSL_connect()
ProcessReply retry in error state, not allowed
wolfSSL error occurred, error = -313
wolfSSL Leaving wolfSSL_negotiate, return -1
wolfSSL Leaving SSL_write(), return -1
[0;32mI (7115) openssl_example: failed[0m
wolfSSL Entering SSL_shutdown()
wolfSSL Leaving SSL_shutdown(), return -1
wolfSSL Entering SSL_free
CTX ref count not 0 yet, no free
wolfSSL Leaving SSL_free, return 0
wolfSSL Entering SSL_CTX_free
CTX ref count down to 0, doing full free
wolfSSL Entering wolfSSL_CertManagerFree
wolfSSL Leaving SSL_CTX_free, return 0
I (14055) wifi: pm start, type:0

UPDATE
I tried connecting to www.google.com and this succeeds. No changes were made to my code, so I think this will be a server issue. However, when I connect to www.howsmyssl.com with mbedtls, the request also succeeds and after comparing the packets by sniffing the network, I cannot see any major differences.

Body:
Merely sharing the Client Hello from the client won't help here. You would need to gather some SSL related logs. I am not an wolfssl expert, but looks like it exposes additional logs when you compile it using --enable-debug. I refered this: WolfSL - SSL Alert fatal error

Cipher Suites is the not the only thing that can go wrong. If the server expected a certain TLS extension in the Client Hello in a certain format and if it was not accepted even in this case, the Server can terminate the handshake.

See this thread for reference: SSL handshake_failure after clientHello

Without the debug logs, it will be like shooting in the dark.

UPDATE:

So these are the errors in the logs:

wolfSSL error occurred, error = 40
wolfSSL error occurred, error = -313

313 means the server either didn't like one of the following sent by the client:

Cipher suites

TLS Extensions

Since you have already specified supported curves, you might try enabling static key cipher suites. These seem to be disabled by default in WolfSSL. WolfSSL - Supported Cipher Suites


问:
Function in postgres with return many rows with some null value
i have little problem with function in postgress means.
I have function:

```<code>CREATE OR REPLACE FUNCTION test(
    x integer,
    y character varying,
    z character varying
)
 RETURNS TABLE(x1 int, y1 varchar,n1 varchar,z1 varchar) AS
$BODY$
BEGIN
   RETURN QUERY
SELECT  x,y,null,z  FROM example_tab
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;
</code>```

When I execute this function I take error:

```<code> Error: Returned type unknown does not match expected type character varying in column 3.

 SELECT * FROM test(694531020,'t'::varchar,'t'::varchar)
</code>```

What should I do to correct run this query and execute this function ???

答:
You should explicitly specify datatype for null, like:</p>

```<code>CREATE OR REPLACE FUNCTION test(
    x integer,
    y character varying,
    z character varying
)
 RETURNS TABLE(x1 int, y1 varchar,n1 varchar,z1 varchar) AS
$BODY$
BEGIN
   RETURN QUERY
SELECT  x,y,null::varchar,z  FROM example_tab
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;
</code>```

Body:
i have little problem with function in postgress means.
I have function:

CREATE OR REPLACE FUNCTION test(
    x integer,
    y character varying,
    z character varying
)
 RETURNS TABLE(x1 int, y1 varchar,n1 varchar,z1 varchar) AS
$BODY$
BEGIN
   RETURN QUERY
SELECT  x,y,null,z  FROM example_tab
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;

When I execute this function I take error:

 Error: Returned type unknown does not match expected type character varying in column 3.

 SELECT * FROM test(694531020,'t'::varchar,'t'::varchar)

What should I do to correct run this query and execute this function ???

Body:
You should explicitly specify datatype for null, like:

CREATE OR REPLACE FUNCTION test(
    x integer,
    y character varying,
    z character varying
)
 RETURNS TABLE(x1 int, y1 varchar,n1 varchar,z1 varchar) AS
$BODY$
BEGIN
   RETURN QUERY
SELECT  x,y,null::varchar,z  FROM example_tab
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;


问:
Using JavaScript to perform a GET request without AJAX
Out of curiosity, I'm wondering about the best (easiest, fastest, shortest, etc; make your pick) way to perform a GET request in JavaScript without using AJAX or any external libraries.

It must work cross-browser and it's not allowed to distort the hosting web page visually or affect it's functionality in any way.

I don't care about headers in the request, just the url-part. I also don't care about the result of the request. I just want the server to do something as a side effect when it receives this request, so firing it is all that matters. If your solution requires the servers to return something in particular, that's ok as well.

I'll post my own suggestion as a possible answer, but I would love it if someone could find a better way!

答:
Have you tried using an Image object? Something like:</p>

```<code>var req = new Image();
req.onload = function() {
    // Probably not required if you're only interested in
    // making the request and don't need a callback function
}
req.src = 'http://example.com/foo/bar';
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Have you tried using an Image object? Something like:

var req = new Image();
req.onload = function() {
    // Probably not required if you're only interested in
    // making the request and don't need a callback function
}
req.src = 'http://example.com/foo/bar';


问:
Efficient way to rotate a list in python
What is the most efficient way to rotate a list in python?
Right now I have something like this:

```<code>>>> def rotate(l, n):
...     return l[n:] + l[:n]
...
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]
</code>```

Is there a better way?

答:
Just some notes on timing:

If you're starting with a list, l.append(l.pop(0)) is the fastest method you can use. This can be shown with time complexity alone:

deque.rotate is O(k) (k=number of elements)

list to deque conversion is O(n)

list.append and list.pop are both O(1)

So if you are starting with deque objects, you can deque.rotate() at the cost of O(k). But, if the starting point is a list, the time complexity of using deque.rotate() is O(n). l.append(l.pop(0) is faster at O(1).

Just for the sake of illustration, here are some sample timings on 1M iterations:

Methods which require type conversion:

deque.rotate with deque object: 0.12380790710449219 seconds (fastest)

deque.rotate with type conversion: 6.853878974914551 seconds

np.roll with nparray: 6.0491721630096436 seconds

np.roll with type conversion: 27.558452129364014 seconds

List methods mentioned here:

l.append(l.pop(0)): 0.32483696937561035 seconds (fastest)

"shiftInPlace": 4.819645881652832 seconds

...

Timing code used is below.

collections.deque

Showing that creating deques from lists is O(n):

```<code>from collections import deque
import big_o

def create_deque_from_list(l):
     return deque(l)

best, others = big_o.big_o(create_deque_from_list, lambda n: big_o.datagen.integers(n, -100, 100))
print best

# --> Linear: time = -2.6E-05 + 1.8E-08*n
</code>```

If you need to create deque objects:

1M iterations @ 6.853878974914551 seconds

```<code>setup_deque_rotate_with_create_deque = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
"""

test_deque_rotate_with_create_deque = """
dl = deque(l)
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_with_create_deque, setup_deque_rotate_with_create_deque)
</code>```

If you already have deque objects:

1M iterations @ 0.12380790710449219 seconds

```<code>setup_deque_rotate_alone = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
dl = deque(l)
"""

test_deque_rotate_alone= """
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_alone, setup_deque_rotate_alone)
</code>```

np.roll

If you need to create nparrays

1M iterations @ 27.558452129364014 seconds

```<code>setup_np_roll_with_create_npa = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
"""

test_np_roll_with_create_npa = """
np.roll(l,-1) # implicit conversion of l to np.nparray
"""
</code>```

If you already have nparrays:

1M iterations @ 6.0491721630096436 seconds

```<code>setup_np_roll_alone = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
npa = np.array(l)
"""

test_roll_alone = """
np.roll(npa,-1)
"""
timeit.timeit(test_roll_alone, setup_np_roll_alone)
</code>```

"Shift in place"

Requires no type conversion

1M iterations @ 4.819645881652832 seconds

```<code>setup_shift_in_place="""
import random
l = [random.random() for i in range(1000)]
def shiftInPlace(l, n):
    n = n % len(l)
    head = l[:n]
    l[:n] = []
    l.extend(head)
    return l
"""

test_shift_in_place="""
shiftInPlace(l,-1)
"""

timeit.timeit(test_shift_in_place, setup_shift_in_place)
</code>```

l.append(l.pop(0))

Requires no type conversion

1M iterations @ 0.32483696937561035

```<code>setup_append_pop="""
import random
l = [random.random() for i in range(1000)]
"""

test_append_pop="""
l.append(l.pop(0))
"""
timeit.timeit(test_append_pop, setup_append_pop)
</code>```

Body:
What is the most efficient way to rotate a list in python?
Right now I have something like this:

>>> def rotate(l, n):
...     return l[n:] + l[:n]
...
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]

Is there a better way?

Body:
Just some notes on timing:

If you're starting with a list, l.append(l.pop(0)) is the fastest method you can use. This can be shown with time complexity alone:

deque.rotate is O(k) (k=number of elements)

list to deque conversion is O(n)

list.append and list.pop are both O(1)

So if you are starting with deque objects, you can deque.rotate() at the cost of O(k). But, if the starting point is a list, the time complexity of using deque.rotate() is O(n). l.append(l.pop(0) is faster at O(1).

Just for the sake of illustration, here are some sample timings on 1M iterations:

Methods which require type conversion:

deque.rotate with deque object: 0.12380790710449219 seconds (fastest)

deque.rotate with type conversion: 6.853878974914551 seconds

np.roll with nparray: 6.0491721630096436 seconds

np.roll with type conversion: 27.558452129364014 seconds

List methods mentioned here:

l.append(l.pop(0)): 0.32483696937561035 seconds (fastest)

"shiftInPlace": 4.819645881652832 seconds

...

Timing code used is below.

collections.deque

Showing that creating deques from lists is O(n):

from collections import deque
import big_o

def create_deque_from_list(l):
     return deque(l)

best, others = big_o.big_o(create_deque_from_list, lambda n: big_o.datagen.integers(n, -100, 100))
print best

# --> Linear: time = -2.6E-05 + 1.8E-08*n

If you need to create deque objects:

1M iterations @ 6.853878974914551 seconds

setup_deque_rotate_with_create_deque = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
"""

test_deque_rotate_with_create_deque = """
dl = deque(l)
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_with_create_deque, setup_deque_rotate_with_create_deque)

If you already have deque objects:

1M iterations @ 0.12380790710449219 seconds

setup_deque_rotate_alone = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
dl = deque(l)
"""

test_deque_rotate_alone= """
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_alone, setup_deque_rotate_alone)

np.roll

If you need to create nparrays

1M iterations @ 27.558452129364014 seconds

setup_np_roll_with_create_npa = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
"""

test_np_roll_with_create_npa = """
np.roll(l,-1) # implicit conversion of l to np.nparray
"""

If you already have nparrays:

1M iterations @ 6.0491721630096436 seconds

setup_np_roll_alone = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
npa = np.array(l)
"""

test_roll_alone = """
np.roll(npa,-1)
"""
timeit.timeit(test_roll_alone, setup_np_roll_alone)

"Shift in place"

Requires no type conversion

1M iterations @ 4.819645881652832 seconds

setup_shift_in_place="""
import random
l = [random.random() for i in range(1000)]
def shiftInPlace(l, n):
    n = n % len(l)
    head = l[:n]
    l[:n] = []
    l.extend(head)
    return l
"""

test_shift_in_place="""
shiftInPlace(l,-1)
"""

timeit.timeit(test_shift_in_place, setup_shift_in_place)

l.append(l.pop(0))

Requires no type conversion

1M iterations @ 0.32483696937561035

setup_append_pop="""
import random
l = [random.random() for i in range(1000)]
"""

test_append_pop="""
l.append(l.pop(0))
"""
timeit.timeit(test_append_pop, setup_append_pop)