问:
Cannot find class in classpath when trying to run TestNG from the main method
I run my Selenium Testng tests using Maven, but I am trying to create executable jars, so other team members can simply run an automation suite from their desktop with minimal setup.

So I have added a main "runner" method to create an executable jar.

```<code>public class LaunchTests {

public static void main(String[] args) {
    TestListenerAdapter tla = new TestListenerAdapter();
    TestNG testng = new TestNG();
    List<String> suites = new ArrayList();
    suites.add("testng.xml");//path to xml..
    testng.setTestSuites(suites);
    testng.run();

}
</code>```

}

My best guess is that something needs to be added to the POM.xml?

When running the testng tests manually from eclipse, or with mvn clean test (Surefire plugin), they run flawlessly. But I get this error when trying to run as a Java program.

```<code>    Exception in thread "main" org.testng.TestNGException:
Cannot find class in classpath: package.TestOne
    at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
    at org.testng.xml.XmlClass.init(XmlClass.java:73)
    at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
    at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:548)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at org.testng.xml.XMLParser.parse(XMLParser.java:38)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:16)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:9)
    at org.testng.xml.Parser.parse(Parser.java:172)
    at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:302)
    at org.testng.TestNG.run(TestNG.java:991)
    at util.LaunchTests.main(LaunchTests.java:17)
</code>```

Testng.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite1" parallel="methods" thread-count="1">

    <test name="Chrome Adviser Portal" allow-return-values="true"
        thread-count="1">
        <parameters>
            <parameter name="browser" value="chrome" />
            <parameter name="loginType" value="adviser" />
        </parameters>
        <classes>
            <class name="adviserPortal.AdviserLogin" />
        </classes>
    </test>
</suite>
</code>```

答:
Yes, you have to add extra plugins in pom.xml to create a runnable jar .

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>StackOverFlow</groupId>
    <artifactId>StackOverFlow</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.stack.JarCreation.Main</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>attached</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                            <archive>
                                <manifest>
                                    <mainClass>com.stack.JarCreation.Main</mainClass>
                                </manifest>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.13.6</version>
        </dependency>
    </dependencies>
</project>
</code>```

Go to your Project =>Right Click => Run As => Maven build... (which has 3 trailing dots) =>In Goals write clean install

It will create two jars in target folder.

The jar which has trailing jar-with-dependencies.jar is the runnable jar.

Place it where your chrome driver is and go to the location of jar and run it , it would work.

Body:
I run my Selenium Testng tests using Maven, but I am trying to create executable jars, so other team members can simply run an automation suite from their desktop with minimal setup.

So I have added a main "runner" method to create an executable jar.

public class LaunchTests {

public static void main(String[] args) {
    TestListenerAdapter tla = new TestListenerAdapter();
    TestNG testng = new TestNG();
    List<String> suites = new ArrayList();
    suites.add("testng.xml");//path to xml..
    testng.setTestSuites(suites);
    testng.run();

}

}

My best guess is that something needs to be added to the POM.xml?

When running the testng tests manually from eclipse, or with mvn clean test (Surefire plugin), they run flawlessly. But I get this error when trying to run as a Java program.

    Exception in thread "main" org.testng.TestNGException:
Cannot find class in classpath: package.TestOne
    at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
    at org.testng.xml.XmlClass.init(XmlClass.java:73)
    at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
    at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:548)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at org.testng.xml.XMLParser.parse(XMLParser.java:38)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:16)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:9)
    at org.testng.xml.Parser.parse(Parser.java:172)
    at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:302)
    at org.testng.TestNG.run(TestNG.java:991)
    at util.LaunchTests.main(LaunchTests.java:17)

Testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite1" parallel="methods" thread-count="1">

    <test name="Chrome Adviser Portal" allow-return-values="true"
        thread-count="1">
        <parameters>
            <parameter name="browser" value="chrome" />
            <parameter name="loginType" value="adviser" />
        </parameters>
        <classes>
            <class name="adviserPortal.AdviserLogin" />
        </classes>
    </test>
</suite>

Body:
Yes, you have to add extra plugins in pom.xml to create a runnable jar .

<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>StackOverFlow</groupId>
    <artifactId>StackOverFlow</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.stack.JarCreation.Main</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>attached</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                            <archive>
                                <manifest>
                                    <mainClass>com.stack.JarCreation.Main</mainClass>
                                </manifest>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.13.6</version>
        </dependency>
    </dependencies>
</project>

Go to your Project =>Right Click => Run As => Maven build... (which has 3 trailing dots) =>In Goals write clean install

It will create two jars in target folder.

The jar which has trailing jar-with-dependencies.jar is the runnable jar.

Place it where your chrome driver is and go to the location of jar and run it , it would work.


来源: stackexchange

问:
Do md5sum on files inside a directory and check if there are identical files
I'm studying shell script and there is an exercise asking to calculate the md5 hash of all files of a folder. It also asks to, in case there's two files with the same hash, print their names in the terminal. My code can do that, but once it finds a match, it's printed twice. I can't figure out how to exclude the first file name from the next iterations.
Another thing: It's forbidden to create any temporary files to help with the task.

```<code>#!/bin/bash

ifs=$IFS
IFS=$'\n'

echo "Verifying the files inside the directory..."

for file1 in $(find . -maxdepth 1 -type f | cut -d "/" -f2); do
  md51=$(md5sum $file1  | cut -d " " -f1)
  for file2 in $(find . -maxdepth 1 -type f | cut -d "/" -f2 | grep -v "$file1"); do
    md52=$(md5sum $file2 | cut -d " " -f1)
    if [ "$md51" == "$md52" ]; then
      echo "Files $file1 e $file2 are the same."
    fi
  done
done
</code>```

I also would like to know if there is a more efficient way to do this task.

答:
This

```<code>mapfile -t list < <(find . -maxdepth 1 -type f -exec md5sum {} + | sort)
mapfile -t dups < <(printf "%s\n" "${list[@]}" | grep -f <(printf "^%s\n" "${list[@]}" | sed 's/ .*//' | sort | uniq -d))

# here the array dups containing the all duplicates along with their md5sum
# you can print the array using a simple
printf "%s\n" "${dups[@]}"
</code>```

and will get output like:

```<code>3b0332e02daabf31651a5a0d81ba830a  ./f2.txt
3b0332e02daabf31651a5a0d81ba830a  ./fff
c9eb23b681c34412f6e6f3168e3990a4  ./both.txt
c9eb23b681c34412f6e6f3168e3990a4  ./f_out
d41d8cd98f00b204e9800998ecf8427e  ./aa
d41d8cd98f00b204e9800998ecf8427e  ./abc def.xxx
d41d8cd98f00b204e9800998ecf8427e  ./dudu
d41d8cd98f00b204e9800998ecf8427e  ./start
d41d8cd98f00b204e9800998ecf8427e  ./xx_yy
</code>```

The following addition is just for a fancier printout

```<code>echo "duplicates:"
while read md5; do
        echo "$md5"
        printf "%s\n" "${dups[@]}" | grep "$md5" | sed 's/[^ ]* /  /'
done < <(printf "%s\n" "${dups[@]}" | sed 's/ .*//' | sort -u)
</code>```

will print something like:

```<code>3b0332e02daabf31651a5a0d81ba830a
   ./f2.txt
   ./fff
c9eb23b681c34412f6e6f3168e3990a4
   ./both.txt
   ./f_out
d41d8cd98f00b204e9800998ecf8427e
   ./aa
   ./abc def.xxx
   ./dudu
   ./start
   ./xx_yy
</code>```

Warning: will work only if the filenames doesn't contains the \n (newline) character. Modifying the script be general needs bash 4.4+, where the mapfile knows the -d parameter.

ContentLicense: CC BY-SA 3.0

Body:
I'm studying shell script and there is an exercise asking to calculate the md5 hash of all files of a folder. It also asks to, in case there's two files with the same hash, print their names in the terminal. My code can do that, but once it finds a match, it's printed twice. I can't figure out how to exclude the first file name from the next iterations.
Another thing: It's forbidden to create any temporary files to help with the task.

#!/bin/bash

ifs=$IFS
IFS=$'\n'

echo "Verifying the files inside the directory..."

for file1 in $(find . -maxdepth 1 -type f | cut -d "/" -f2); do
  md51=$(md5sum $file1  | cut -d " " -f1)
  for file2 in $(find . -maxdepth 1 -type f | cut -d "/" -f2 | grep -v "$file1"); do
    md52=$(md5sum $file2 | cut -d " " -f1)
    if [ "$md51" == "$md52" ]; then
      echo "Files $file1 e $file2 are the same."
    fi
  done
done

I also would like to know if there is a more efficient way to do this task.

Body:
This

mapfile -t list < <(find . -maxdepth 1 -type f -exec md5sum {} + | sort)
mapfile -t dups < <(printf "%s\n" "${list[@]}" | grep -f <(printf "^%s\n" "${list[@]}" | sed 's/ .*//' | sort | uniq -d))

# here the array dups containing the all duplicates along with their md5sum
# you can print the array using a simple
printf "%s\n" "${dups[@]}"

