问:
Selenium Cucumber Repository (Java) Picocontainer issue
Hi everybody: I'm creating a repository in Maven with Cucumber, Selenium, TestNG.

What I'm trying to do is getting the values from a properties file for sending these parameters with Selenium, but I cannot reach with the solution to the issues generated here.

This is the structure of my project:

```<code>    .
├── pom.xml
├── selenium_cucumber.iml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── utilities
│   │   │       ├── LoadProperties.java
│   │   │       └── ReportMerger.java
│   │   └── resources
│   │       ├── config.properties
│   │       └── log4j.properties
│   └── test
│       ├── java
│       │   ├── features
│       │   │   └── first.feature
│       │   ├── hooks
│       │   │   ├── ServiceHooks.java
│       │   │   ├── TakesScreenshots.java
│       │   │   └── WebDriverManager.java
│       │   ├── pages
│       │   │   ├── BasePage.java
│       │   │   └── Page_First.java
│       │   ├── runners
│       │   │   └── testNGCucumberRunner.java
│       │   └── steps
│       │       └── Step_First.java
│       └── resources
│           └── testng.xml
└── target
</code>```

This is my feature file:

```<code>@test
Feature: Navigation Test
  This is example of using Cucumber-JVM with TestNG and Selenium

  Scenario: Search google.com to verify google search is working

    Given I go to "<Url>" Google
    When I query for "<search>" cucumber spring selenium
    And click search
    Then google page title should become the first page
</code>```

Continue with the page that load the properties from a properties file (config.properties)

```<code>package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class LoadProperties {

    Properties prop;

    public LoadProperties(){

        try{
            prop = new Properties();

            File fis = new File("src/main/resources/config.properties");

            FileInputStream input = new FileInputStream(fis);

            prop.load(input);
        }
        catch(Exception e){
            System.out.println("Error loading configuration file");
        }
    }

    public String getUrl()
    {
        return prop.getProperty("Url");
    }

    public String getNavigator(){

        return prop.getProperty("navigator");
    }

    public String searchData(){

        return prop.getProperty("search");
    }

}
</code>```

The config.properties file:

```<code>navigator = "firefox"
Url = "https://www.google.com"
search = "cucumber spring selenium"
</code>```

Very important to mention that I'm using the API WebdriverManager (By Boni Garcia), because with this it is not necessary put the drivers of each browser in a folder and download them.

```<code>package hooks;

import com.codeborne.selenide.WebDriverRunner;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

    @Component
    public class WebDriverManager {

        private WebDriver webDriver;

        public WebDriver getDriver() {
            return webDriver;
        }

        @Bean(destroyMethod = "quit")
        public WebDriver getWebDriver(){
            String currentWebDriver = System.getProperty("browser", "");
            switch(currentWebDriver) {
                case ("chrome"):
                    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
                    webDriver = new ChromeDriver();
                    break;
                case ("firefox"):
                    System.setProperty("webdriver.gecko.driver", "geckodriver.exe");
                    FirefoxOptions firefoxOptions = new FirefoxOptions();
                    firefoxOptions.setCapability("marionette", true);
                    webDriver = new FirefoxDriver(firefoxOptions);
                    break;
                case ("chromeHeadless"):
                    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
                    ChromeOptions chromeHeadless = new ChromeOptions();
                    chromeHeadless.setHeadless(true);
                    webDriver = new ChromeDriver(chromeHeadless);
                    break;
                case ("iexplorer"):
                    System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
                    DesiredCapabilities capabilitiesIE = DesiredCapabilities.internetExplorer();
                    capabilitiesIE.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                    webDriver = new InternetExplorerDriver(capabilitiesIE);
                    break;
                case ("edge"):
                    System.setProperty("webdriver.edge.driver", "MicrosoftWebDriver.exe");
                    webDriver = new EdgeDriver();
                    break;
                case ("opera"):
                    System.setProperty("webdriver.opera.driver", "operadriver.exe");
                    webDriver = new OperaDriver();
                    break;
                default:
                    System.getProperty("browser", "chrome");
                    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
                    webDriver = new ChromeDriver();
                    break;
            }

            //Using Selenide driver:
            WebDriverRunner.setWebDriver(webDriver);
            return webDriver;
        }

        @PreDestroy
        public void closeSession(){
            getDriver().manage().deleteAllCookies();
            getDriver().close();
            getDriver().quit();
        }
}
</code>```

By other hand I'm working with Page Factory, this is the Common Base Page for working with:

```<code>package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public abstract class BasePage {

    private WebDriver driver ;
    private static final Logger log = Logger.getLogger(BasePage.class.getName());

    //Constructor
    public BasePage(WebDriver driver){

        this.driver = driver;
        this.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        this.driver.manage().window().maximize();
        this.driver.getTitle();

        log.info("______________________Starting tests______________________");
    }

    public String getPageTitle(){
        return driver.getTitle();
    }

    public Logger getLOG() {
        return log;
    }

    public void navigate(String Url){
        driver.get(Url);
    }

/*
    public abstract boolean isAt();
*/

    //Methods

    protected void waitForElementClickable(WebElement element){
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.elementToBeClickable(element));
    }

    protected void waitForElementVisible(WebElement element){
        WebDriverWait wait = new WebDriverWait(driver, 15);
        wait.until(ExpectedConditions.visibilityOf(element));
    }

    protected void setTextAs(WebElement element, String text) throws IOException {
        waitForElementClickable(element);
        element.sendKeys((text));
    }

    protected void clearElement(WebElement element){
        waitForElementClickable(element);
        element.clear();
    }

    protected void clickElement(WebElement element){
        waitForElementClickable(element);
        element.click();
    }

    protected void clickElementByJavascriptExecutor(String xpath){
        WebElement element=driver.findElement(By.xpath(xpath));
        JavascriptExecutor ex=(JavascriptExecutor)driver;
        ex.executeScript("arguments[0].click()", element);
    }

    protected void clickLink(WebElement element){
        waitForElementVisible(element);
        element.click();
    }

    protected String getText(WebElement element){
        waitForElementVisible(element);
        return element.getText();
    }

    protected void freeze(int seconds) {
        try {
            Thread.sleep(seconds * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Don't we forget about a Test Runner Class (testNGCucumberRunner)

```<code>package runners;

import cucumber.api.CucumberOptions;
import cucumber.api.testng.CucumberFeatureWrapper;
import cucumber.api.testng.PickleEventWrapper;
import cucumber.api.testng.TestNGCucumberRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

@CucumberOptions(
        plugin = {"pretty","json:target/report/cucumber2.json", "html:target/cucumber-reports"},
        strict = true,
        features = {"src/test/java/features"},
        tags = {"@test"},
        glue = {"steps"}
)
    public class testNGCucumberRunner {
    private static final Logger LOG = LoggerFactory.getLogger(runners.testNGCucumberRunner.class);
    private TestNGCucumberRunner testNGCucumberRunner;

    @BeforeClass(alwaysRun = true)
    public void setUpClass() throws Exception {
        testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
    }

    @Test(groups = "Cucumber", description = "Runs Cucumber Feature", dataProvider = "scenarios")
    public void scenario(PickleEventWrapper pickleEvent, CucumberFeatureWrapper cucumberFeature) throws Throwable {
        LOG.info("STARTING THIS FEATURE >>>>>" + cucumberFeature + "<<<<<<<<<<<<<<<<<<<<<<<<<<");
        testNGCucumberRunner.runScenario(pickleEvent.getPickleEvent());
    }

    @DataProvider
    public Object[][] scenarios() {
        return testNGCucumberRunner.provideScenarios();
    }

    @AfterClass(alwaysRun = true)
    public void tearDownClass() throws Exception {
        testNGCucumberRunner.finish();
    }
}
</code>```

Also the Hooks class is present here (ServiceHooks)

```<code>package hooks;

import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.codeborne.selenide.WebDriverRunner.getWebDriver;

public class ServiceHooks {

    private static final Logger log = LoggerFactory.getLogger(ServiceHooks.class);
    private WebDriver webDriver;

    @Before
    public void setUpBrowser(Scenario scenario) throws Exception {

        log.info("****************************************************************************************");
        log.info("$$$$$$$$$$$$$$$$$$$$$ Start of execution of scenario with name: " + scenario.getName() + "    $$$$$$$$$$$$$$$$$$$$$$$");
        log.info("****************************************************************************************");

        if (webDriver == null) {
            log.error("WebDriver did not initialize correctly");
        }
    }