and will get output like:

3b0332e02daabf31651a5a0d81ba830a  ./f2.txt
3b0332e02daabf31651a5a0d81ba830a  ./fff
c9eb23b681c34412f6e6f3168e3990a4  ./both.txt
c9eb23b681c34412f6e6f3168e3990a4  ./f_out
d41d8cd98f00b204e9800998ecf8427e  ./aa
d41d8cd98f00b204e9800998ecf8427e  ./abc def.xxx
d41d8cd98f00b204e9800998ecf8427e  ./dudu
d41d8cd98f00b204e9800998ecf8427e  ./start
d41d8cd98f00b204e9800998ecf8427e  ./xx_yy

The following addition is just for a fancier printout

echo "duplicates:"
while read md5; do
        echo "$md5"
        printf "%s\n" "${dups[@]}" | grep "$md5" | sed 's/[^ ]* /  /'
done < <(printf "%s\n" "${dups[@]}" | sed 's/ .*//' | sort -u)

will print something like:

3b0332e02daabf31651a5a0d81ba830a
   ./f2.txt
   ./fff
c9eb23b681c34412f6e6f3168e3990a4
   ./both.txt
   ./f_out
d41d8cd98f00b204e9800998ecf8427e
   ./aa
   ./abc def.xxx
   ./dudu
   ./start
   ./xx_yy

Warning: will work only if the filenames doesn't contains the \n (newline) character. Modifying the script be general needs bash 4.4+, where the mapfile knows the -d parameter.


问:
What to gitignore to protect my OS license (and computer)
I'm going to upload a project to github but I'm not sure that if some temporary files or binaries from visual studio, includes some important info about the OS and computer I use, which could(?) let people do hacking.

Which files should I consider ignoring or not uploading from my  project (has C++ and C# parts)?

I already have a github page:

https://github.com/tugrul512bit/Cekirdekler

and using Visual Studio 2015 community edition.

答:
You should use this .gitignore.

Remember that you can always edit it to fit your specific needs, but this should work for VS2015.


问:
"Impossible" NPE in a multi-threaded situation
I have some inherently asynchronous code in an Android app. I'm using RxJava2. The class Thing is not under my control (but ThingFactory is). In one method (createThing()), a new Thing is instantiated. Thing's constructor does some work and, when it is complete, notifies us via a callback onThingInitialized(). At the point that callback is called, we should be guaranteed that thing exists. In the callback, I schedule work to happen on a separate thread (in this case, using RxJava2, but I don't think it should matter). There is nowhere in this code that I call anything like thing = null. So, once it's set, it's set forever.

I threw a volatile onto it because the instance does get updated, but never nulled. If I'm mis-using it, please feel free to berate me.

```<code>public class UsesAThing implements ThingCallbacks {

    private volatile Thing thing; // I feel like I don't understand 'volatile'

    // I call this method
    public void createThing() {
        thing = thingFactory.newThing(param1, param2);
    }

    // Thing's constructor does some work and notifies us when it's done
    @Override
    public void onThingInitialized() {
        // Called on main thread, but I want to do some IO work, so:
        Schedulers.io().scheduleDirect(() -> {
            thing.doStuff(); // NPE!
        });
    }
}
</code>```

How is an NPE possible there?

EDIT:

Thing's constructor does its work asynchronously. As I said, this is in an Android environment, so the work it's actually doing is binding to a Service. When the Service is bound, its ServiceConnection::onServiceConnected() callback is hit, which itself actually fires up an AsyncTask which, in its onPostExecute() callback, calls the onThingInitialized() callback.

EDIT 2:

I should also note that this NPE doesn't happen all the time. I've run through this code hundreds of time, and I've only seen it occur once.

EDIT 3: Sample calling code

I didn't provide sample code because it's about as simple as one might imagine, but here's what it looks like:

```<code>Flowable.just(1)
    .subscribeOn(Schedulers.io())
    .subscribe(i -> createThing());
</code>```

答:
If I understand your comment, createThing() is called in a worker thread.  It's unlikely but possible that the thread scheduler will halt this worker thread after the Thing constructor initiates the sequence of events that leads to the callback, but before newThing() returns and thing is assigned.  If the whole callback sequence runs before the thread calling createThing() runs again, you will see this NPE.

To test this theory, first create a test that runs repeatedly to reproduce the issue.  Then change it so createThing() is called in the main thread and see if the problem goes away.  That would be a workaround, not a fix.  But a real fix would involve not doing work in Thing's constructor, which you stated is out of your control.

Body:
I have some inherently asynchronous code in an Android app. I'm using RxJava2. The class Thing is not under my control (but ThingFactory is). In one method (createThing()), a new Thing is instantiated. Thing's constructor does some work and, when it is complete, notifies us via a callback onThingInitialized(). At the point that callback is called, we should be guaranteed that thing exists. In the callback, I schedule work to happen on a separate thread (in this case, using RxJava2, but I don't think it should matter). There is nowhere in this code that I call anything like thing = null. So, once it's set, it's set forever.

I threw a volatile onto it because the instance does get updated, but never nulled. If I'm mis-using it, please feel free to berate me.

public class UsesAThing implements ThingCallbacks {

    private volatile Thing thing; // I feel like I don't understand 'volatile'

    // I call this method
    public void createThing() {
        thing = thingFactory.newThing(param1, param2);
    }

    // Thing's constructor does some work and notifies us when it's done
    @Override
    public void onThingInitialized() {
        // Called on main thread, but I want to do some IO work, so:
        Schedulers.io().scheduleDirect(() -> {
            thing.doStuff(); // NPE!
        });
    }
}

How is an NPE possible there?

EDIT:

Thing's constructor does its work asynchronously. As I said, this is in an Android environment, so the work it's actually doing is binding to a Service. When the Service is bound, its ServiceConnection::onServiceConnected() callback is hit, which itself actually fires up an AsyncTask which, in its onPostExecute() callback, calls the onThingInitialized() callback.

EDIT 2:

I should also note that this NPE doesn't happen all the time. I've run through this code hundreds of time, and I've only seen it occur once.

EDIT 3: Sample calling code

I didn't provide sample code because it's about as simple as one might imagine, but here's what it looks like:

Flowable.just(1)
    .subscribeOn(Schedulers.io())
    .subscribe(i -> createThing());


问:
Mocking not able to mock method call
I am trying to mock a call in my test but I am getting a error as its calling the real method than mocking it.

This is my method

```<code>@Value("${omega.aws.nonprod-profile}")
private String nonProdProfile;

@Autowired
AwsService awsService;

public List<SecurityGroup> getAllSecurityGroups() {
    AmazonEC2 ec2 = configSetter();
    return awsService.getAllSecurityGroups(ec2);
}

protected AmazonEC2 configSetter() {

    ProfileCredentialsProvider credentials = new ProfileCredentialsProvider(nonProdProfile);
    ClientConfiguration clientCfg = new ClientConfiguration();
    clientCfg.setProxyHost(this.proxyHost);
    clientCfg.setProxyPort(Integer.valueOf(proxyPort));
    clientCfg.setProtocol(Protocol.HTTPS);
    return new AmazonEC2Client(credentials, clientCfg);
</code>```

}

Here is my test class

```<code>@InjectMocks
    private AwsConfigurationLocal subject;

    @Mock
    private AwsService awsService;

    @Test
    public void TestgetAllSecurityGroups() throws Exception {

        ec2 = Mockito.mock(AmazonEC2Client.class);
        securityGroup = new SecurityGroup();
        List<SecurityGroup> result = Collections.singletonList(securityGroup);
        Mockito.when(awsService.getAllSecurityGroups(ec2)).thenReturn(result);
        List<SecurityGroup> actual = subject.getAllSecurityGroups();
        assertThat(actual, CoreMatchers.is(equals(result)));
    }
</code>```

The test actually calls the protected method configSetter and fails when setting a proxy. Help me understand what I am doing wrong here.

答:
subject.getAllSecurityGroups(); calls real configSetter() which returns real AmazonEC2 which in turn is passed on to awsService.getAllSecurityGroups(ec2);. The parameter doesn't match your mock ec2 so the default mock implementation is returned (I guess it's null) as a actual.

So the issue is: there is nothing that would prevent real implementation of configSetter() to be called.
If you annotate subject with @Spy and do

```<code>Mockito.when(subject.configSetter()).then(ec2);
</code>```

it should work as expected.

That being said there's a lot of set up done only to check simple invocation being delegated. This is due intermixing of two responsibility in AwsConfigurationLocal - creation of AmazonEC2Client and providing getAllSecurityGroups(). If you move the former into separate class (let's say AmazonEC2ClientFactor) everything should fall in place.

Title: Mocking not able to mock method call

Body:
I am trying to mock a call in my test but I am getting a error as its calling the real method than mocking it.

This is my method

@Value("${omega.aws.nonprod-profile}")
private String nonProdProfile;

@Autowired
AwsService awsService;

public List<SecurityGroup> getAllSecurityGroups() {
    AmazonEC2 ec2 = configSetter();
    return awsService.getAllSecurityGroups(ec2);
}

protected AmazonEC2 configSetter() {

    ProfileCredentialsProvider credentials = new ProfileCredentialsProvider(nonProdProfile);
    ClientConfiguration clientCfg = new ClientConfiguration();
    clientCfg.setProxyHost(this.proxyHost);
    clientCfg.setProxyPort(Integer.valueOf(proxyPort));
    clientCfg.setProtocol(Protocol.HTTPS);
    return new AmazonEC2Client(credentials, clientCfg);

}

Here is my test class

@InjectMocks
    private AwsConfigurationLocal subject;

    @Mock
    private AwsService awsService;

    @Test
    public void TestgetAllSecurityGroups() throws Exception {

        ec2 = Mockito.mock(AmazonEC2Client.class);
        securityGroup = new SecurityGroup();
        List<SecurityGroup> result = Collections.singletonList(securityGroup);
        Mockito.when(awsService.getAllSecurityGroups(ec2)).thenReturn(result);
        List<SecurityGroup> actual = subject.getAllSecurityGroups();
        assertThat(actual, CoreMatchers.is(equals(result)));
    }

The test actually calls the protected method configSetter and fails when setting a proxy. Help me understand what I am doing wrong here.

Body:
subject.getAllSecurityGroups(); calls real configSetter() which returns real AmazonEC2 which in turn is passed on to awsService.getAllSecurityGroups(ec2);. The parameter doesn't match your mock ec2 so the default mock implementation is returned (I guess it's null) as a actual.

So the issue is: there is nothing that would prevent real implementation of configSetter() to be called.
If you annotate subject with @Spy and do

Mockito.when(subject.configSetter()).then(ec2);

it should work as expected.

That being said there's a lot of set up done only to check simple invocation being delegated. This is due intermixing of two responsibility in AwsConfigurationLocal - creation of AmazonEC2Client and providing getAllSecurityGroups(). If you move the former into separate class (let's say AmazonEC2ClientFactor) everything should fall in place.


问:
Unable to make clickable link in Swift 3
I want to have a clickable uitextview hyperlink in iOS Swift 3. My Code:</p>

```<code>private func setUpTextViews() {
  let attributedString = NSMutableAttributedString(string: "http://www.vitensenteret.no")
  attributedString.addAttribute(NSLinkAttributeName, value: "http//:www.vitensenteret.no", range: NSRange(location: 0, length: 19))

  hyperLink.attributedText = attributedString
  hyperLink.dataDetectorTypes = UIDataDetectorTypes.all
  phoneNumber.dataDetectorTypes = UIDataDetectorTypes.all
}

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in     characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
  UIApplication.shared.open(URL, options: [:])
  return false
}
</code>```

答:
Is it because there is a typo in your link string?

```<code>"http//:www.vitensenteret.no"
</code>```

Note the location of the :.

Body:
I want to have a clickable uitextview hyperlink in iOS Swift 3. My Code:

private func setUpTextViews() {
  let attributedString = NSMutableAttributedString(string: "http://www.vitensenteret.no")
  attributedString.addAttribute(NSLinkAttributeName, value: "http//:www.vitensenteret.no", range: NSRange(location: 0, length: 19))

  hyperLink.attributedText = attributedString
  hyperLink.dataDetectorTypes = UIDataDetectorTypes.all
  phoneNumber.dataDetectorTypes = UIDataDetectorTypes.all
}

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in     characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
  UIApplication.shared.open(URL, options: [:])
  return false
}

Body:
Is it because there is a typo in your link string?

"http//:www.vitensenteret.no"

Note the location of the :.


问:
Check and uncheck checkbox and read its state
How can I read the state of my checkbox and set it's state to be visible ? I'm trying something like this, but it always returns true:</p>

```<code> $('.show-check').live('click', function(e) {
    e.preventDefault();

    var checked = ($(this).is(':checked'));
    if(checked == true){
       $(this).attr('checked', true);
    }
    else{
        $(this).attr('checked', false);
    }
 });

    <li>
        <img src="" class="show-image"/>
        <span class="show-title"></span>
        <input type="checkbox" class="show-check" />
    </li>
</code>```

答:
Maybe this would be clearer if you used the .change() event instead of the .clecked() event.

You are saying when the check box is clicked, if checked==true than set checked = true, so the false part will never be executed if you start with it checked.  The same is true if you start with it set to false.

ContentLicense: CC BY-SA 2.5

Body:
How can I read the state of my checkbox and set it's state to be visible ? I'm trying something like this, but it always returns true:

 $('.show-check').live('click', function(e) {
    e.preventDefault();

    var checked = ($(this).is(':checked'));
    if(checked == true){
       $(this).attr('checked', true);
    }
    else{
        $(this).attr('checked', false);
    }
 });

        <input type="checkbox" class="show-check" />


问:
How to select files from a grid using a checkbox to add to a zip to download
I have a directory viewer that generates rows based on the files present in the directory that are  displayed on the grid. I'm trying to add checkboxes that, when checked, will add the selected files to a zip archive. Currently my code is this

```<code><div id="directory-list-header">
            <div class="row">
                <div class="col-md-7 col-sm-6 col-xs-10">File</div>
                <div class="col-md-1 col-sm-2 col-xs-2 text-right">Size</div>
                <div class="col-md-2 col-sm-2 hidden-xs text-right">Last Modified</div>
                <div class="col-md-2 col-sm-2 col-xs-2 text-right">Select</div>
            </div>
        </div>

        <ul id="directory-listing" class="nav nav-pills nav-stacked">

            <?php foreach($dirArray as $name => $fileInfo): ?>
                <li data-name="<?php echo $name; ?>" data-href="<?php echo $fileInfo['url_path']; ?>">
                    <a href="<?php echo $fileInfo['url_path']; ?>" class="clearfix" data-name="<?php echo $name; ?>">

                        <div class="row">
                            <span class="file-name col-md-7 col-sm-6 col-xs-9">
                                <i class="fa <?php echo $fileInfo['icon_class']; ?> fa-fw"></i>
                                <?php echo $name; ?>
                            </span>

                            <span class="file-size col-md-1 col-sm-2 col-xs-3 text-right">
                                <?php echo $fileInfo['file_size']; ?>
                            </span>

                            <span class="file-modified col-md-2 col-sm-2 hidden-xs text-right">
                                <?php echo $fileInfo['mod_time']; ?>
                            </span>

                            <span class="selected col-md-2 col-sm-2 col-xs-1 text-right">
                                <form method="get">
                                    <input type="checkbox" name="selected[]" value="<?php echo $fileInfo['url_path']; ?>">
                                </form>
                            </span>
                        </div>
</code>```

I added the  tag and I was thinking that I should add any files that are checked to an array, then send that array to a zip using ZipArchive() and serving it to the client via a stream, however I'm not sure how the code would look for the checkbox logic since this is my first foray into HTML/PHP. Any help would be appreciated, I have the user interface squared away, it's just a matter of getting the background working

答: Create array[] from $_POST['files_names'] like here PHP access all $_POST[] variables into an array? and from that array create zip like here Download multiple files as a zip-file using php 6 answer.</p>

Body:
I have a directory viewer that generates rows based on the files present in the directory that are  displayed on the grid. I'm trying to add checkboxes that, when checked, will add the selected files to a zip archive. Currently my code is this

File

Size

Last Modified

Select

            <?php foreach($dirArray as $name => $fileInfo): ?>
                <li data-name="<?php echo $name; ?>" data-href="<?php echo $fileInfo['url_path']; ?>">
                    <a href="<?php echo $fileInfo['url_path']; ?>" class="clearfix" data-name="<?php echo $name; ?>">

                                <i class="fa <?php echo $fileInfo['icon_class']; ?> fa-fw">
                                <?php echo $name; ?>

                                <?php echo $fileInfo['file_size']; ?>

                                <?php echo $fileInfo['mod_time']; ?>

                                <form method="get">
                                    <input type="checkbox" name="selected[]" value="<?php echo $fileInfo['url_path']; ?>">
                                </form>

I added the  tag and I was thinking that I should add any files that are checked to an array, then send that array to a zip using ZipArchive() and serving it to the client via a stream, however I'm not sure how the code would look for the checkbox logic since this is my first foray into HTML/PHP. Any help would be appreciated, I have the user interface squared away, it's just a matter of getting the background working


问:
Microsoft Access query assistance
I have a database I use to track personnel for my job and often I have to import new rosters from 2 different sources. The two sources list the names differently.
1st table: Alpha
2nd Table: DRMD

The 1st table allows up to 32 characters such as: ASHLEYJOHNSON, DEVAUGHN GARY
The 2nd table only allows for 19 characters, such as: ASHLEYJOHNSON, DEVA

Is there a query I can run that will show me the names in table 1 (ALPHA) that are similar to the names in table 2 (DRMD)? Both tables have the names listed in the field (Name), i.e., [ALPHA].[NAME] and [DRMD].[NAME]

Can anyone assist?

答:
Seems like adding a WHERE statement of:

WHERE [DRMD].[NAME] = LEFT([ALPHA].[NAME], 19)