    @After
    public void tearDown(Scenario scenario) throws Exception {
        WebDriver driver = getWebDriver();
        log.info("****************************************************************************************");
        log.info("$$$$$$$$$$$$$$$$$$$$$ Completion of execution of scenario with name: " + scenario.getName() + "    $$$$$$$$$$$$$$$$$$$$$$$");
        log.info("****************************************************************************************");
        if (scenario.isFailed()) {
            log.info("****************************************************************************************");
            log.info("$$$$$$$$$$$$$$$$$$$$$ Failing scenario with name: " + scenario.getName() + "    $$$$$$$$$$$$$$$$$$$$$$$");
            log.info("****************************************************************************************");
            try {
                byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
                scenario.embed(screenshot, "image/png");
            } catch (WebDriverException somePlatformsDontSupportScreenshots) {
                System.err.println(somePlatformsDontSupportScreenshots.getMessage());
            }
        }
        driver.quit();
        log.info("Driver closed");
    }
}
</code>```

My POM cannot be forgotten here:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>automation</groupId>
    <artifactId>selenium_cucumber</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.7.0</maven.compiler.version>
        <cucumber.version>3.0.2</cucumber.version>
        <selenium.version>3.12.0</selenium.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java8 -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java8</artifactId>
            <version>${cucumber.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-picocontainer -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-picocontainer</artifactId>
            <version>${cucumber.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>${cucumber.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.8.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.codeborne/selenide -->
        <dependency>
            <groupId>com.codeborne</groupId>
            <artifactId>selenide</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

My testng.xml file is the next:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Google Suite" verbose="1" thread-count="1" parallel="tests" configfailurepolicy="continue">
    <test name="Google UI automation">
        <classes>
            <class name="runners.testNGCucumberRunner">
                <methods>
                    <include name="scenario"/>
                </methods>
            </class>
        </classes>
    </test>
</suite>
</code>```

The Page related with the feature named before is the next:

```<code>@test
Feature: Navigation Test
  This is example of using Cucumber-JVM with TestNG and Selenium

  Scenario: Search google.com to verify google search is working

    Given I go to "<Url>" Google
    When I query for "<search>" cucumber spring selenium
    And click search
    Then google page title should become the first page
</code>```0

And the step definitions class related with this is the next one:

```<code>@test
Feature: Navigation Test
  This is example of using Cucumber-JVM with TestNG and Selenium

  Scenario: Search google.com to verify google search is working

    Given I go to "<Url>" Google
    When I query for "<search>" cucumber spring selenium
    And click search
    Then google page title should become the first page
</code>```1

After all this information and classes and more classes, I really don't know where I'm failing, because when I run the testNGCucumberRunner class from the IDE (IntelliJ IDEA) I'm getting the next error in console:

```<code>@test
Feature: Navigation Test
  This is example of using Cucumber-JVM with TestNG and Selenium

  Scenario: Search google.com to verify google search is working

    Given I go to "<Url>" Google
    When I query for "<search>" cucumber spring selenium
    And click search
    Then google page title should become the first page
</code>```2

I think is something related with picocontainer dependency (Included in my POM), but I cannot reach the failing issue.

```<code>Failed scenarios:
src/test/java/features/first.feature:6 # Search google.com to verify google search is working

1 Scenarios (1 failed)
4 Steps (1 failed, 3 skipped)
0m0.071s

org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException: steps.Step_First has unsatisfied dependency 'interface org.openqa.selenium.WebDriver' for constructor 'public steps.Step_First(org.openqa.selenium.WebDriver)' from org.picocontainer.DefaultPicoContainer@4c12331b:1<|
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:191)
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:110)
    at org.picocontainer.injectors.ConstructorInjector.access$100(ConstructorInjector.java:51)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:331)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
    at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:48)
    at cucumber.runtime.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:50)
    ...
    at cucumber.api.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:56)
    at runners.testNGCucumberRunner.scenario(testNGCucumberRunner.java:33)
    ...
    at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
    at ✽.I go to "<Url>" Google (src/test/java/features/first.feature:8)

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
===============================================
</code>```

May anybody help me with this?
Thanks in advance.

答:
It's important to read the exception message carefully. The exception is not related to pico container. But rather pico container is telling you about a problem with your step definitions.

```<code>org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException:
steps.Step_First has unsatisfied dependency 'interface org.openqa.selenium.WebDriver'
for constructor 'public steps.Step_First(org.openqa.selenium.WebDriver)'
from org.picocontainer.DefaultPicoContainer@4c12331b:1<|
</code>```

So there is something wrong the constructor for First_Step. It has an unsatisfied dependency. This means that pico container can't figure out how to create an instance of it First_Step .

```<code>    public Step_First(WebDriver driver){

        this.driver = driver;
    }
</code>```

If you look at the constructor you can see that it declares a dependency on WebDriver. So you must have an instance of the WebDriver before you can create Step_First.
Normally pico container would try to create a web driver for you. But because WebDriver is an interface it can't create an instance of it.

So you may instead want to inject ServiceHooks instead because inside that class you are creating an instance of WebDriver.

Body:
Hi everybody: I'm creating a repository in Maven with Cucumber, Selenium, TestNG.

What I'm trying to do is getting the values from a properties file for sending these parameters with Selenium, but I cannot reach with the solution to the issues generated here.

This is the structure of my project:

    .
├── pom.xml
├── selenium_cucumber.iml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── utilities
│   │   │       ├── LoadProperties.java
│   │   │       └── ReportMerger.java
│   │   └── resources
│   │       ├── config.properties
│   │       └── log4j.properties
│   └── test
│       ├── java
│       │   ├── features
│       │   │   └── first.feature
│       │   ├── hooks
│       │   │   ├── ServiceHooks.java
│       │   │   ├── TakesScreenshots.java
│       │   │   └── WebDriverManager.java
│       │   ├── pages
│       │   │   ├── BasePage.java
│       │   │   └── Page_First.java
│       │   ├── runners
│       │   │   └── testNGCucumberRunner.java
│       │   └── steps
│       │       └── Step_First.java
│       └── resources
│           └── testng.xml
└── target

This is my feature file:

@test
Feature: Navigation Test
  This is example of using Cucumber-JVM with TestNG and Selenium

  Scenario: Search google.com to verify google search is working

    Given I go to "<Url>" Google
    When I query for "<search>" cucumber spring selenium
    And click search
    Then google page title should become the first page

Continue with the page that load the properties from a properties file (config.properties)

package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class LoadProperties {

    Properties prop;

    public LoadProperties(){

        try{
            prop = new Properties();

            File fis = new File("src/main/resources/config.properties");

            FileInputStream input = new FileInputStream(fis);

            prop.load(input);
        }
        catch(Exception e){
            System.out.println("Error loading configuration file");
        }
    }

    public String getUrl()
    {
        return prop.getProperty("Url");
    }

    public String getNavigator(){

        return prop.getProperty("navigator");
    }

    public String searchData(){

        return prop.getProperty("search");
    }

}

The config.properties file:

navigator = "firefox"
Url = "https://www.google.com"
search = "cucumber spring selenium"

Very important to mention that I'm using the API WebdriverManager (By Boni Garcia), because with this it is not necessary put the drivers of each browser in a folder and download them.

package hooks;

import com.codeborne.selenide.WebDriverRunner;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

    @Component
    public class WebDriverManager {

        private WebDriver webDriver;

        public WebDriver getDriver() {
            return webDriver;
        }

        @Bean(destroyMethod = "quit")
        public WebDriver getWebDriver(){
            String currentWebDriver = System.getProperty("browser", "");
            switch(currentWebDriver) {
                case ("chrome"):
                    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
                    webDriver = new ChromeDriver();
                    break;
                case ("firefox"):
                    System.setProperty("webdriver.gecko.driver", "geckodriver.exe");
                    FirefoxOptions firefoxOptions = new FirefoxOptions();
                    firefoxOptions.setCapability("marionette", true);
                    webDriver = new FirefoxDriver(firefoxOptions);
                    break;
                case ("chromeHeadless"):
                    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
                    ChromeOptions chromeHeadless = new ChromeOptions();
                    chromeHeadless.setHeadless(true);
                    webDriver = new ChromeDriver(chromeHeadless);
                    break;
                case ("iexplorer"):
                    System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
                    DesiredCapabilities capabilitiesIE = DesiredCapabilities.internetExplorer();
                    capabilitiesIE.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                    webDriver = new InternetExplorerDriver(capabilitiesIE);
                    break;
                case ("edge"):
                    System.setProperty("webdriver.edge.driver", "MicrosoftWebDriver.exe");
                    webDriver = new EdgeDriver();
                    break;
                case ("opera"):
                    System.setProperty("webdriver.opera.driver", "operadriver.exe");
                    webDriver = new OperaDriver();
                    break;
                default:
                    System.getProperty("browser", "chrome");
                    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
                    webDriver = new ChromeDriver();
                    break;
            }

            //Using Selenide driver:
            WebDriverRunner.setWebDriver(webDriver);
            return webDriver;
        }

        @PreDestroy
        public void closeSession(){
            getDriver().manage().deleteAllCookies();
            getDriver().close();
            getDriver().quit();
        }
}