would work. Both tables in the query, no join commands.

Title: Microsoft Access query assistance


问:
DirectX 9 - Getting camera resolutions? (C++)
noob question:
Any examples of how to get parameters from the connected camera, such as supported resolutions?

I'm using DirectX June 2010.
Code to create a device:

```<code>HWND                    m_hwnd;
HDC                     *phdc;
IDirect3D9              *m_pD3D;
IDirect3DDevice9        *m_pDevice;
IDirect3DSwapChain9     *m_pSwapChain;

HRESULT DrawDevice::CreateDevice(HWND hwnd)
{
    if (m_pDevice)
    {
        return S_OK;
    }

    // Create the Direct3D object.
    if (m_pD3D == NULL)
    {
        m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

        if (m_pD3D == NULL)
        {
            return E_FAIL;
        }
    }

    HRESULT hr = S_OK;
    D3DPRESENT_PARAMETERS pp = { 0 };
    D3DDISPLAYMODE mode = { 0 };

    hr = m_pD3D->GetAdapterDisplayMode(
        D3DADAPTER_DEFAULT,
        &mode
    );

    if (FAILED(hr)) { return hr; }

    hr = m_pD3D->CheckDeviceType(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        mode.Format,
        D3DFMT_X8R8G8B8,
        TRUE    // windowed
    );

    if (FAILED(hr)) { return hr; }

    pp.BackBufferFormat = D3DFMT_X8R8G8B8;
    pp.SwapEffect = D3DSWAPEFFECT_COPY;
    pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    pp.Windowed = TRUE;
    pp.hDeviceWindow = hwnd;

    hr = m_pD3D->CreateDevice(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        hwnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
        &pp,
        &m_pDevice
    );

    if (FAILED(hr)) { return hr; }

    m_hwnd = hwnd;
    m_d3dpp = pp;

    return hr;
}
</code>```

My purpose is to give the user a list of options to choose...

Thanks !!

答:
Well if  you  need  Monitor  resolutions  you  should use  DXUT microsoft  Gui library or QT  or  custom you  should make enumeration  type and declare screen  resolutions.  I  don't know  what  kind of  resolutions you  prefer.  </p>

<p>P.S. I am not sure if you will  succeded  with DX SDK 2010 June and if you are  using  latest Windows and  Visual Studio IDE. Simply  that kind of DirectX SDK  doesn't  supported any more by  Microsoft. You should use  Windows  SDK  at least Windows 8.1 version.  Hope this helps. </p>

Body:
noob question:
Any examples of how to get parameters from the connected camera, such as supported resolutions?

I'm using DirectX June 2010.
Code to create a device:

HWND                    m_hwnd;
HDC                     *phdc;
IDirect3D9              *m_pD3D;
IDirect3DDevice9        *m_pDevice;
IDirect3DSwapChain9     *m_pSwapChain;

HRESULT DrawDevice::CreateDevice(HWND hwnd)
{
    if (m_pDevice)
    {
        return S_OK;
    }

    // Create the Direct3D object.
    if (m_pD3D == NULL)
    {
        m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

        if (m_pD3D == NULL)
        {
            return E_FAIL;
        }
    }

    HRESULT hr = S_OK;
    D3DPRESENT_PARAMETERS pp = { 0 };
    D3DDISPLAYMODE mode = { 0 };

    hr = m_pD3D->GetAdapterDisplayMode(
        D3DADAPTER_DEFAULT,
        &mode
    );

    if (FAILED(hr)) { return hr; }

    hr = m_pD3D->CheckDeviceType(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        mode.Format,
        D3DFMT_X8R8G8B8,
        TRUE    // windowed
    );

    if (FAILED(hr)) { return hr; }

    pp.BackBufferFormat = D3DFMT_X8R8G8B8;
    pp.SwapEffect = D3DSWAPEFFECT_COPY;
    pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    pp.Windowed = TRUE;
    pp.hDeviceWindow = hwnd;

    hr = m_pD3D->CreateDevice(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        hwnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
        &pp,
        &m_pDevice
    );

    if (FAILED(hr)) { return hr; }

    m_hwnd = hwnd;
    m_d3dpp = pp;

    return hr;
}

My purpose is to give the user a list of options to choose...

Thanks !!

Body:
Well if  you  need  Monitor  resolutions  you  should use  DXUT microsoft  Gui library or QT  or  custom you  should make enumeration  type and declare screen  resolutions.  I  don't know  what  kind of  resolutions you  prefer.

P.S. I am not sure if you will  succeded  with DX SDK 2010 June and if you are  using  latest Windows and  Visual Studio IDE. Simply  that kind of DirectX SDK  doesn't  supported any more by  Microsoft. You should use  Windows  SDK  at least Windows 8.1 version.  Hope this helps.


问:
Merge two Columns when specific Column starts with a Specific test
I need to change two columns in every line where "Color" column starts with a specific value "yell"

My table is:

```<code>+------+----------+----------+
| Name | Color    | Quantity |
+------+----------+----------+
| A    | <yell> U | 2        |
+------+----------+----------+
| B    | Blue     | 1        |
+------+----------+----------+
| C    | Red      | 4        |
+------+----------+----------+
| D    | <yell> A | 2        |
+------+----------+----------+
</code>```

For this, example table, I have 2 lines where column Collor starts with the string "Yell" . I need to change that field to Yellow and Put quantity = quantity-1, for the column "Quantity"

I need to match only the first 6 characters of the Collor string . What comes after this can be different from line to line.

So my table would be:

```<code>+------+--------+----------+
| Name | Color  | Quantity |
+------+--------+----------+
| A    | Yellow | 1        |
+------+--------+----------+
| B    | Blue   | 1        |
+------+--------+----------+
| C    | Red    | 4        |
+------+--------+----------+
| D    | Yellow | 1        |
+------+--------+----------+
</code>```

Can you help me? I've tried a merge but i'm not doing it right.

答:
this actually requires only a straight forward update, at least as directly specified. </p>

```<code>update tablename
  set color = 'Yellow';
    , quantity = quantity-1
where substr(color,1,6) = '<yell>' ;
</code>```

<p>However, you may need to adjust the string in the where clause. As is it will update a color value 'some other stuff here', but will NOT update the value 'yellow' nor '', nor other variations. </p>

Body:
I need to change two columns in every line where "Color" column starts with a specific value "yell"

My table is:

+------+----------+----------+
| Name | Color    | Quantity |
+------+----------+----------+
| A    | <yell> U | 2        |
+------+----------+----------+
| B    | Blue     | 1        |
+------+----------+----------+
| C    | Red      | 4        |
+------+----------+----------+
| D    | <yell> A | 2        |
+------+----------+----------+

For this, example table, I have 2 lines where column Collor starts with the string "Yell" . I need to change that field to Yellow and Put quantity = quantity-1, for the column "Quantity"

I need to match only the first 6 characters of the Collor string . What comes after this can be different from line to line.

So my table would be:

+------+--------+----------+
| Name | Color  | Quantity |
+------+--------+----------+
| A    | Yellow | 1        |
+------+--------+----------+
| B    | Blue   | 1        |
+------+--------+----------+
| C    | Red    | 4        |
+------+--------+----------+
| D    | Yellow | 1        |
+------+--------+----------+

Can you help me? I've tried a merge but i'm not doing it right.

Body:
this actually requires only a straight forward update, at least as directly specified.

update tablename
  set color = 'Yellow';
    , quantity = quantity-1
where substr(color,1,6) = '<yell>' ;

However, you may need to adjust the string in the where clause. As is it will update a color value 'some other stuff here', but will NOT update the value 'yellow' nor '', nor other variations.


问:
Yii2 field filter not showing on GridView with 3 tables related
I have used the gii tool to create crud application. I have 3 tables 'Empreendy' , 'Tramity', 'Protoprocess'.
The gridview is working perfectly, showing all the necessary data, however the search field 'nomeempreend' not appeared.

```<code>[Protoprocess table]

id (*)      |  int
============|=======
codprocesso |  char
============|=======
empreendy_id|  int
============|=======
dtabertura  |  date

[Tramity table]

id (*)         |  int
===============|=======
protoprocess_id|  int
===============|=======
datacad        |  date

[Empreendy Table]

id (*)       |  int
=============|=======
clientesy_id |  char
=============|=======
empreendy_id |  int
=============|=======
address      |  char
</code>```

Index fail

```<code> <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
       // 'protoprocess_id',
// #update here  < ####
     [
           'attribute' => 'empreendiment',
       'label'=>'Empreendimento',
       'value' => 'empreendyName.empreendy.nomeempreend',
           'filter'=>ArrayHelper::map(Empreendy::find()->asArray()->all(), 'id', 'nomeempreend'),
        ],
</code>```

// # end here  < ####

```<code>[
            'attribute' => 'protoprocess_id',
            'value'    => 'protoprocess.codprocesso',
        ],
</code>```

=======