By other hand I'm working with Page Factory, this is the Common Base Page for working with:

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public abstract class BasePage {

    private WebDriver driver ;
    private static final Logger log = Logger.getLogger(BasePage.class.getName());

    //Constructor
    public BasePage(WebDriver driver){

        this.driver = driver;
        this.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        this.driver.manage().window().maximize();
        this.driver.getTitle();

        log.info("______________________Starting tests______________________");
    }

    public String getPageTitle(){
        return driver.getTitle();
    }

    public Logger getLOG() {
        return log;
    }

    public void navigate(String Url){
        driver.get(Url);
    }

/*
    public abstract boolean isAt();
*/

    //Methods

    protected void waitForElementClickable(WebElement element){
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.elementToBeClickable(element));
    }

    protected void waitForElementVisible(WebElement element){
        WebDriverWait wait = new WebDriverWait(driver, 15);
        wait.until(ExpectedConditions.visibilityOf(element));
    }

    protected void setTextAs(WebElement element, String text) throws IOException {
        waitForElementClickable(element);
        element.sendKeys((text));
    }

    protected void clearElement(WebElement element){
        waitForElementClickable(element);
        element.clear();
    }

    protected void clickElement(WebElement element){
        waitForElementClickable(element);
        element.click();
    }

    protected void clickElementByJavascriptExecutor(String xpath){
        WebElement element=driver.findElement(By.xpath(xpath));
        JavascriptExecutor ex=(JavascriptExecutor)driver;
        ex.executeScript("arguments[0].click()", element);
    }

    protected void clickLink(WebElement element){
        waitForElementVisible(element);
        element.click();
    }

    protected String getText(WebElement element){
        waitForElementVisible(element);
        return element.getText();
    }

    protected void freeze(int seconds) {
        try {
            Thread.sleep(seconds * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Don't we forget about a Test Runner Class (testNGCucumberRunner)

package runners;

import cucumber.api.CucumberOptions;
import cucumber.api.testng.CucumberFeatureWrapper;
import cucumber.api.testng.PickleEventWrapper;
import cucumber.api.testng.TestNGCucumberRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

@CucumberOptions(
        plugin = {"pretty","json:target/report/cucumber2.json", "html:target/cucumber-reports"},
        strict = true,
        features = {"src/test/java/features"},
        tags = {"@test"},
        glue = {"steps"}
)
    public class testNGCucumberRunner {
    private static final Logger LOG = LoggerFactory.getLogger(runners.testNGCucumberRunner.class);
    private TestNGCucumberRunner testNGCucumberRunner;

    @BeforeClass(alwaysRun = true)
    public void setUpClass() throws Exception {
        testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
    }

    @Test(groups = "Cucumber", description = "Runs Cucumber Feature", dataProvider = "scenarios")
    public void scenario(PickleEventWrapper pickleEvent, CucumberFeatureWrapper cucumberFeature) throws Throwable {
        LOG.info("STARTING THIS FEATURE >>>>>" + cucumberFeature + "<<<<<<<<<<<<<<<<<<<<<<<<<<");
        testNGCucumberRunner.runScenario(pickleEvent.getPickleEvent());
    }

    @DataProvider
    public Object[][] scenarios() {
        return testNGCucumberRunner.provideScenarios();
    }

    @AfterClass(alwaysRun = true)
    public void tearDownClass() throws Exception {
        testNGCucumberRunner.finish();
    }
}

Also the Hooks class is present here (ServiceHooks)

package hooks;

import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.codeborne.selenide.WebDriverRunner.getWebDriver;

public class ServiceHooks {

    private static final Logger log = LoggerFactory.getLogger(ServiceHooks.class);
    private WebDriver webDriver;

    @Before
    public void setUpBrowser(Scenario scenario) throws Exception {

        log.info("****************************************************************************************");
        log.info("$$$$$$$$$$$$$$$$$$$$$ Start of execution of scenario with name: " + scenario.getName() + "    $$$$$$$$$$$$$$$$$$$$$$$");
        log.info("****************************************************************************************");

        if (webDriver == null) {
            log.error("WebDriver did not initialize correctly");
        }
    }

    @After
    public void tearDown(Scenario scenario) throws Exception {
        WebDriver driver = getWebDriver();
        log.info("****************************************************************************************");
        log.info("$$$$$$$$$$$$$$$$$$$$$ Completion of execution of scenario with name: " + scenario.getName() + "    $$$$$$$$$$$$$$$$$$$$$$$");
        log.info("****************************************************************************************");
        if (scenario.isFailed()) {
            log.info("****************************************************************************************");
            log.info("$$$$$$$$$$$$$$$$$$$$$ Failing scenario with name: " + scenario.getName() + "    $$$$$$$$$$$$$$$$$$$$$$$");
            log.info("****************************************************************************************");
            try {
                byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
                scenario.embed(screenshot, "image/png");
            } catch (WebDriverException somePlatformsDontSupportScreenshots) {
                System.err.println(somePlatformsDontSupportScreenshots.getMessage());
            }
        }
        driver.quit();
        log.info("Driver closed");
    }
}

My POM cannot be forgotten here:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>automation</groupId>
    <artifactId>selenium_cucumber</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.7.0</maven.compiler.version>
        <cucumber.version>3.0.2</cucumber.version>
        <selenium.version>3.12.0</selenium.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java8</artifactId>
            <version>${cucumber.version}</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-picocontainer</artifactId>
            <version>${cucumber.version}</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>${cucumber.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.8.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.codeborne</groupId>
            <artifactId>selenide</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

My testng.xml file is the next:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Google Suite" verbose="1" thread-count="1" parallel="tests" configfailurepolicy="continue">
    <test name="Google UI automation">
        <classes>
            <class name="runners.testNGCucumberRunner">
                <methods>
                    <include name="scenario"/>
                </methods>
            </class>
        </classes>
    </test>
</suite>

The Page related with the feature named before is the next:

package pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import java.io.IOException;

public class Page_First extends BasePage{

    /////////////Constructor/////////////

    public Page_First(WebDriver driver) {
        super(driver);
    }

    //////////////////////////////////////////////WEB ELEMENTS//////////////////////////////////////////////////////////

    @FindBy(name = "q")
    private WebElement searchText;

    @FindBy(name="btnK")
    private WebElement searchButton;

    //////////////////////////////////////////////BASE METHODS//////////////////////////////////////////////////////////

    public void search(String search) throws IOException {
        setTextAs(searchText, search);
    }

    public void enterButton (){
        clickElement(searchButton);
    }
}

And the step definitions class related with this is the next one:

package steps;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
import pages.Page_First;
import utilities.LoadProperties;

import java.io.IOException;
import java.util.logging.Logger;

public class Step_First {

    private WebDriver driver;
    private BasePage basepage;

    private Page_First page_first = PageFactory.initElements(driver, Page_First.class);

    private static final java.util.logging.Logger log = Logger.getLogger(Page_First.class.getName());
    LoadProperties load = new LoadProperties();

    public Step_First(WebDriver driver){

        this.driver = driver;
    }

    @Given("I go to {string} Google")
    public void I_go_to_Google (String Url) {

        load.getUrl();
    //    basepage.navigate(Url);
    }

    @When("I query for {string} cucumber spring selenium")
    public void I_query_for_cucumber_spring_selenium (String search) throws IOException {

        page_first.search(search);
    }

    @When("click search")
    public void click_search(){

        page_first.enterButton();
    }

    @Then("google page title should become the first page")
    public void google_page_title_should_become_the_first_page() {

        log.info("All OK");

    }
}

After all this information and classes and more classes, I really don't know where I'm failing, because when I run the testNGCucumberRunner class from the IDE (IntelliJ IDEA) I'm getting the next error in console:

    @test
  Scenario: Search google.com to verify google search is working # src/test/java/features/first.feature:6
    Given I go to "<Url>" Google                                 # Step_First.I_go_to_Google(String)
      org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException: steps.Step_First has unsatisfied dependency 'interface org.openqa.selenium.WebDriver' for constructor 'public steps.Step_First(org.openqa.selenium.WebDriver)' from org.picocontainer.DefaultPicoContainer@4c12331b:1<|
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:191)
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:110)
    at org.picocontainer.injectors.ConstructorInjector.access$100(ConstructorInjector.java:51)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:331)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
    at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:48)
    at cucumber.runtime.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:50)
    at cucumber.runner.TestStep.executeStep(TestStep.java:55)
    at cucumber.runner.TestStep.run(TestStep.java:42)
    at cucumber.runner.PickleStepTestStep.run(PickleStepTestStep.java:53)
    at cucumber.runner.TestCase.run(TestCase.java:47)
    at cucumber.runner.Runner.runPickle(Runner.java:44)
    at cucumber.api.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:56)
    at runners.testNGCucumberRunner.scenario(testNGCucumberRunner.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    ...
    at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
    at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
    at ✽.I go to "<Url>" Google (src/test/java/features/first.feature:8)

I think is something related with picocontainer dependency (Included in my POM), but I cannot reach the failing issue.

Failed scenarios:
src/test/java/features/first.feature:6 # Search google.com to verify google search is working

1 Scenarios (1 failed)
4 Steps (1 failed, 3 skipped)
0m0.071s

org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException: steps.Step_First has unsatisfied dependency 'interface org.openqa.selenium.WebDriver' for constructor 'public steps.Step_First(org.openqa.selenium.WebDriver)' from org.picocontainer.DefaultPicoContainer@4c12331b:1<|
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:191)
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:110)
    at org.picocontainer.injectors.ConstructorInjector.access$100(ConstructorInjector.java:51)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:331)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
    at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:48)
    at cucumber.runtime.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:50)
    ...
    at cucumber.api.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:56)
    at runners.testNGCucumberRunner.scenario(testNGCucumberRunner.java:33)
    ...
    at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
    at ✽.I go to "<Url>" Google (src/test/java/features/first.feature:8)

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
===============================================

May anybody help me with this?
Thanks in advance.

Body:
It's important to read the exception message carefully. The exception is not related to pico container. But rather pico container is telling you about a problem with your step definitions.

org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException:
steps.Step_First has unsatisfied dependency 'interface org.openqa.selenium.WebDriver'
for constructor 'public steps.Step_First(org.openqa.selenium.WebDriver)'
from org.picocontainer.DefaultPicoContainer@4c12331b:1<|

So there is something wrong the constructor for First_Step. It has an unsatisfied dependency. This means that pico container can't figure out how to create an instance of it First_Step .

    public Step_First(WebDriver driver){

        this.driver = driver;
    }

If you look at the constructor you can see that it declares a dependency on WebDriver. So you must have an instance of the WebDriver before you can create Step_First.
Normally pico container would try to create a web driver for you. But because WebDriver is an interface it can't create an instance of it.

So you may instead want to inject ServiceHooks instead because inside that class you are creating an instance of WebDriver.


来源: stackexchange

问:
Trying to make button appear onmouseover
I am trying to make it so that when i mouse over where this button is, it appears.

here is my code

html:

```<code><div class="hide"><button type="button" onmouseover="appear()" id="button">LIGHT!!</button></div>
</code>```

css:

```<code>div.appear {display: none;}
</code>```

javascript:

```<code>function appear(){document.getElementById("button").style.display = "block";}
</code>```

答:
A hidden element has no mouse events so you would need to use opacity.

.hide {
  opacity: 0;
  transition: opacity 0.5s ease;
}

.hide:hover {
  opacity: 1;
  transition: opacity 0.5s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hide"><button type="button" id="button">LIGHT!!</button></div></code>```

You can hide it if you apply the hover/mouseover to the parent

.hide {
  height: 30px;
  width: 200px;
}

.hide > button {
  display: none;
}

.hide:hover > button {
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hide"><button type="button" id="button">LIGHT!!</button></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make it so that when i mouse over where this button is, it appears.

here is my code

html:

<button type="button" onmouseover="appear()" id="button">LIGHT!!</button>

css:

div.appear {display: none;}

javascript:

function appear(){document.getElementById("button").style.display = "block";}

Body:
A hidden element has no mouse events so you would need to use opacity.

.hide {
  opacity: 0;
  transition: opacity 0.5s ease;
}

.hide:hover {
  opacity: 1;
  transition: opacity 0.5s ease;
}

<div class="hide"><button type="button" id="button">LIGHT!!</button></div>

You can hide it if you apply the hover/mouseover to the parent

.hide {
  height: 30px;
  width: 200px;
}

.hide > button {
  display: none;
}

.hide:hover > button {
  display: inline;
}

<div class="hide"><button type="button" id="button">LIGHT!!</button></div>


问:
Open multiple copies of Word template document using VBA for applications
I am developing a database application where users open a Word template document and merge this with database records. I have successfully written code that does this for one record where I open a template file and replace items in the template document with DB data. I have tried opening the template document multiple times (once for each DB record), but this opens a Word dialogue box prompting the user to open the second and subsequent documents as read only (not very elegant) and I get a Word Normal.dotm error when each of the documents is closed.
So, how can I use one template document to create multiple word documents at the same time. Two options as I see them are to 1) Save one doc in a new name before creating other documents or 2) Have one document with multiple pages (one per DB record) but to do this I would have to copy and paste the template document contents once for every record, but I don't see how to do this.
Please keep in mind that I am experienced in database programming and only a rudimentary knowledge of VB for applications, so the more explicit you can be, the more useful it will be.

Thanks in advance.

答:
This function will create a new document for each record based on a specified template. I'm using a preset bookmark in the Word template to add data from the database. This sub would run in the database.</p>

```<code>Public Sub CreateDocs()

    Dim oWord As Word.Application
    Set oWord = New Word.Application
    Dim oDocument As Word.Document
    Dim oDatabase As DAO.Database
    Set oDatabase = CurrentDb

    ' where to save our files
    Dim strDocPath As String
    strDocPath = CurrentProject.Path & "\"

    ' preset bookmark in template
    Dim oBookMark As Word.Bookmark

    ' query with records
    Dim oRecordset As DAO.Recordset
    Set oRecordset = oDatabase.OpenRecordset("qrySomeQuery")

    ' template file
    Dim strTemplateName As String
    strTemplateName = "C:\users\you\Documents\Doc1.dotx"

    ' hide Word
    oWord.WindowState = wdWindowStateMinimize
    oWord.Visible = False

    While Not oRecordset.EOF
        ' create new document from template
        Set oDocument = oWord.Documents.Add(strTemplatePath, False, , False)

        ' get reference to bookmark in template
        Set oBookMark = oDocument.Bookmarks("bkmkSomePlace")

        ' add our data
        oBookMark.Range.Text = oRecordset.Fields(0).Value & vbTab & oRecordset.Fields(1).Value

        ' Save and close
        ' Saving using one of the query fields that is unique
        oDocument.SaveAs strDocPath & "generatedFile" & oRecordset.Fields(0).Value, wdFormatDocumentDefault
        oDocument.Close

        ' next record
        oRecordset.MoveNext
    Wend

    oWord.Close
    Set oWord = Nothing
    If Not oRecordset Is Nothing Then oRecordset.Close
    Set oRecordset = Nothing
    oDatabase.Close
    Set oDatabase = Nothing
    Set oDocument = Nothing
End Sub
</code>```

OwnerDisplayName: Frank Battista

ContentLicense: CC BY-SA 2.5

Body:
This function will create a new document for each record based on a specified template. I'm using a preset bookmark in the Word template to add data from the database. This sub would run in the database.

Public Sub CreateDocs()

    Dim oWord As Word.Application
    Set oWord = New Word.Application
    Dim oDocument As Word.Document
    Dim oDatabase As DAO.Database
    Set oDatabase = CurrentDb

    ' where to save our files
    Dim strDocPath As String
    strDocPath = CurrentProject.Path & "\"

    ' preset bookmark in template
    Dim oBookMark As Word.Bookmark

    ' query with records
    Dim oRecordset As DAO.Recordset
    Set oRecordset = oDatabase.OpenRecordset("qrySomeQuery")

    ' template file
    Dim strTemplateName As String
    strTemplateName = "C:\users\you\Documents\Doc1.dotx"

    ' hide Word
    oWord.WindowState = wdWindowStateMinimize
    oWord.Visible = False

    While Not oRecordset.EOF
        ' create new document from template
        Set oDocument = oWord.Documents.Add(strTemplatePath, False, , False)

        ' get reference to bookmark in template
        Set oBookMark = oDocument.Bookmarks("bkmkSomePlace")

        ' add our data
        oBookMark.Range.Text = oRecordset.Fields(0).Value & vbTab & oRecordset.Fields(1).Value

        ' Save and close
        ' Saving using one of the query fields that is unique
        oDocument.SaveAs strDocPath & "generatedFile" & oRecordset.Fields(0).Value, wdFormatDocumentDefault
        oDocument.Close

        ' next record
        oRecordset.MoveNext
    Wend

    oWord.Close
    Set oWord = Nothing
    If Not oRecordset Is Nothing Then oRecordset.Close
    Set oRecordset = Nothing
    oDatabase.Close
    Set oDatabase = Nothing
    Set oDocument = Nothing
End Sub

ContentLicense: CC BY-SA 3.0


问:
Why my generated Flex/Bison parser gives syntax error even if it's added in rules?
I am trying to implement a simple flex/bison code which will check a C like a program as follows:

```<code>main(){
x = 3;
print x;
}
</code>```

But when I provide this input to the program, it is not able to match with the rules I mentioned in the flex file. Below is my code for both flex and bison files:

calc.l

```<code>%{
#include <stdio.h>
#include <string.h>
#include "calc.tab.h"
int lineno = 1;
%}

digit   [0-9]+
id      [a-z][a-zA-Z0-9]*

%%
{digit}+    { yylval.num = atoi(yytext); return TOK_NUMBER; }
"main"      { return TOK_MAIN; }
"("         { return TOK_ORBRACKET; }
")"         { return TOK_CRBRACKET; }
"{"         { return TOK_OCBRACKET; }
"}"         { return TOK_CCBRACKET; }
"print"     { return TOK_PRINT; }
{id}        { sscanf(yytext, "%s", (yylval.index)); return TOK_VARIABLE; }
";"         { return TOK_SEMICOLON; }
"+"         { return TOK_ADD; }
"*"         { return TOK_MUL; }
"(-{digit}+)" { return TOK_NEGNUM; }
"="         { return TOK_EQUAL; }
[ \t]+      { }
[ \n]+      { lineno++; }
.           { printf("Lexical error:'%c'\n", yytext[0]); }

%%
</code>```

calc.y