```<code>class TramitySearch extends Tramity
{
/**
 * @inheritdoc
 */

public $empreendy_id;
public function rules()
{
    return [
        [['id'], 'integer'],
        [['obs', 'orgars_id', 'datacad', 'statusproto', 'protoprocess_id', 'empreendy_id', 'Dbusers_id'], 'safe'],
    ];
}

 public function search($params)
{
    $query = Tramity::find();

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }
$query->joinWith('orgars');
$query->joinWith('protoprocess');
$query->joinWith('empreendyName');
    // grid filtering conditions
    $query->andFilterWhere([
        'id' => $this->id,
     //   'protoprocess_id' => $this->protoprocess_id,
     //   'orgars_id' => $this->orgars_id,
        'datacad' => $this->datacad,
   'empreendyName.empreendy.nomeempreend' => $this->empreendy_id,

  //        'Dbusers_id' => $this->Dbusers_id,
    ]);

    $query->andFilterWhere(['like', 'obs', $this->obs])
        ->andFilterWhere(['like', 'statusproto', $this->statusproto])
        ->andFilterWhere(['like', 'codprocesso', $this->protoprocess_id])
        //    ->andFilterWhere(['like',  'nomeempreend', $this->empreendy_id])
          ->andFilterWhere(['like', 'sigla', $this->orgars_id]);
</code>```

====
 public $empreendiment;

====
     /**
     * @return \yii\db\ActiveQuery
     */
     public function getOrgars()
     {
        return $this->hasOne(Orgars::className(), ['id' => 'orgars_id']);
     }

```<code> /**
 * @return \yii\db\ActiveQuery
 */
  public function getProtoprocess()
{
    return $this->hasOne(Protoprocess::className(), ['id' => 'protoprocess_id'])->with(['empreendy']);
}

public function getDbusers()
{
    return $this->hasOne(Dbusers::className(), ['id' => 'Dbusers_id']);
}

public function getDeptoOrgars()
{
    return $this->hasMany(DeptoOrgars::className(), ['orgars_id' => 'id']);
}

public function getSeqTramity()
{
    return $this->hasMany(SeqTramity::className(), ['tramity_id' => 'id']);
}

public function getEmpreendyName()
{
return $this->hasOne(Protoprocess::className(), ['id' => 'protoprocess_id'])->with(['tramity']);
}
</code>```

=====

How to proceed for the input to be shown in the query by 'nomeempreend'?

答:
Only fields in rules() are searchable, thus:

On your TramitySearch class

```<code>public function rules()
{
    return [
        [['protoprocess.empreendy_id'], 'integer'],
        [['protoprocess_id'], 'integer'],
    ]
}
</code>```

Let me know if works for you, like works for me!

Body:
I have used the gii tool to create crud application. I have 3 tables 'Empreendy' , 'Tramity', 'Protoprocess'.
The gridview is working perfectly, showing all the necessary data, however the search field 'nomeempreend' not appeared.

[Protoprocess table]

id (*)      |  int
============|=======
codprocesso |  char
============|=======
empreendy_id|  int
============|=======
dtabertura  |  date

[Tramity table]

id (*)         |  int
===============|=======
protoprocess_id|  int
===============|=======
datacad        |  date

[Empreendy Table]

id (*)       |  int
=============|=======
clientesy_id |  char
=============|=======
empreendy_id |  int
=============|=======
address      |  char

Index fail

 <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
       // 'protoprocess_id',
// #update here  < ####
     [
           'attribute' => 'empreendiment',
       'label'=>'Empreendimento',
       'value' => 'empreendyName.empreendy.nomeempreend',
           'filter'=>ArrayHelper::map(Empreendy::find()->asArray()->all(), 'id', 'nomeempreend'),
        ],

// # end here  < ####

[
            'attribute' => 'protoprocess_id',
            'value'    => 'protoprocess.codprocesso',
        ],

=======

class TramitySearch extends Tramity
{
/**
 * @inheritdoc
 */

public $empreendy_id;
public function rules()
{
    return [
        [['id'], 'integer'],
        [['obs', 'orgars_id', 'datacad', 'statusproto', 'protoprocess_id', 'empreendy_id', 'Dbusers_id'], 'safe'],
    ];
}

 public function search($params)
{
    $query = Tramity::find();

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }
$query->joinWith('orgars');
$query->joinWith('protoprocess');
$query->joinWith('empreendyName');
    // grid filtering conditions
    $query->andFilterWhere([
        'id' => $this->id,
     //   'protoprocess_id' => $this->protoprocess_id,
     //   'orgars_id' => $this->orgars_id,
        'datacad' => $this->datacad,
   'empreendyName.empreendy.nomeempreend' => $this->empreendy_id,

  //        'Dbusers_id' => $this->Dbusers_id,
    ]);

    $query->andFilterWhere(['like', 'obs', $this->obs])
        ->andFilterWhere(['like', 'statusproto', $this->statusproto])
        ->andFilterWhere(['like', 'codprocesso', $this->protoprocess_id])
        //    ->andFilterWhere(['like',  'nomeempreend', $this->empreendy_id])
          ->andFilterWhere(['like', 'sigla', $this->orgars_id]);

====
 public $empreendiment;

====
     /**
     * @return \yii\db\ActiveQuery
     */
     public function getOrgars()
     {
        return $this->hasOne(Orgars::className(), ['id' => 'orgars_id']);
     }

 /**
 * @return \yii\db\ActiveQuery
 */
  public function getProtoprocess()
{
    return $this->hasOne(Protoprocess::className(), ['id' => 'protoprocess_id'])->with(['empreendy']);
}

public function getDbusers()
{
    return $this->hasOne(Dbusers::className(), ['id' => 'Dbusers_id']);
}

public function getDeptoOrgars()
{
    return $this->hasMany(DeptoOrgars::className(), ['orgars_id' => 'id']);
}

public function getSeqTramity()
{
    return $this->hasMany(SeqTramity::className(), ['tramity_id' => 'id']);
}

public function getEmpreendyName()
{
return $this->hasOne(Protoprocess::className(), ['id' => 'protoprocess_id'])->with(['tramity']);
}

=====

How to proceed for the input to be shown in the query by 'nomeempreend'?

Body:
Only fields in rules() are searchable, thus:

On your TramitySearch class

public function rules()
{
    return [
        [['protoprocess.empreendy_id'], 'integer'],
        [['protoprocess_id'], 'integer'],
    ]
}

Let me know if works for you, like works for me!


问:
if statement for codeigniter
I got a code that would display the date value from a database column based on it's id but the problem is..

When I'm trying to put a new data which sets the ID to null, I'm having an error because it can't fetch the data so I've tried using if statements.

here it is

```<code><input id="product_expirations" name="product_expirations" type="date" value="
<?php
if ($products){

}else
echo $products->product_expirations;?>"
class="form-control">
</code>```

I don't know what parameter to be put beside if $products.
please help me.
Thanks in advance

答:
you can just write single line if

```<code><input id="product_expirations" name="product_expirations" type="date" value="<?php echo (!empty($products)) ? $products->product_expirations; : '' ?>" class="form-control">
</code>```

Syntax for single line if

```<code>(condition) ? TRUE: FALSE
</code>```

Title: if statement for codeigniter

Body:
I got a code that would display the date value from a database column based on it's id but the problem is..

When I'm trying to put a new data which sets the ID to null, I'm having an error because it can't fetch the data so I've tried using if statements.

here it is

<input id="product_expirations" name="product_expirations" type="date" value="
<?php
if ($products){

}else
echo $products->product_expirations;?>"
class="form-control">

I don't know what parameter to be put beside if $products.
please help me.
Thanks in advance

Body:
you can just write single line if

<input id="product_expirations" name="product_expirations" type="date" value="<?php echo (!empty($products)) ? $products->product_expirations; : '' ?>" class="form-control">

Syntax for single line if

(condition) ? TRUE: FALSE


问:
Makefile generating error
Every time I enter the command on UNIX

```<code>unix1% make clean
</code>```

It returns an error message

```<code>mksh: Warning: newline is not last character in file makefile
Current working directory /home/s/m/mel
rm -f *.o core firstpass
unix1%
</code>```

Here is my makefile:

```<code>firstpass: main.o hashFunct.o symbolTable.o opcodeTable.o
        gcc main.o hashFunct.o symbolTable.o opcodeTable.o -o firstpass

main.o: main.c
        gcc -c main.c

hashFunct.o: hashFunct.c
        gcc -c hashFunct.c

symbolTable.o: symbolTable.c
        gcc -c symbolTable.c

opcodeTable.o: opcodeTable.c
        gcc -c opcodeTable.c

clean:
       rm -f *.o core firstpass
</code>```

I don't understand the problem, and I've tried to open it in emacs and see no mysterious characters. Also the word firstpass is the last character in the makefile. What does this error exactly mean?

答:
mksh: Warning: newline is not last character in file makefile

The problem is exactly what it said, it wants a newline as the last character of the file. Currently the last character is probably the s of firstpass.

Open it in an editor, go to the end of the file, hit return.

Some editors will add a final newline to files for you.

A newline at the end of a file should not be a requirement. This sort of warning is common in older systems whose parsers might freak out if they are given input without a newline. Perl 1 is the only time I've seen this in the wild, and that's from 1987, but C compilers still issue this warning.

Title: Makefile generating error

Body:
Every time I enter the command on UNIX

unix1% make clean

It returns an error message

mksh: Warning: newline is not last character in file makefile
Current working directory /home/s/m/mel
rm -f *.o core firstpass
unix1%

Here is my makefile:

firstpass: main.o hashFunct.o symbolTable.o opcodeTable.o
        gcc main.o hashFunct.o symbolTable.o opcodeTable.o -o firstpass

main.o: main.c
        gcc -c main.c

hashFunct.o: hashFunct.c
        gcc -c hashFunct.c

symbolTable.o: symbolTable.c
        gcc -c symbolTable.c

opcodeTable.o: opcodeTable.c
        gcc -c opcodeTable.c

clean:
       rm -f *.o core firstpass

I don't understand the problem, and I've tried to open it in emacs and see no mysterious characters. Also the word firstpass is the last character in the makefile. What does this error exactly mean?


问:
angular 2 validation on dynamic generated fields in loop
I have a list of input fields that are generated with a model. I am trying to add validation to them.
The requirement is they should not be empty or less than 2 characters.
problem is in the documentation only shows validation with non-dynamically generated variable Name. My fields are all generated dynamically. So there is no tempVariableName I can hardcode (otherwise they conflict), so I created temp variable from the name of the property I binded the field to. So I came up with something like this :

```<code>    <div *ngFor="let field of connector.configFields">
    <label>{{field.name}}</label>
    <input [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'"
           placeholder="{{field.name}} (required)"
           ngControl="[fieldName+field.name]"
           required minlength="2"
           #fieldName+[field.name]="ngModel" />
    <div *ngIf="(fieldName+[field.name]).errors && ((fieldName+[field.name]).dirty || (fieldName+[field.name]).touched)">
        <span *ngIf="(fieldName+[field.name]).errors.required">Enter Name</span>
        <span *ngIf="(fieldName+[field.name]).errors.minlength">Name minimum at 2 characters</span>
    </div>
</div>
</code>```

and the configFields in typescript look like this :

```<code>export class FieldModel {
public name: string;
public type: string;
public value: any;
</code>```

}

But this simply would not work. I am new to angular 2 so I am not exactly sure what I did wrong.

答:
You can use the unique index for each field in the array. Use this together with the name attribute (and ngModel) which will evaluate each form controls separately. So each input field gets the unique name, eg:

name="f{{i}}"
```

<p>where we get <code>{{i}}</code> from the iteration: </p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let field of connector.configFields; let i = index">
</code>```

So finally, your template could look like this:

<form #myForm="ngForm">

    <input name="f{{i}}" [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'" required #f="ngModel" minlength="2"/>

 This field is required

 Min 2 chars

</form>
```

Here's a live

Demo

Body:
I have a list of input fields that are generated with a model. I am trying to add validation to them.
The requirement is they should not be empty or less than 2 characters.
problem is in the documentation only shows validation with non-dynamically generated variable Name. My fields are all generated dynamically. So there is no tempVariableName I can hardcode (otherwise they conflict), so I created temp variable from the name of the property I binded the field to. So I came up with something like this :

    {{field.name}}
    <input [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'"
           placeholder="{{field.name}} (required)"
           ngControl="[fieldName+field.name]"
           required minlength="2"
           #fieldName+[field.name]="ngModel" />

        Enter Name
        Name minimum at 2 characters

and the configFields in typescript look like this :

export class FieldModel {
public name: string;
public type: string;
public value: any;

}

But this simply would not work. I am new to angular 2 so I am not exactly sure what I did wrong.

Body:
You can use the unique index for each field in the array. Use this together with the name attribute (and ngModel) which will evaluate each form controls separately. So each input field gets the unique name, eg:

name="f{{i}}"

where we get {{i}} from the iteration:

<div *ngFor="let field of connector.configFields; let i = index">

So finally, your template could look like this:

<form #myForm="ngForm">
  <div *ngFor="let field of connector.configFields; let i = index">
    <input name="f{{i}}" [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'" required #f="ngModel" minlength="2"/>
    <div *ngIf="f.errors && (f.dirty || f.touched)">
      <div *ngIf="f.errors.required"> This field is required </div>
      <div *ngIf="f.errors.minlength"> Min 2 chars </div>
    </div>
  </div>
</form>

Here's a live

Demo


问:
Application is not launching(AndroidRuntime: FATAL EXCEPTION: main)
please help me to figure out, the problem with a code. For the first place application was working as expected, but when the screen orientation changes from portrait to landscape application is destroying, that is why I decided to add 'onSaveInstanceState(Bundle outState)' and 'onRestoreInstanceState(Bundle savedInstanceState)', I am really new in Java, but I tried to solve it by myself for a four days and no actual results.

Here is my Java code and logcat after:

```<code>package com.example.android.dartscounter;

  import android.os.Bundle;
  import android.support.v7.app.AppCompatActivity;
  import android.view.View;
  import android.widget.NumberPicker;
  import android.widget.TextView;

  public class MainActivity extends AppCompatActivity {
  int scorePlayerOne = 0;
  int scorePlayerTwo = 0;
  NumberPicker noPicker;
  NumberPicker niPicker;
  int currentValue = 0;
  int currentValue2 = 0;
  static final String STATE_SCORE_ONE = "myInt";
  static final String STATE_SCORE_TWO = "myIntt";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  noPicker.setMinValue(0);
  noPicker.setMaxValue(20);
  noPicker.setWrapSelectorWheel(true);
  noPicker = (NumberPicker) findViewById(R.id.pickerOne);

  niPicker.setMinValue(0);
  niPicker.setMaxValue(20);
  niPicker.setWrapSelectorWheel(true);
  niPicker = (NumberPicker) findViewById(R.id.pickerTwo);

  }

  /**
  * Displays the given score for Player1.
  */
  public void displayForPlayerOne(int score) {
  TextView scoreView = (TextView) findViewById(R.id.playerOneScore);
  scoreView.setText(String.valueOf(score));

  }

  public void addToPlayerOne(View v) {
  currentValue = noPicker.getValue();
  scorePlayerOne = scorePlayerOne + currentValue;
  displayForPlayerOne(scorePlayerOne);

  }

  public void multiplyTwoPlayerOne(View v) {
  currentValue = noPicker.getValue();
  scorePlayerOne = scorePlayerOne + currentValue * 2;
  displayForPlayerOne(scorePlayerOne);
  }

  public void multiplyThreePlayerOne(View v) {
  currentValue = noPicker.getValue();
  scorePlayerOne = scorePlayerOne + currentValue * 3;
  displayForPlayerOne(scorePlayerOne);

  }

  /**
  * Displays the given score for Player2.
  */

  public void displayForPlayerTwo(int score) {
  TextView scoreView = (TextView) findViewById(R.id.playerTwoScore);
  scoreView.setText(String.valueOf(score));

  }

  public void addToPlayerTwo(View v) {
  currentValue2 = niPicker.getValue();
  scorePlayerTwo = scorePlayerTwo + currentValue2;
  displayForPlayerTwo(scorePlayerTwo);

  }

  public void multiplyTwoPlayerTwo(View v) {
  currentValue2 = niPicker.getValue();
  scorePlayerTwo = scorePlayerTwo + currentValue2 * 2;
  displayForPlayerTwo(scorePlayerTwo);
  }

  public void multiplyThreePlayerTwo(View v) {
  currentValue2 = niPicker.getValue();
  scorePlayerTwo = scorePlayerTwo + currentValue2 * 3;
  displayForPlayerTwo(scorePlayerTwo);

  }

  public void reset(View v) {
  scorePlayerOne = 0;
  scorePlayerTwo = 0;
  displayForPlayerTwo(scorePlayerTwo);
  displayForPlayerOne(scorePlayerOne);

  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
  setContentView(R.layout.activity_main);
  super.onSaveInstanceState(outState);

  outState.putInt(STATE_SCORE_ONE, scorePlayerOne);
  outState.putInt(STATE_SCORE_TWO, scorePlayerTwo);

  }

  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  setContentView(R.layout.activity_main);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  scorePlayerOne = savedInstanceState.getInt(STATE_SCORE_ONE);
  scorePlayerTwo = savedInstanceState.getInt(STATE_SCORE_TWO);
  }

  }