```<code>%{
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "calc.tab.h"

extern int lineno;
int variable_counter = 0;

/* Flex functions */
int yylex(void);
void yyerror(char *s);
void set_variable(char* var_name, int var_value);
int get_variable_value(char* var_name);
extern FILE* yyin;
%}

%union {
    char index[100];
    int num;
}

%token TOK_NUMBER TOK_MUL TOK_ADD TOK_NEGNUM TOK_EQUAL TOK_MAIN TOK_ORBRACKET TOK_CRBRACKET TOK_OCBRACKET TOK_CCBRACKET TOK_SEMICOLON TOK_PRINT TOK_VARIABLE

%code requires {
    struct symtable
    {
        char var_name[100];
        int var_value;
    };
}

%code {
    struct symtable symboltable[100];
    int pos = 0;
}

%type <num> expr TOK_NUMBER TOK_NEGNUM
%type <index> TOK_VARIABLE

%left TOK_ADD
%left TOK_MUL

%%

prog:
    TOK_MAIN TOK_ORBRACKET TOK_CRBRACKET TOK_OCBRACKET stmts TOK_CCBRACKET
;

stmts:
    | stmt TOK_SEMICOLON stmts
;

stmt:
    expr TOK_SEMICOLON
    | TOK_PRINT expr TOK_SEMICOLON      {   fprintf(stdout, "%d\n", $2);    }
    | assignment
;

expr:
    TOK_NUMBER                                  { $$ = $1; }
    | TOK_VARIABLE                              { $$ = get_variable_value($1); }
    | expr TOK_MUL expr                         { $$ = $1 * $3; }
    | expr TOK_ADD expr                         { $$ = $1 + $3; }
    | TOK_NEGNUM                                { $$ = -$1; }
    | TOK_ORBRACKET expr TOK_CRBRACKET          { $$ = $2; }
;

assignment:
    TOK_VARIABLE TOK_EQUAL expr { set_variable($1, $3); }
;

%%

void set_variable(char* var_name, int var_value) {
    int counter;
    bool found = false;
    for (counter = 0; counter<=variable_counter; counter++) {
        if (strcmp(var_name, symboltable[counter].var_name) == 0) {
            found = true;
            break;
        }
    }

    if(!found) {
        strcpy(symboltable[counter].var_name, var_name);
        symboltable[counter].var_value = var_value;
        variable_counter++;
    }
}

int get_variable_value(char* var_name) {
    int counter;
    for (counter = 0; counter<=variable_counter; counter++) {
        if (strcmp(var_name, symboltable[counter].var_name) == 0) {
            return symboltable[counter].var_value;
        }
    }
}

void yyerror(char *s)
{
    fprintf(stderr, "Parsing error: line %d and %s\n", lineno, s);
}

int main(int argc,char* argv[])
{
    if(argc==1) {
        printf("\nPlease provide an input file name. Exiting...\n");
        return 0;
    }

    yyin = fopen(argv[1], "r");
    if (!yyin) {
        printf("ERROR: Couldn't open file %s\n", argv[1]);
        return -1;
    }

    yyparse();
    return 0;
}

</code>```

It is showing output as:

```<code>'exical error:'
'exical error:'
3
'exical error:'
Parsing error: line 4 and syntax error
</code>```

Thanks in advance for your help.

答:
Two issues:

The messages 'exical error:' come from DOS-style \r\n line endings in your parsed file. You should either convert these to \n endings or eat the \r characters in your parser, for example by extending the rule

```<code>[ \t]+      { }
</code>```

to

```<code>[ \t\r]+      { }
</code>```

The message Parsing error: line 4 and syntax error comes from a logic flaw in your parser. Here

```<code>stmts:
    | stmt TOK_SEMICOLON stmts
;
</code>```

you specify, that each stmt is terminated by a semicolon. But here

```<code>stmt:
    expr TOK_SEMICOLON
    | TOK_PRINT expr TOK_SEMICOLON      {   fprintf(stdout, "%d\n", $2);    }
    | assignment
;
</code>```

you also require a semicolon after expr and TOK_PRINT expr. So you needed two semicolons after this line

```<code>print x;;
</code>```

But you probably want to remove the redundant TOK_SEMICOLON like this:

```<code>stmt:
    expr
    | TOK_PRINT expr      {   fprintf(stdout, "%d\n", $2);    }
    | assignment
;
</code>```

Then your file should parse as you expect.

Body:
I am trying to implement a simple flex/bison code which will check a C like a program as follows:

main(){
x = 3;
print x;
}

But when I provide this input to the program, it is not able to match with the rules I mentioned in the flex file. Below is my code for both flex and bison files:

calc.l

%{
#include <stdio.h>
#include <string.h>
#include "calc.tab.h"
int lineno = 1;
%}

digit   [0-9]+
id      [a-z][a-zA-Z0-9]*

%%
{digit}+    { yylval.num = atoi(yytext); return TOK_NUMBER; }
"main"      { return TOK_MAIN; }
"("         { return TOK_ORBRACKET; }
")"         { return TOK_CRBRACKET; }
"{"         { return TOK_OCBRACKET; }
"}"         { return TOK_CCBRACKET; }
"print"     { return TOK_PRINT; }
{id}        { sscanf(yytext, "%s", (yylval.index)); return TOK_VARIABLE; }
";"         { return TOK_SEMICOLON; }
"+"         { return TOK_ADD; }
"*"         { return TOK_MUL; }
"(-{digit}+)" { return TOK_NEGNUM; }
"="         { return TOK_EQUAL; }
[ \t]+      { }
[ \n]+      { lineno++; }
.           { printf("Lexical error:'%c'\n", yytext[0]); }

%%

calc.y

%{
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "calc.tab.h"

extern int lineno;
int variable_counter = 0;

/* Flex functions */
int yylex(void);
void yyerror(char *s);
void set_variable(char* var_name, int var_value);
int get_variable_value(char* var_name);
extern FILE* yyin;
%}

%union {
    char index[100];
    int num;
}

%token TOK_NUMBER TOK_MUL TOK_ADD TOK_NEGNUM TOK_EQUAL TOK_MAIN TOK_ORBRACKET TOK_CRBRACKET TOK_OCBRACKET TOK_CCBRACKET TOK_SEMICOLON TOK_PRINT TOK_VARIABLE

%code requires {
    struct symtable
    {
        char var_name[100];
        int var_value;
    };
}

%code {
    struct symtable symboltable[100];
    int pos = 0;
}

%type <num> expr TOK_NUMBER TOK_NEGNUM
%type <index> TOK_VARIABLE

%left TOK_ADD
%left TOK_MUL

%%

prog:
    TOK_MAIN TOK_ORBRACKET TOK_CRBRACKET TOK_OCBRACKET stmts TOK_CCBRACKET
;

stmts:
    | stmt TOK_SEMICOLON stmts
;

stmt:
    expr TOK_SEMICOLON
    | TOK_PRINT expr TOK_SEMICOLON      {   fprintf(stdout, "%d\n", $2);    }
    | assignment
;

expr:
    TOK_NUMBER                                  { $$ = $1; }
    | TOK_VARIABLE                              { $$ = get_variable_value($1); }
    | expr TOK_MUL expr                         { $$ = $1 * $3; }
    | expr TOK_ADD expr                         { $$ = $1 + $3; }
    | TOK_NEGNUM                                { $$ = -$1; }
    | TOK_ORBRACKET expr TOK_CRBRACKET          { $$ = $2; }
;

assignment:
    TOK_VARIABLE TOK_EQUAL expr { set_variable($1, $3); }
;

%%

void set_variable(char* var_name, int var_value) {
    int counter;
    bool found = false;
    for (counter = 0; counter<=variable_counter; counter++) {
        if (strcmp(var_name, symboltable[counter].var_name) == 0) {
            found = true;
            break;
        }
    }

    if(!found) {
        strcpy(symboltable[counter].var_name, var_name);
        symboltable[counter].var_value = var_value;
        variable_counter++;
    }
}

int get_variable_value(char* var_name) {
    int counter;
    for (counter = 0; counter<=variable_counter; counter++) {
        if (strcmp(var_name, symboltable[counter].var_name) == 0) {
            return symboltable[counter].var_value;
        }
    }
}

void yyerror(char *s)
{
    fprintf(stderr, "Parsing error: line %d and %s\n", lineno, s);
}

int main(int argc,char* argv[])
{
    if(argc==1) {
        printf("\nPlease provide an input file name. Exiting...\n");
        return 0;
    }

    yyin = fopen(argv[1], "r");
    if (!yyin) {
        printf("ERROR: Couldn't open file %s\n", argv[1]);
        return -1;
    }

    yyparse();
    return 0;
}

It is showing output as:

'exical error:'
'exical error:'
3
'exical error:'
Parsing error: line 4 and syntax error

Thanks in advance for your help.

Body:
Two issues:

The messages 'exical error:' come from DOS-style \r\n line endings in your parsed file. You should either convert these to \n endings or eat the \r characters in your parser, for example by extending the rule

[ \t]+      { }

to

[ \t\r]+      { }

The message Parsing error: line 4 and syntax error comes from a logic flaw in your parser. Here

stmts:
    | stmt TOK_SEMICOLON stmts
;

you specify, that each stmt is terminated by a semicolon. But here

stmt:
    expr TOK_SEMICOLON
    | TOK_PRINT expr TOK_SEMICOLON      {   fprintf(stdout, "%d\n", $2);    }
    | assignment
;

you also require a semicolon after expr and TOK_PRINT expr. So you needed two semicolons after this line

print x;;

But you probably want to remove the redundant TOK_SEMICOLON like this:

stmt:
    expr
    | TOK_PRINT expr      {   fprintf(stdout, "%d\n", $2);    }
    | assignment
;

Then your file should parse as you expect.


问:
Laravel Eloquent disable automatic lazy loading
Laravel by default has this automatic eager loading which may cause some multiple query issue Eg:

```<code>// If do something like this
$posts = Post::published()->get();
// then
foreach ($posts as $p) {
    echo $p->author->name;
}
// Eloquent will query the author for every post
</code>```

Is it possible to disable this behavior?

答:
It's lazy load the example you provided as @LobsterBaz mentioned. If you want to avoid that:

You can check if the relationship is loaded

```<code>foreach ($posts as $p) {
    if ($p->relationLoaded('author')) echo $p->author->name;
}
</code>```

But I found this package Laravel Disable Lazy Load which has all the credit for the idea.

That is very simple. By borrowing the idea you can create a Trait yourself to do it overriding the getRelationshipFromMethod.

```<code><?php

namespace App\Traits;

trait DisableLazyLoad
{
    public function getRelationshipFromMethod($method)
    {
        throw new \BadMethodCallException('Relation lazy load has been disabled for performance reasons.');
    }
}
</code>```

Then use the Trait in your Model

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\DisableLazyLoad;

class Post extends Model
{

    use DisableLazyLoad;

}
</code>```

or install the package an use it in the same way

```<code>composer require ybaruchel/laravel-disable-lazyload
</code>```

Body:
Laravel by default has this automatic eager loading which may cause some multiple query issue Eg:

// If do something like this
$posts = Post::published()->get();
// then
foreach ($posts as $p) {
    echo $p->author->name;
}
// Eloquent will query the author for every post

Is it possible to disable this behavior?

Body:
It's lazy load the example you provided as @LobsterBaz mentioned. If you want to avoid that:

You can check if the relationship is loaded

foreach ($posts as $p) {
    if ($p->relationLoaded('author')) echo $p->author->name;
}

But I found this package Laravel Disable Lazy Load which has all the credit for the idea.

That is very simple. By borrowing the idea you can create a Trait yourself to do it overriding the getRelationshipFromMethod.

<?php

namespace App\Traits;

trait DisableLazyLoad
{
    public function getRelationshipFromMethod($method)
    {
        throw new \BadMethodCallException('Relation lazy load has been disabled for performance reasons.');
    }
}

Then use the Trait in your Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\DisableLazyLoad;

class Post extends Model
{

    use DisableLazyLoad;

}

or install the package an use it in the same way

composer require ybaruchel/laravel-disable-lazyload


问:
Replace Product SKU Based on product Title in Order Details Page
I am trying to append text to the SKU when a sample is ordered.

I have tried the following code to modify the title,

```<code>  function cart_title($title, $values, $cart_item_key){
          if ($values['sample']){
                  $title .= ' [' . __('Sample','woosample') . '] ';
          }
          return $title;
  }
</code>```

How do I modify this code to change the SKU?

答:
note: woocommerce_cart_item_name will not display in the backend order
  view

function cart_title( $title, $cart_item, $cart_item_key ) {
    $product = $cart_item['data'];

    $product_sku = $product->get_sku();

    // optional
    if ( empty( $product_sku ) ) {
        $product_sku = 'not found!';
    }

    $title = $title . ' + ' .  $product_sku;
    return $title;
}
add_filter('woocommerce_cart_item_name', 'cart_title', 10, 3 );
```

Body:
I am trying to append text to the SKU when a sample is ordered.

I have tried the following code to modify the title,

  function cart_title($title, $values, $cart_item_key){
          if ($values['sample']){
                  $title .= ' [' . __('Sample','woosample') . '] ';
          }
          return $title;
  }

How do I modify this code to change the SKU?


问:
Autodesk Forge .NET SDK GetObject function and downloading files from BIM 360 Docs hub
I am having trouble using the GetObject function from the Forge .NET SDK to download a file from a BIM 360 Docs hub.

Here is my jQuery ajax call (client side) :

```<code>function downloadFile(storageUrl, displayName) {
jQuery.ajax({
    url: '/api/forge/datamanagement/download?' + $.param({ storageUrl: storageUrl }),
    success: function (res) {
        // create a blob url representing the data
        var blob = new Blob([res]);
        var url = window.URL.createObjectURL(blob);
        // attach blob url to anchor element with download attribute
        var anchor = document.createElement('a');
        anchor.setAttribute('href', url);
        anchor.setAttribute('download', displayName);
        anchor.click();
        window.URL.revokeObjectURL(url);
    }
});
</code>```

And here is my .NET C# corresponding controller function (server side) :

```<code>    [HttpGet]
    [Route("api/forge/datamanagement/download")]
    public async Task<dynamic> GetObject(string storageUrl)
    {
        Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);
        if (Credentials == null) { return null; }

        ObjectsApi objectsApi = new ObjectsApi();
        objectsApi.Configuration.AccessToken = Credentials.TokenInternal;

        string[] idParams = storageUrl.Split('/');
        string bucketKey = idParams[6];
        string objectName = idParams[8];
        if (objectName.Contains("?"))
            objectName = objectName.Split("?")[0];

        dynamic obj = await objectsApi.GetObjectAsync(bucketKey, objectName);

        if (obj is FileStream)
            return File(obj, "application/octet-stream");

        if (obj is MemoryStream ms)
        {
            FileStream fs = new FileStream(Path.Combine(Path.GetTempPath(), objectName), FileMode.Create, FileAccess.ReadWrite);
            ms.CopyTo(fs);
            ms.Position = 0;
            fs.Position = 0;
            return File(fs, "application/octet-stream");
        }

        return null;
    }
</code>```

The trouble is after getting the result from GetObjectAsync call :

If it returns a FileStream (like for .txt files), there is no problem, downloaded files are correct.

If it returns a MemoryStream (like for .json and .rvt files), I write it in a FileStream then returns it. But it works only for .json files. For .rvt files, the downloaded files are corrupt and cannot be opened by Revit.

What is strange is that :

the corrupt files are approximately 2 times bigger than the "real"/"correct" ones.

when copying the MemoryStream into a FileStream the temporary created Revit files in my server temp folder are correct.

What am I missing here ?

Thanks for your help.

Maxime

答:
There is probably an encoding issue here, as you mentioned the file is 2x bigger.

Anyway, I would suggest you use a "proxy" approach instead. Let me explain: the GetObjectAsync will download the entire file to your server, which can be big and allocate a lot of memory. Even if you save it locally before sending to the client, still allocating disk resources...

A proxy approach would just get chunks of data from Forge and stream each chunk to the client. There are different ways of implementing it, probably this other answer is a start.

Body:
I am having trouble using the GetObject function from the Forge .NET SDK to download a file from a BIM 360 Docs hub.

Here is my jQuery ajax call (client side) :

function downloadFile(storageUrl, displayName) {
jQuery.ajax({
    url: '/api/forge/datamanagement/download?' + $.param({ storageUrl: storageUrl }),
    success: function (res) {
        // create a blob url representing the data
        var blob = new Blob([res]);
        var url = window.URL.createObjectURL(blob);
        // attach blob url to anchor element with download attribute
        var anchor = document.createElement('a');
        anchor.setAttribute('href', url);
        anchor.setAttribute('download', displayName);
        anchor.click();
        window.URL.revokeObjectURL(url);
    }
});

And here is my .NET C# corresponding controller function (server side) :

    [HttpGet]
    [Route("api/forge/datamanagement/download")]
    public async Task<dynamic> GetObject(string storageUrl)
    {
        Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);
        if (Credentials == null) { return null; }

        ObjectsApi objectsApi = new ObjectsApi();
        objectsApi.Configuration.AccessToken = Credentials.TokenInternal;

        string[] idParams = storageUrl.Split('/');
        string bucketKey = idParams[6];
        string objectName = idParams[8];
        if (objectName.Contains("?"))
            objectName = objectName.Split("?")[0];

        dynamic obj = await objectsApi.GetObjectAsync(bucketKey, objectName);

        if (obj is FileStream)
            return File(obj, "application/octet-stream");

        if (obj is MemoryStream ms)
        {
            FileStream fs = new FileStream(Path.Combine(Path.GetTempPath(), objectName), FileMode.Create, FileAccess.ReadWrite);
            ms.CopyTo(fs);
            ms.Position = 0;
            fs.Position = 0;
            return File(fs, "application/octet-stream");
        }

        return null;
    }

The trouble is after getting the result from GetObjectAsync call :

If it returns a FileStream (like for .txt files), there is no problem, downloaded files are correct.

If it returns a MemoryStream (like for .json and .rvt files), I write it in a FileStream then returns it. But it works only for .json files. For .rvt files, the downloaded files are corrupt and cannot be opened by Revit.

What is strange is that :

the corrupt files are approximately 2 times bigger than the "real"/"correct" ones.

when copying the MemoryStream into a FileStream the temporary created Revit files in my server temp folder are correct.

What am I missing here ?