</code>```

xml:

```<code><?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#f5f5f5"
  android:orientation="vertical"
  android:theme="@android:style/Theme.Material"
  tools:context="com.example.android.dartscounter.MainActivity"
  tools:ignore="NewApi">

  <LinearLayout
  android:id="@+id/linearLayout"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">

  <LinearLayout
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_weight="0.5"
  android:orientation="vertical">

  <TextView
  android:id="@+id/player_1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:padding="16dp"
  android:text="Player 1"
  android:textColor="#616161"
  android:textSize="14sp" />

  <TextView
  android:id="@+id/playerOneScore"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="24dp"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:text="0"
  android:textColor="#000000"
  android:textSize="56sp" />

  <NumberPicker
  android:id="@+id/pickerOne"
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:clickable="true"
  android:descendantFocusability="blocksDescendants"
  android:scrollbarAlwaysDrawVerticalTrack="true"
  android:soundEffectsEnabled="true"
  android:theme="@style/Base.V22.Theme.AppCompat.Light" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="addToPlayerOne"
  android:text="add" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyTwoPlayerOne"
  android:text="x 2" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyThreePlayerOne"
  android:text="x 3" />
  </LinearLayout>

  <View
  android:layout_width="0.2dp"
  android:layout_height="match_parent"
  android:layout_marginTop="16dp"
  android:background="#212121"
  android:id="@+id/view_view"/>

  <LinearLayout
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_weight="0.5"
  android:orientation="vertical">

  <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:padding="16dp"
  android:text="Player 2"
  android:textColor="#616161"
  android:textSize="14sp"
  android:id="@+id/player_2"/>

  <TextView
  android:id="@+id/playerTwoScore"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="24dp"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:text="0"
  android:textColor="#000000"
  android:textSize="56sp" />

  <NumberPicker
  android:id="@+id/pickerTwo"
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:descendantFocusability="blocksDescendants"
  android:isScrollContainer="true"
  android:theme="@style/Base.V22.Theme.AppCompat.Light" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="addToPlayerTwo"
  android:text="add" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyTwoPlayerTwo"
  android:text="x 2" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyThreePlayerTwo"
  android:text="x 3" />
  </LinearLayout>

  </LinearLayout>

  <ImageButton
  android:id="@+id/imageButton"
  style="@android:style/Widget.ImageButton"
  android:layout_width="70dp"
  android:layout_height="70dp"
  android:layout_below="@+id/linearLayout"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="30dp"
  android:onClick="reset"
  android:scaleType="centerCrop"
  android:visibility="visible"
  app:srcCompat="@drawable/vector" />

  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@id/imageButton"
  android:layout_centerHorizontal="true"
  android:text="Reset"
  android:textColor="#424242" />

  </RelativeLayout>
</code>```

Error log:

```<code>                                                 --------- beginning of crash
03-23 20:55:23.365 2528-2528/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.android.dartscounter, PID: 2528
                                                 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.dartscounter/com.example.android.dartscounter.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.android.dartscounter.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.android.dartscounter-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.dartscounter-1/lib/x86, /vendor/lib, /system/lib]]
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:148)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                  Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.android.dartscounter.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.android.dartscounter-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.dartscounter-1/lib/x86, /vendor/lib, /system/lib]]
                                                     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:148)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                    Suppressed: java.lang.ClassNotFoundException: com.example.android.dartscounter.MainActivity
                                                     at java.lang.Class.classForName(Native Method)
                                                     at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                     at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                            ... 12 more
                                                  Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
03-23 20:55:29.709 2528-2528/com.example.android.dartscounter I/Process: Sending signal. PID: 2528 SIG: 9
</code>```

AndroidManifest:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.dartscounter" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
I actually found a way to save my activity state, and it works just as expected.

final working Java code provided below:

```<code>package com.example.android.dartscounter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.TextView;

import static android.R.string.no;

import static com.example.android.dartscounter.R.id.playerOneScore;
import static com.example.android.dartscounter.R.id.playerTwoScore;

public class MainActivity extends AppCompatActivity {
    int scorePlayerOne = 0;
    int scorePlayerTwo = 0;
    NumberPicker noPicker;
    NumberPicker niPicker;
    int currentValue = 0;
    int currentValue2 = 0;
    //key-pairs for saving
    private static final String STATE_SCORE_ONE = "myInt";
    private static final String STATE_SCORE_TWO = "myIntt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //below is the code for Number Pickers

        noPicker = (NumberPicker) findViewById(R.id.pickerOne);
        noPicker.setMaxValue(20);
        noPicker.setMinValue(0);
        noPicker.setWrapSelectorWheel(true);

        niPicker = (NumberPicker) findViewById(R.id.pickerTwo);
        niPicker.setMaxValue(20);
        niPicker.setMinValue(0);
        niPicker.setWrapSelectorWheel(true);