Thanks for your help.

Maxime


问:
Streaming input for speech recognition
How to extract feature from stream of sound?

I tried to use htk, pytorch, or other libraries for filterbank.
But they need loading wav file.

I want to process directly microphone input by pyaudio.

```<code>p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True)
while stream.is_active():
    input = stream.read(CHUNK)
</code>```

答:
You can use librosa, pretty standard library. You need stream feature:

https://librosa.github.io/librosa/generated/librosa.core.stream.html

```<code>p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True)
stream = librosa.stream(stream,
                         block_length=256,
                         frame_length=2048,
                         hop_length=2048)
for y_block in stream:
     m_block = librosa.feature.melspectrogram(y_block, sr=sr,
                                              n_fft=2048,
                                              hop_length=2048,
                                              center=False)
</code>```

Title: Streaming input for speech recognition

Body:
How to extract feature from stream of sound?

I tried to use htk, pytorch, or other libraries for filterbank.
But they need loading wav file.

I want to process directly microphone input by pyaudio.

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True)
while stream.is_active():
    input = stream.read(CHUNK)

Body:
You can use librosa, pretty standard library. You need stream feature:

https://librosa.github.io/librosa/generated/librosa.core.stream.html

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True)
stream = librosa.stream(stream,
                         block_length=256,
                         frame_length=2048,
                         hop_length=2048)
for y_block in stream:
     m_block = librosa.feature.melspectrogram(y_block, sr=sr,
                                              n_fft=2048,
                                              hop_length=2048,
                                              center=False)


问:
Memory Leak warning while addSubView to Current ViewController
I get memory leak warning when I addsubView to Current ViewController....This is my code..

```<code>     NoOfGolferViewController *objNoOfGolferViewController = [[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil];
     [objNoOfGolferViewController setParent:self];
     [objNoOfGolferViewController.view setFrame:CGRectMake(15, 110, 290, 330)];
     [self.view addSubview:objNoOfGolferViewController.view];
</code>```

and when I release object

```<code>      [objNoOfGolferViewController release];
</code>```

Application get crashed by giving EXE_BAD_ACCESS message.

How can I solve this memory leak warning?

Thanks in advance..

答:
Probably you are declaring variable locally.
Instead make it global and release it in dealloc.
Reason behind that is when you are releasing the object ,delegate method releted to that are  in progress .

OR

You can release the object after removing the view.

Body:
I get memory leak warning when I addsubView to Current ViewController....This is my code..

     NoOfGolferViewController *objNoOfGolferViewController = [[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil];
     [objNoOfGolferViewController setParent:self];
     [objNoOfGolferViewController.view setFrame:CGRectMake(15, 110, 290, 330)];
     [self.view addSubview:objNoOfGolferViewController.view];

and when I release object

      [objNoOfGolferViewController release];

Application get crashed by giving EXE_BAD_ACCESS message.

How can I solve this memory leak warning?

Thanks in advance..


问:
Java print items in tree map list
I currently have a TreeMap of the form <String, List<List<String>>

I'm trying to write my tree map to an output file where I get the inner values of my string[] all separated by a colon.

Do I need a second for loop to loop through each inner list and format it using a .join(":", elements)?

Or is there a more concise way to keep it all in a single for loop statement?

I've tried a few things and my current code is:

```<code>new File(outFolder).mkdir();
File dir = new File(outFolder);
//get the file we're writing to
File outFile = new File(dir, "javaoutput.txt");
//create a writer
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"))) {
  for (Map.Entry<String, String[]> entry : allResults.entrySet()) {
    writer.write(entry.getKey() + ", "+ Arrays.toString(entry.getValue()).replace("null", "").toString());
    writer.newLine();
  }
</code>```

Current output:

ANY, [[469, 470], [206, 1013, 1014], [2607, 2608]]

Desired output:

ANY, 469:470, 206:1013:1014, 2607:2608

Any suggestions would be greatly appreciated.

答:
String.join(":", arr) can be used to take the String array and return a colon-separated String.   This can then be used with Streams with a Collector to join these strings with a comma-separator, so :

```<code>TreeMap<String, String[]> allResults = new TreeMap<>();
allResults.put("a", new String[]{"469", "470"});
allResults.put("b", new String[]{"206", "1013", "1014"});
allResults.put("c", new String[]{"2607", "2608"});

String result = allResults.entrySet().stream()
                  .map(e -> String.join(":", e.getValue()))
                  .collect(Collectors.joining(", "));

System.out.println(result);
</code>```

produces :

```<code>469:470, 206:1013:1014, 2607:2608
</code>```

With a List<List<String>>, you need a stream within a stream, so :

```<code>    TreeMap<String, List<List<String>>> allResults = new TreeMap<>();
    allResults.put("a", Arrays.asList(Arrays.asList("469", "470"), Arrays.asList("206", "1013", "1014"), Arrays.asList("2607", "2608")));
    allResults.put("b", Arrays.asList(Arrays.asList("169", "470")));
    allResults.put("c", Arrays.asList(Arrays.asList("269", "470")));

    String result = allResults.entrySet().stream()
                      .map(i -> i.getKey() + "," + i.getValue().stream().map(elements -> String.join(":", elements))
                                      .collect(Collectors.joining(", "))
                                      )
                      .collect(Collectors.joining("\n"));

    System.out.println(result);
</code>```

which produces :

```<code>a,469:470, 206:1013:1014, 2607:2608
b,169:470
c,269:470
</code>```

Title: Java print items in tree map list

Body:
I currently have a TreeMap of the form <String, List<List<String>>

I'm trying to write my tree map to an output file where I get the inner values of my string[] all separated by a colon.

Do I need a second for loop to loop through each inner list and format it using a .join(":", elements)?

Or is there a more concise way to keep it all in a single for loop statement?

I've tried a few things and my current code is:

new File(outFolder).mkdir();
File dir = new File(outFolder);
//get the file we're writing to
File outFile = new File(dir, "javaoutput.txt");
//create a writer
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"))) {
  for (Map.Entry<String, String[]> entry : allResults.entrySet()) {
    writer.write(entry.getKey() + ", "+ Arrays.toString(entry.getValue()).replace("null", "").toString());
    writer.newLine();
  }

Current output:

ANY, [[469, 470], [206, 1013, 1014], [2607, 2608]]

Desired output:

ANY, 469:470, 206:1013:1014, 2607:2608

Any suggestions would be greatly appreciated.

Body:
String.join(":", arr) can be used to take the String array and return a colon-separated String.   This can then be used with Streams with a Collector to join these strings with a comma-separator, so :

TreeMap<String, String[]> allResults = new TreeMap<>();
allResults.put("a", new String[]{"469", "470"});
allResults.put("b", new String[]{"206", "1013", "1014"});
allResults.put("c", new String[]{"2607", "2608"});

String result = allResults.entrySet().stream()
                  .map(e -> String.join(":", e.getValue()))
                  .collect(Collectors.joining(", "));

System.out.println(result);

produces :

469:470, 206:1013:1014, 2607:2608

With a List<List<String>>, you need a stream within a stream, so :

    TreeMap<String, List<List<String>>> allResults = new TreeMap<>();
    allResults.put("a", Arrays.asList(Arrays.asList("469", "470"), Arrays.asList("206", "1013", "1014"), Arrays.asList("2607", "2608")));
    allResults.put("b", Arrays.asList(Arrays.asList("169", "470")));
    allResults.put("c", Arrays.asList(Arrays.asList("269", "470")));

    String result = allResults.entrySet().stream()
                      .map(i -> i.getKey() + "," + i.getValue().stream().map(elements -> String.join(":", elements))
                                      .collect(Collectors.joining(", "))
                                      )
                      .collect(Collectors.joining("\n"));

    System.out.println(result);

which produces :

a,469:470, 206:1013:1014, 2607:2608
b,169:470
c,269:470


问:
Model Derivative API - Conversion from dwg to obj
I have been trying to convert a dwg file into an obj file using the model derivative API following the viewer tutorial. It works fine with the input files and output formats provided in the tutorial; however, when using a dwg file as input and changing the output to obj, I get the following

error: Error at Model Derivative job.

Does anyone know why this is happening? Can the model derivative API convert dwg to obj?

Looking at the console, I can see the following line in the response: 'x-ads-troubleshooting': 'The system does not support this file format.',

答: Unfortunate DWG to OBJ is not a supported translation.</p>


问:
Surprising or wrong benchmarks of Where(predicate).FirstOrDefault() vs FirstOrDefault(predicate)?
I know this question has been asked a lot by people and some even say

So, first(FirstOrDefault(predicate)) one is better in terms of performance1

and I get it, I also think that one more method call should be slightly slower, its just intuition that I have. Nevertheless, I decided to run some benchmarks in order to prove my right and boy little did I know.

This is what I had as results of running my benchmarks:

```<code>BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-XMZTSC : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                            N      Mean         Error      StdDev    Ratio    RatioSD
WherePlusFirstOrDefaultArray    10000   31.44 us    0.288 us    0.270 us    0.40    0.00
FirstOrDefaultArray             10000   78.47 us    0.679 us    0.635 us    1.00    0.00
WherePlusFirstOrDefaultList     10000   54.27 us    1.070 us    1.099 us    0.69    0.02
FirstOrDefaultList              10000   100.84 us   1.722 us    1.611 us    1.29    0.02
WherePlusFirstOrDefaultArray    100000  325.41 us   4.840 us    4.527 us    0.39    0.01
FirstOrDefaultArray             100000  829.85 us   16.513 us   15.446 us   1.00    0.00
WherePlusFirstOrDefaultList     100000  558.10 us   5.507 us    5.151 us    0.67    0.01
FirstOrDefaultList              100000  1,026.93 us 17.648 us   16.508 us   1.24    0.02
WherePlusFirstOrDefaultArray    1000000 3,255.46 us 9.615 us    7.507 us    0.40    0.01
FirstOrDefaultArray             1000000 8,134.15 us 108.425 us  101.420 us  1.00    0.00
WherePlusFirstOrDefaultList     1000000 5,477.63 us 70.584 us   66.024 us   0.67    0.01
FirstOrDefaultList              1000000 9,987.54 us 64.239 us   60.089 us   1.23    0.02
</code>```

Not only Where(predicate).FirstOrDefault() was faster, but at what margin.

This is my benchmark code using BenchmarkDotNet

```<code>[SimpleJob(RuntimeMoniker.Net472)]
public class Benchmarks
{
    private int[] _array;
    private List<int> _list;

    [Params(10000, 100000, 1000000)]
    public int N;

    [GlobalSetup]
    public void Setup()
    {
        _array = new int[N];
        _list = new List<int>(N);

        _array = Enumerable
            .Repeat(0, N - 1).ToArray();
        _list = Enumerable
            .Repeat(0, N - 1).ToList();

        _array[N - 2] = 7;
        _list[N - 2] = 7;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultArray()
    {
        var seven = _array.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark(Baseline = true)]
    public int FirstOrDefaultArray()
    {
        var seven = _array.FirstOrDefault(n => n == 7);

        return seven;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultList()
    {
        var seven = _list.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark]
    public int FirstOrDefaultList()
    {
        var seven = _list.FirstOrDefault(n => n == 7);

        return seven;
    }
}
</code>```

Since I was stunned from the results leaving me with no other choice but to ask you guys what am I doing wrong or am I missing something?

EDIT:

I added benchmarks for array vs list structure to the guys thinking it might be because of the List.

EDIT2:
 The saga continues and I think I am closer to the answer. Adding hardware counter to my benchmark yielded following interesting results:

```<code>BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-ZTIMEH : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                             N     Mean        Error      StdDev     Ratio    RatioSD CacheMisses/Op  BranchMispredictions/Op
WherePlusFirstOrDefaultArray    1000000 3.222 ms    0.0224 ms   0.0210 ms    0.39     0.01      885                  327
FirstOrDefaultArray             1000000 8.166 ms    0.1992 ms   0.1863 ms   1.00      0.00     1,795                 810
WherePlusFirstOrDefaultList     1000000 5.564 ms    0.1066 ms   0.1228 ms   0.68      0.02     1,051                 503
FirstOrDefaultList              1000000 10.161 ms   0.1816 ms   0.1699 ms   1.24      0.03     3,451                1,442
</code>```

For some reason, I can't still explain to myself why FirstOrDefault(predicate) method is yielding 2 to 3 times more branch mispredictions and ofc cache misses than Where(predicate).FirstOrDefault(), surely this has to play a bit part in the results I am observing previously.

Also, one curious thing, if you look at FirstOrDefaultArray and FirstOrDefaultList results and compare them you will see that list is 24% slower, but assemblies generated by these methods are identical to me: https://www.diffchecker.com/WSjAQlet (I stripped memory addresses of the instructions.)

答:
The generic Enumerable.Where function maps to different subclasses based on the type of argument. In this case, your argument is a List<int> so you get returned from Where a Enumerable.WhereListIterator<int> that takes a List<int> parameter. It then uses List<T>.GetEnumerator() to enumerator the list, which returns a List<T>.Enumerator struct, which uses an index to index into the List<> and return each member. This is very fast.

FirstOrDefault(Func<> pred) doesn't have this optimization, and uses foreach to traverse the list. While this also ultimately uses the same very fast List<T>.Enumerator, it calls its member methods via the IEnumerable<T> interface, which is considerably slower than calling the List<T>.Enumerator methods directly.

My testing shows that the result is FirstOrDefault(Func<> pred) takes about twice as long per element of the source list. If you write your own FirstOrDefault<T>(List<T> src, Func<T,bool> pred) using either GetEnumerator or foreach, it will run about twice as fast as the built-in FirstOrDefault.

Body:
I know this question has been asked a lot by people and some even say

So, first(FirstOrDefault(predicate)) one is better in terms of performance1

and I get it, I also think that one more method call should be slightly slower, its just intuition that I have. Nevertheless, I decided to run some benchmarks in order to prove my right and boy little did I know.

This is what I had as results of running my benchmarks:

BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-XMZTSC : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                            N      Mean         Error      StdDev    Ratio    RatioSD
WherePlusFirstOrDefaultArray    10000   31.44 us    0.288 us    0.270 us    0.40    0.00
FirstOrDefaultArray             10000   78.47 us    0.679 us    0.635 us    1.00    0.00
WherePlusFirstOrDefaultList     10000   54.27 us    1.070 us    1.099 us    0.69    0.02
FirstOrDefaultList              10000   100.84 us   1.722 us    1.611 us    1.29    0.02
WherePlusFirstOrDefaultArray    100000  325.41 us   4.840 us    4.527 us    0.39    0.01
FirstOrDefaultArray             100000  829.85 us   16.513 us   15.446 us   1.00    0.00
WherePlusFirstOrDefaultList     100000  558.10 us   5.507 us    5.151 us    0.67    0.01
FirstOrDefaultList              100000  1,026.93 us 17.648 us   16.508 us   1.24    0.02
WherePlusFirstOrDefaultArray    1000000 3,255.46 us 9.615 us    7.507 us    0.40    0.01
FirstOrDefaultArray             1000000 8,134.15 us 108.425 us  101.420 us  1.00    0.00
WherePlusFirstOrDefaultList     1000000 5,477.63 us 70.584 us   66.024 us   0.67    0.01
FirstOrDefaultList              1000000 9,987.54 us 64.239 us   60.089 us   1.23    0.02

Not only Where(predicate).FirstOrDefault() was faster, but at what margin.

This is my benchmark code using BenchmarkDotNet

[SimpleJob(RuntimeMoniker.Net472)]
public class Benchmarks
{
    private int[] _array;
    private List<int> _list;

    [Params(10000, 100000, 1000000)]
    public int N;

    [GlobalSetup]
    public void Setup()
    {
        _array = new int[N];
        _list = new List<int>(N);

        _array = Enumerable
            .Repeat(0, N - 1).ToArray();
        _list = Enumerable
            .Repeat(0, N - 1).ToList();

        _array[N - 2] = 7;
        _list[N - 2] = 7;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultArray()
    {
        var seven = _array.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark(Baseline = true)]
    public int FirstOrDefaultArray()
    {
        var seven = _array.FirstOrDefault(n => n == 7);

        return seven;
    }

    [Benchmark]
    public int WherePlusFirstOrDefaultList()
    {
        var seven = _list.Where(n => n == 7).FirstOrDefault();

        return seven;
    }

    [Benchmark]
    public int FirstOrDefaultList()
    {
        var seven = _list.FirstOrDefault(n => n == 7);

        return seven;
    }
}

Since I was stunned from the results leaving me with no other choice but to ask you guys what am I doing wrong or am I missing something?

EDIT:

I added benchmarks for array vs list structure to the guys thinking it might be because of the List.

EDIT2:
 The saga continues and I think I am closer to the answer. Adding hardware counter to my benchmark yielded following interesting results:

BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363
Intel Core i7-3630QM CPU 2.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.101
  [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
  Job-ZTIMEH : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
Runtime=.NET 4.7.2

Method                             N     Mean        Error      StdDev     Ratio    RatioSD CacheMisses/Op  BranchMispredictions/Op
WherePlusFirstOrDefaultArray    1000000 3.222 ms    0.0224 ms   0.0210 ms    0.39     0.01      885                  327
FirstOrDefaultArray             1000000 8.166 ms    0.1992 ms   0.1863 ms   1.00      0.00     1,795                 810
WherePlusFirstOrDefaultList     1000000 5.564 ms    0.1066 ms   0.1228 ms   0.68      0.02     1,051                 503
FirstOrDefaultList              1000000 10.161 ms   0.1816 ms   0.1699 ms   1.24      0.03     3,451                1,442

For some reason, I can't still explain to myself why FirstOrDefault(predicate) method is yielding 2 to 3 times more branch mispredictions and ofc cache misses than Where(predicate).FirstOrDefault(), surely this has to play a bit part in the results I am observing previously.

Also, one curious thing, if you look at FirstOrDefaultArray and FirstOrDefaultList results and compare them you will see that list is 24% slower, but assemblies generated by these methods are identical to me: https://www.diffchecker.com/WSjAQlet (I stripped memory addresses of the instructions.)