        // Check whether we're recreating a previously destroyed instance
        //restoring saved variables
        if (savedInstanceState != null) {
            // Restore value of members from saved state
            scorePlayerOne = savedInstanceState.getInt(STATE_SCORE_ONE);
            scorePlayerTwo = savedInstanceState.getInt(STATE_SCORE_TWO);
            //diplaying restored values
            displayForPlayerOne(scorePlayerOne);
            displayForPlayerTwo(scorePlayerTwo);

        }

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Save the user's current game state
        outState.putInt(STATE_SCORE_ONE, scorePlayerOne);
        outState.putInt(STATE_SCORE_TWO, scorePlayerTwo);
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(outState);
    }

    /**
     * Displays the given score for Player1.
     */
    public void displayForPlayerOne(int score) {
        TextView scoreView = (TextView) findViewById(playerOneScore);
        scoreView.setText(String.valueOf(score));

    }

    public void addToPlayerOne(View v) {
        currentValue = noPicker.getValue();
        scorePlayerOne = scorePlayerOne + currentValue;
        displayForPlayerOne(scorePlayerOne);

    }

    public void multiplyTwoPlayerOne(View v) {
        currentValue = noPicker.getValue();
        scorePlayerOne = scorePlayerOne + currentValue * 2;
        displayForPlayerOne(scorePlayerOne);
    }

    public void multiplyThreePlayerOne(View v) {
        currentValue = noPicker.getValue();
        scorePlayerOne = scorePlayerOne + currentValue * 3;
        displayForPlayerOne(scorePlayerOne);

    }

    /**
     * Displays the given score for Player2.
     */

    public void displayForPlayerTwo(int score) {
        TextView scoreView = (TextView) findViewById(playerTwoScore);
        scoreView.setText(String.valueOf(score));

    }

    public void addToPlayerTwo(View v) {
        currentValue2 = niPicker.getValue();
        scorePlayerTwo = scorePlayerTwo + currentValue2;
        displayForPlayerTwo(scorePlayerTwo);

    }

    public void multiplyTwoPlayerTwo(View v) {
        currentValue2 = niPicker.getValue();
        scorePlayerTwo = scorePlayerTwo + currentValue2 * 2;
        displayForPlayerTwo(scorePlayerTwo);
    }

    public void multiplyThreePlayerTwo(View v) {
        currentValue2 = niPicker.getValue();
        scorePlayerTwo = scorePlayerTwo + currentValue2 * 3;
        displayForPlayerTwo(scorePlayerTwo);

    }

    public void reset(View v) {
        scorePlayerOne = 0;
        scorePlayerTwo = 0;
        displayForPlayerTwo(scorePlayerTwo);
        displayForPlayerOne(scorePlayerOne);

    }

}
</code>```

Body:
please help me to figure out, the problem with a code. For the first place application was working as expected, but when the screen orientation changes from portrait to landscape application is destroying, that is why I decided to add 'onSaveInstanceState(Bundle outState)' and 'onRestoreInstanceState(Bundle savedInstanceState)', I am really new in Java, but I tried to solve it by myself for a four days and no actual results.

Here is my Java code and logcat after:

package com.example.android.dartscounter;

  import android.os.Bundle;
  import android.support.v7.app.AppCompatActivity;
  import android.view.View;
  import android.widget.NumberPicker;
  import android.widget.TextView;

  public class MainActivity extends AppCompatActivity {
  int scorePlayerOne = 0;
  int scorePlayerTwo = 0;
  NumberPicker noPicker;
  NumberPicker niPicker;
  int currentValue = 0;
  int currentValue2 = 0;
  static final String STATE_SCORE_ONE = "myInt";
  static final String STATE_SCORE_TWO = "myIntt";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  noPicker.setMinValue(0);
  noPicker.setMaxValue(20);
  noPicker.setWrapSelectorWheel(true);
  noPicker = (NumberPicker) findViewById(R.id.pickerOne);

  niPicker.setMinValue(0);
  niPicker.setMaxValue(20);
  niPicker.setWrapSelectorWheel(true);
  niPicker = (NumberPicker) findViewById(R.id.pickerTwo);

  }

  /**
  * Displays the given score for Player1.
  */
  public void displayForPlayerOne(int score) {
  TextView scoreView = (TextView) findViewById(R.id.playerOneScore);
  scoreView.setText(String.valueOf(score));

  }

  public void addToPlayerOne(View v) {
  currentValue = noPicker.getValue();
  scorePlayerOne = scorePlayerOne + currentValue;
  displayForPlayerOne(scorePlayerOne);

  }

  public void multiplyTwoPlayerOne(View v) {
  currentValue = noPicker.getValue();
  scorePlayerOne = scorePlayerOne + currentValue * 2;
  displayForPlayerOne(scorePlayerOne);
  }

  public void multiplyThreePlayerOne(View v) {
  currentValue = noPicker.getValue();
  scorePlayerOne = scorePlayerOne + currentValue * 3;
  displayForPlayerOne(scorePlayerOne);

  }

  /**
  * Displays the given score for Player2.
  */

  public void displayForPlayerTwo(int score) {
  TextView scoreView = (TextView) findViewById(R.id.playerTwoScore);
  scoreView.setText(String.valueOf(score));

  }

  public void addToPlayerTwo(View v) {
  currentValue2 = niPicker.getValue();
  scorePlayerTwo = scorePlayerTwo + currentValue2;
  displayForPlayerTwo(scorePlayerTwo);

  }

  public void multiplyTwoPlayerTwo(View v) {
  currentValue2 = niPicker.getValue();
  scorePlayerTwo = scorePlayerTwo + currentValue2 * 2;
  displayForPlayerTwo(scorePlayerTwo);
  }

  public void multiplyThreePlayerTwo(View v) {
  currentValue2 = niPicker.getValue();
  scorePlayerTwo = scorePlayerTwo + currentValue2 * 3;
  displayForPlayerTwo(scorePlayerTwo);

  }

  public void reset(View v) {
  scorePlayerOne = 0;
  scorePlayerTwo = 0;
  displayForPlayerTwo(scorePlayerTwo);
  displayForPlayerOne(scorePlayerOne);

  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
  setContentView(R.layout.activity_main);
  super.onSaveInstanceState(outState);

  outState.putInt(STATE_SCORE_ONE, scorePlayerOne);
  outState.putInt(STATE_SCORE_TWO, scorePlayerTwo);

  }

  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  setContentView(R.layout.activity_main);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  scorePlayerOne = savedInstanceState.getInt(STATE_SCORE_ONE);
  scorePlayerTwo = savedInstanceState.getInt(STATE_SCORE_TWO);
  }

  }

xml:

<?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#f5f5f5"
  android:orientation="vertical"
  android:theme="@android:style/Theme.Material"
  tools:context="com.example.android.dartscounter.MainActivity"
  tools:ignore="NewApi">

  <LinearLayout
  android:id="@+id/linearLayout"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">

  <LinearLayout
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_weight="0.5"
  android:orientation="vertical">

  <TextView
  android:id="@+id/player_1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:padding="16dp"
  android:text="Player 1"
  android:textColor="#616161"
  android:textSize="14sp" />

  <TextView
  android:id="@+id/playerOneScore"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="24dp"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:text="0"
  android:textColor="#000000"
  android:textSize="56sp" />

  <NumberPicker
  android:id="@+id/pickerOne"
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:clickable="true"
  android:descendantFocusability="blocksDescendants"
  android:scrollbarAlwaysDrawVerticalTrack="true"
  android:soundEffectsEnabled="true"
  android:theme="@style/Base.V22.Theme.AppCompat.Light" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="addToPlayerOne"
  android:text="add" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyTwoPlayerOne"
  android:text="x 2" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyThreePlayerOne"
  android:text="x 3" />
  </LinearLayout>

  <View
  android:layout_width="0.2dp"
  android:layout_height="match_parent"
  android:layout_marginTop="16dp"
  android:background="#212121"
  android:id="@+id/view_view"/>

  <LinearLayout
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_weight="0.5"
  android:orientation="vertical">

  <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:padding="16dp"
  android:text="Player 2"
  android:textColor="#616161"
  android:textSize="14sp"
  android:id="@+id/player_2"/>

  <TextView
  android:id="@+id/playerTwoScore"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="24dp"
  android:fontFamily="casual"
  android:gravity="center_horizontal"
  android:text="0"
  android:textColor="#000000"
  android:textSize="56sp" />

  <NumberPicker
  android:id="@+id/pickerTwo"
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:descendantFocusability="blocksDescendants"
  android:isScrollContainer="true"
  android:theme="@style/Base.V22.Theme.AppCompat.Light" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="addToPlayerTwo"
  android:text="add" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyTwoPlayerTwo"
  android:text="x 2" />

  <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginLeft="24dp"
  android:layout_marginRight="24dp"
  android:onClick="multiplyThreePlayerTwo"
  android:text="x 3" />
  </LinearLayout>

  </LinearLayout>

  <ImageButton
  android:id="@+id/imageButton"
  style="@android:style/Widget.ImageButton"
  android:layout_width="70dp"
  android:layout_height="70dp"
  android:layout_below="@+id/linearLayout"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="30dp"
  android:onClick="reset"
  android:scaleType="centerCrop"
  android:visibility="visible"
  app:srcCompat="@drawable/vector" />

  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@id/imageButton"
  android:layout_centerHorizontal="true"
  android:text="Reset"
  android:textColor="#424242" />

  </RelativeLayout>

Error log:

                                                 --------- beginning of crash
03-23 20:55:23.365 2528-2528/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.android.dartscounter, PID: 2528
                                                 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.dartscounter/com.example.android.dartscounter.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.android.dartscounter.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.android.dartscounter-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.dartscounter-1/lib/x86, /vendor/lib, /system/lib]]
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:148)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                  Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.android.dartscounter.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.android.dartscounter-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.dartscounter-1/lib/x86, /vendor/lib, /system/lib]]
                                                     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:148)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                    Suppressed: java.lang.ClassNotFoundException: com.example.android.dartscounter.MainActivity
                                                     at java.lang.Class.classForName(Native Method)
                                                     at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                     at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                            ... 12 more
                                                  Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
03-23 20:55:29.709 2528-2528/com.example.android.dartscounter I/Process: Sending signal. PID: 2528 SIG: 9

AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.dartscounter" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Body:
I actually found a way to save my activity state, and it works just as expected.

final working Java code provided below:

package com.example.android.dartscounter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.TextView;

import static android.R.string.no;

import static com.example.android.dartscounter.R.id.playerOneScore;
import static com.example.android.dartscounter.R.id.playerTwoScore;

public class MainActivity extends AppCompatActivity {
    int scorePlayerOne = 0;
    int scorePlayerTwo = 0;
    NumberPicker noPicker;
    NumberPicker niPicker;
    int currentValue = 0;
    int currentValue2 = 0;
    //key-pairs for saving
    private static final String STATE_SCORE_ONE = "myInt";
    private static final String STATE_SCORE_TWO = "myIntt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //below is the code for Number Pickers

        noPicker = (NumberPicker) findViewById(R.id.pickerOne);
        noPicker.setMaxValue(20);
        noPicker.setMinValue(0);
        noPicker.setWrapSelectorWheel(true);

        niPicker = (NumberPicker) findViewById(R.id.pickerTwo);
        niPicker.setMaxValue(20);
        niPicker.setMinValue(0);
        niPicker.setWrapSelectorWheel(true);

        // Check whether we're recreating a previously destroyed instance
        //restoring saved variables
        if (savedInstanceState != null) {
            // Restore value of members from saved state
            scorePlayerOne = savedInstanceState.getInt(STATE_SCORE_ONE);
            scorePlayerTwo = savedInstanceState.getInt(STATE_SCORE_TWO);
            //diplaying restored values
            displayForPlayerOne(scorePlayerOne);
            displayForPlayerTwo(scorePlayerTwo);

        }

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Save the user's current game state
        outState.putInt(STATE_SCORE_ONE, scorePlayerOne);
        outState.putInt(STATE_SCORE_TWO, scorePlayerTwo);
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(outState);
    }

    /**
     * Displays the given score for Player1.
     */
    public void displayForPlayerOne(int score) {
        TextView scoreView = (TextView) findViewById(playerOneScore);
        scoreView.setText(String.valueOf(score));

    }

    public void addToPlayerOne(View v) {
        currentValue = noPicker.getValue();
        scorePlayerOne = scorePlayerOne + currentValue;
        displayForPlayerOne(scorePlayerOne);

    }

    public void multiplyTwoPlayerOne(View v) {
        currentValue = noPicker.getValue();
        scorePlayerOne = scorePlayerOne + currentValue * 2;
        displayForPlayerOne(scorePlayerOne);
    }

    public void multiplyThreePlayerOne(View v) {
        currentValue = noPicker.getValue();
        scorePlayerOne = scorePlayerOne + currentValue * 3;
        displayForPlayerOne(scorePlayerOne);

    }

    /**
     * Displays the given score for Player2.
     */

    public void displayForPlayerTwo(int score) {
        TextView scoreView = (TextView) findViewById(playerTwoScore);
        scoreView.setText(String.valueOf(score));

    }

    public void addToPlayerTwo(View v) {
        currentValue2 = niPicker.getValue();
        scorePlayerTwo = scorePlayerTwo + currentValue2;
        displayForPlayerTwo(scorePlayerTwo);

    }

    public void multiplyTwoPlayerTwo(View v) {
        currentValue2 = niPicker.getValue();
        scorePlayerTwo = scorePlayerTwo + currentValue2 * 2;
        displayForPlayerTwo(scorePlayerTwo);
    }

    public void multiplyThreePlayerTwo(View v) {
        currentValue2 = niPicker.getValue();
        scorePlayerTwo = scorePlayerTwo + currentValue2 * 3;
        displayForPlayerTwo(scorePlayerTwo);

    }

    public void reset(View v) {
        scorePlayerOne = 0;
        scorePlayerTwo = 0;
        displayForPlayerTwo(scorePlayerTwo);
        displayForPlayerOne(scorePlayerOne);

    }

}