Search

Sunday, November 30, 2014

5 Ways to Determine if String has all Unique Characters : Java Code with Example

In the technical interviews ,you may come across this question many times ,determine whether a string has all unique characters or not . Before moving to the solution , here in this question   we have taken one assumption that is  all the characters in the string are ASCII characters.
For those who are not familiar with ASCII characters.

ASCII abbreviation is known as American Standard Code for  Information Interchange.
In simple words it is just the number representation of  characters.

So , First understand the question by writing examples :

Input : Alive is awesome 
Output : false

Input : Live present moment
Output : false 

Input : Alive swum
Output: true



PseudoCode for Method 1 :

1. Create a HashSet object.
2. Scan the whole string, and add each character one by one to the HashSet object
3. If the add object  returns true then continue
    else return false 



Method 1

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class uniquechar {

public static void main (String args[])
{
boolean result=false;
String inputstring="Alve i@wsom";
System.out.println(inputstring);
HashSet < Character> uniquecharset= new HashSet();
for(int i=0;i < inputstring.length();i++)
{
result=uniquecharset.add(inputstring.charAt(i));
if (result == false)
break;
}
System.out.println(result); }
}


PseudoCode for Method 2 :

1. Scan the input string , take each character one by one and set count flag to 0.
2. For each character in the inputstring ,Rescan the inputstring and compare the character with each character appear in the inputstring
3. If equal then increase the count by 1
                   else continue the loop
4.  If count flag value is greater than 1 then return false
                  else return true


Method 2

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class UniqueChar2 {

public static void main (String args[])
{
boolean result=false;
String inputstring="Alive is awesome";
System.out.println("String method 2 answer "+ method2(inputstring));
}

public static boolean method2(String input)
{
for(int i=0; i < input.length();i++)
{
char charcterofinputstring=input.charAt(i);
int count=0;
for(int j=i; j < input.length();j++)
{
if (charcterofinputstring==input.charAt(j))
count++;
}
if(count > 1)
return false;
}
return true;
}
}
 


PseudoCode for Method 3:

1. indexOf() returns the index of first occurence of the character or else return -1. So , here we are creating an arraylist object.
2. Scan the inputstring and add the index of each character to the arraylist object.
3. Sort the arraylist object.

unique characters in string java example
 
  4. Compare the values of  each adjacent positions of arraylist object
 if equal then return false
                  else continue scanning the arraylist

5.  return true
  




Method 3

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class UniqueChar3 {

public static void main (String args[])
{
boolean result=false;
String inputstring="Alive is awesome";
System.out.println("String method 3 answer "+ method3(inputstring));
}
public static boolean method3(String input)
{
ArrayList ar= new ArrayList();
for (int i=0; i < input.length() ; i++ )
{
int j = input.indexOf(input.charAt(i));
ar.add(j);
}
Collections.sort(ar);
for (int i=0;i < (ar.size()-1);i++)
{
if (ar.get(i) == ar.get(i+1))
return false;
}
return true;
}
}

 PseudoCode for Method 4 :

1.  For this method we need to know about  two inbuilt functions in java , indexOf() which returns the index of first occurence of the character in the string , while second function lastIndexOf() returns the index of last occurence of the character in the given string.
2. First , we convert the given inputstring into characterarray by using toCharArray() function.
3. Calculate the indexOf() and lastIndexOf() for each character in the given inputstring
4. If both are equal then continue and make result= true
        else set flag result = false
5. Return result


Method 4

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class UniqueChar4 {

public static void main (String args[])
{
boolean result=false;
String inputstring="Alive is awesome";
System.out.println("String method 4 answer "+ method4(inputstring));
}

public static boolean method4(String input)
{
boolean result=false;
for (char ch: input.toCharArray())
{
if(input.indexOf(ch)== input.lastIndexOf(ch))
result= true;
else
{
result=false;
break;
}
}
return result;
}
}
 
 


Method 5

Most memory efficient answer 

Please mention in the comments what is the time complexity of each of the above method and why ?
Also write in comments if you have any other method to find all the unique characters in string.

Difference between instance and Object in Java

In Java or other object oriented programming language, we often use Object and instance word interchangeably, but sometime it confuse beginners like hell. I have been often asked several times, whether object and instance is same thing or different? Why we sometime use object and sometime instance if they are same thing etc? This gives me idea to write a little bit about it. I will mostly talk on Java conventions perspective. Just like we use word function in C or C++  for a block of code, which can be called by its same, but in Java we refer them as methods. In Java functions are known as methods, similarly objects are known as instances in Java. You have a class, which represent a blueprint of a real world thing e.g. Car, and object represent a real world car e.g. your car, mine car, a red car or a blue car. They are also known as instances of car. One reason of calling instance may be because they are representation of that class at particular instant. In practice, use instance to say about one particular object, and use object to talk about many objects. By the way, it's also worth remembering that Java has class named Object, or java.lang.Object, which is the master class and every other class extend it. This is another reason why using instance is better because it will minimize confusion. So use Object when you want to talk about java.lang.Object and use instance when you want to talk about object of OOPS. Let's take a look more closely in next section.
Read more »

How To Enable/Disable @Test Method In Selenium WebDriver Using TestNG

TestNG has very good feature to enable or disable selenium webdriver @Test method. During test execution, If you do not wants to execute specific @Test method from test class then you can directly disable It using TestNG property enabled = false. It Is something like excluding @Test method from execution as described In THIS POST.

Let us try to Implement It practically. In bellow given test case, I have used @Test(priority=1,enabled = false) with method testCaseOne_Test_One(). Here, enabled = false property Is used for disabling that @Test method from execution.

Create bellow given test class and testng.xml file In your eclipse and run It.

1. Test_One.java
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Test_One {
WebDriver driver;
WebElement dragElementFrom;

@BeforeTest
public void setup() throws Exception {
System.out.println("In @BeforeTest Of Test_One.");
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}

@Test(priority=1,enabled = false)
public void testCaseOne_Test_One() {
System.out.println("Executing testCaseOne_Test_One.");
driver.findElement(By.xpath("//input[@id='2']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='6']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
String Result = driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value");
System.out.println("Result of testCaseOne_Test_One = "+Result);
}

@Test(priority=2)
public void testCaseTwo_Test_One() {
System.out.println("Executing testCaseTwo_Test_One.");
driver.findElement(By.xpath("//input[@id='Resultbox']")).clear();
driver.findElement(By.xpath("//input[@id='3']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='7']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
String Result = driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value");
System.out.println("Result of testCaseTwo_Test_One = "+Result);
}
}


testng.xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Parallel Class Suite" parallel="classes" thread-count="2">
<test name="Parallel Class Test" >
<classes>
<class name="Testing_Pack.Test_One"/>
</classes>
</test>
</suite>

Test execution result will looks like bellow. If you can see In bellow Image, only  testCaseTwo_Test_One() method has been executed because testCaseOne_Test_One() @Test method Is disabled so TestNG will exclude It from execution.


Thursday, November 27, 2014

How to create User Defined Exception class in Java

Java has very good support of handling Error and Exception, It has a well-defined Exception hierarchy and language level support to throw and catch Exception and deal with them. Java Programmers often deals with built-in exceptions from java.lang package and several others which are already defined in JDK API e.g. NullPointerException. If you have read Effective Java, you may remember advice of Joshua Bloch regrading Exception. According to him you should try to reuse the Exception classes provided in the JDK, e.g., IndexOutOfBoundException, ArithmeticException, IOException, and java.lang.ArrayIndexOutOfBoundsException , instead of creating new ones for similar purpose. But there are cases when a user defined, custom exception provides better opportunity to deal with special cases. So remember, you can always create you own Exception classes by extending from the class Exception or one of its sub classes. Also note that RuntimeException and its sub classes are not checked by the compiler and need not be declared in the method's signature. Therefore, use them with care, as you will not be informed and may not be aware of the exceptions that may occur by using that method (and therefore do not have the proper exception handling codes) – a bad software engineering practice. Once again, even Joshua Bloch has advised to use standard exception in Effective Java.

Read more »

Wednesday, November 26, 2014

TestNG With Selenium WebDriver Interview Questions And Answers

Part 15

68 : What Is the usage of testng.xml file?

Answer : In selenium WebDriver software testing tool, We are using testng.xml file to configure our whole test suite In single file. Few of the tasks which we can specify In testng.xml file are as bellow.

  • We can define software testing test suite using set of test cases to run them from single place.
  • Can Include or exclude test methods from software web application's test execution.
  • Can specify a group to Include or exclude.
  • Can pass parameter to use In test case of software web application.
  • Can specify group dependencies.
  • Can configure parallel test execution for software web application.
  • Can define listeners.
69 : How to pass parameter with testng.xml file to use It In test case?

Answer : We can define parameter In testng.xml file using syntax like bellow.
<parameter name="browser" value="FFX" />

Here, name attribute defines parameter name and value defines value of that parameter. Then we can use that parameter In selenium webdriver software automation test case using bellow given syntax.
@Parameters ({"browser"})

VIEW FULL EXAMPLE on how to define and use parameter from testng.xml file.

70 : I have a test case with two @Test methods. I wants to exclude one @Test method from execution. Can I do It? How?

Answer : Yes you need to specify @Test method exclusion In testng.xml file as bellow.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Exclusion Suite">
<test name="Exclusion Test" >
<classes>
<class name="Your Test Class Name">
<methods>
<exclude name="Your Test Method Name To Exclude"/>
</methods>
</class>
</classes>
</test>
</suite>

You need to provide @Test method name In exclude tag to exclude It from execution.

You can VIEW DETAILED EXAMPLE on how to exclude specific @Test method from execution.


71 : Tell me syntax to skip @Test method from execution.

Answer : You can use bellow given syntax Inside @Test method to skip It from test execution.
throw new SkipException("Test Check_Checkbox Is Skipped");

It will throw skip exception and @Test method will be sipped Immediately from execution. You can VIEW FULL EXAMPLE on how to skip @Test method from execution.

72 : Arrange bellow give testng.xml tags from parent to child.

<test>
<suite>
<class>
</methods>
</classes>

Answer : Parent to child arrangement for above testng tags Is as bellow.

<suite>
<test>
</classes>
<class>
</methods>

Tuesday, November 25, 2014

Use Of preserve-order In TestNG With Selenium WebDriver

preserve-order Is very Important attribute In TestNG. In Selenium WebDriver test execution, Many times peoples are complaining like my test cases execution not runs In correct sequence as given In testng.xml file but they are being executed In random sequence(unpredictable order). Actually they have copy pasted testng.xml file from somewhere with attribute preserve-order="fasle" but they don't know meaning of this attribute. Let me try to explain you meaning of this attribute.

  1. In testng.xml file, If you have not set preserve-order attribute with <test> node, By default It will be true. So your test class execution order will remain same as you have given In testng.xml file.
  2. Sameway, If you set attribute preserve-order="true" with <test> node, Your test execution will be same as given In testng.xml file.
  3. But If you set preserve-order="false", Your test cases will be executed In unpredictable order.
Let me give you examples with preserve-order="true" and preserve-order="false" attribute.

You can find more tutorial links on testng with webdriver at PAGE 1 and PAGE 2

Create three test cases as bellow under package Testing_Pack.

1. Test_One.java
package Testing_Pack;

import org.testng.annotations.Test;

public class Test_One {
@Test
public void testCaseOne_ClassOne() {
System.out.println("Executing testCaseOne_ClassOne Of ClassOne");
}
}

2. Test_Two.java
package Testing_Pack;

import org.testng.annotations.Test;

public class Test_Two {
@Test
public void testCaseOne_ClassTwo() {
System.out.println("Executing testCaseOne_ClassTwo Of ClassTwo");
}
}

3. Test_Three.java
package Testing_Pack;

import org.testng.annotations.Test;

public class Test_Three {

@Test
public void testCaseOne_ClassThree() {
System.out.println("Executing testCaseOne_ClassThree Of ClassThree");
}
}

Create bellow given testng.xml file under your project to run all above test cases.

testng.xml (with preserve-order="false")
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="preserve-order Suite">
<test name="preserve-order Test" preserve-order="false">
<classes>
<class name="Testing_Pack.Test_One"/>
<class name="Testing_Pack.Test_Two"/>
<class name="Testing_Pack.Test_Three"/>
</classes>
</test>
</suite>

If you will run above given testng.xml file, test classes execution order will looks like bellow. You can see that test execution sequence Is not same as given In testng.xml file.


Now let us use preserve-order="true" attribute In testng.xml file as bellow and observe execution result.

testng.xml (with preserve-order="true")
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="preserve-order Suite">
<test name="preserve-order Test" preserve-order="true">
<classes>
<class name="Testing_Pack.Test_One"/>
<class name="Testing_Pack.Test_Two"/>
<class name="Testing_Pack.Test_Three"/>
</classes>
</test>
</suite>

Now run above testng.xml file and observe test classes execution order. It will be same as given In testng.xml file as shown In bellow given Image.


So this Is the example of using preserve-order attribute In testng.xml file. To execute test cases In correct order, you need to set preserve-order=true and to execute them In unpredictable order, set preserve-order=false.

Java 8 Comparator Example Using Lambda Expressions

What is the best way to learn lambda expression of Java 8? Of course by using it on your day to day programming task. Since implementing equals, hashcode, compareTo, and compare methods are some of the most common task of a Java developer, it make sense to learn how to use lambda expression to implement custom Comparator and Comparable in Java. One question comes in mind, can we use lambda expression with Comparator, because it's an old interface and may not implement functional interface annotated with @FunctionalInterface annotation? Answer to this question is Yes, you can use lambda expression to implement Comparator and Comparable interface in Java, and not just these two but to implement any interface, which just got one abstract method, remember from Java 8 interface can have non abstract methods as well e.g. default and static methods. That's why lambda expression in Java 8 is known as SAM type, where SAM stands for Single Abstract Method. This was a very important decision Java designers made, which makes it lambdas even more useful. Due to this you can use lambda expressions with Runnable, ActionListener and several other interface which got just one abstract method. By the way, you need not to worry in case of Comparator, because it is made to implement @FunctionalInterface as shown below :
Read more »

Sunday, November 23, 2014

Selenium WebDriver with TestNG Interview Questions With Answers

Part 14

63 : What Is TestNG?

Answer : TestNG Is Open Source(Freeware) framework which Is Inspired from NUnit and JUnit with Introducing few new features and functionality compared to NUnit and JUnit to make It easy to use and more powerful.

We can use TestNg with selenium webdriver software testing tool to configure and run test cases very easily, easy to understand, read and manage test cases, and to generate HTML or XSLT test reports.

You will find Selenium WebDriver with TestNG practical example Links on PAGE 1 and PAGE 2.

64 : Can you describe major features of TestNG?

Answer : TestNG has many major features like support of @DataProvider annotation to perform data driven testing on software web application, can set test case execution dependency, test case grouping, generate HTML and XSLT test execution report for software web application etc.. VIEW MORE FEATURES with detailed description.

65 : Describe the similarities and difference between JUnit and TestNG unit testing frameworks.

Answer : You can find all the similarities and difference between JUnit and TestNG framework on THIS PAGE.

66 : How to Install TestNG In Eclipse? How do you verify that TestNg Is Installed properly In Eclipse?

Answer : To Install TestNG software unit testing framework In Eclipse, We have to follow steps as described on THIS PAGE.


67 : What are different annotations supported by TestNG ?

Answer : TestNG supports many different annotations to configure Selenium WebDriver software automation test. You can see mostly used annotations list with detailed description and practical example link on THIS PAGE.

How to test if an Array contains a value in Java - Linear Search

One of the common coding question from Java interviews is how to test if an Array contains a certain value or not? This is simple question but some time interview pressure makes candidates nervous. Since array in Java doesn't have any inbuilt method for search, interviewer prefer to ask this question, to see how candidate deal with such situation. If you have good knowledge of Java API then you will immediately come to know that there are alternatives available e.g. binary search of Arrays class or taking advantage of ArrayList contains method by first converting your array to ArrayList. If you come up with those solution, Interviewer will surely ask you to write down a method to search an element in array without using any library method. You can easily solve this question if you know linear search or binary search algorithm. Linear search is very simple to implement, all you need to do is loop over array and check each value if that is the one or not. Binary search is little tricky but not too difficult either, recursive version is very natural as well. In this tutorial, though I have given two solution, one is using ArrayList, and second is using linear search, leaving binary search an exercise for you. But you must remember to sort array before using binary search. By the way to make question more challenging, I usually asked candidate to write a parametric method using generic so that it will work for any type of object array in Java.
Read more »

Thursday, November 20, 2014

How to Convert a Double to Long in Java - Example Tutorial

We often need to convert a floating point number into integral number e.g. a double or float value 234.50d to long value 234L or 235L. There are couple of ways to convert a double value to long value in Java e.g. you can simply cast a double value to long or you can wrap a double value into Double object and call it's longValue() method, or using Math.round() method to round floating point value into nearest integer. Te right way to covert a double value to a long in Java really depends upon what you want to do with floating point value. If you just want to truncate the double value to remove zero and take integer value, you can simply cast double to long. If you have Double object instead of double primitive type then you can also Double.longValue() method, this doesn't do anything but just cast the double primitive wrapped inside Double object to long. It's clear from following code snippet taken from java.lang.Double class

 public long longValue() {
return (long)value;
}

On the other hand if you want to round the double value to nearest long, you can use Math.round() method, this will return a long value rounded up to nearest position, for example if double value is 100.5 then it will rounded to 101, while if it is less than that e.g. 100.1 then it will be rounded to just 100. In next section we will see detailed examples of these 3 ways to convert double to long in Java.

Read more »

Wednesday, November 19, 2014

Using Single @DataProvider Method To Store All WebDriver Test Case Data

We have learnt how to create and store multiple @DataProvider methods In single class file called dataProvider_Repository.java and then we can use those data In different test case execution as described In THIS PAGE. Using this, We can manage data of all test cases very easily In single file and If you wants to modify test data of any test case, You have to modify only single file.

Now, Instead of creating separate @DataProvider method for each test case, Is It possible to store all test cases data In single @DataProvider method? Yes we can do It by passing method name In @DataProvider method as shown In bellow example.

Create bellow given class files under TestNG_Advanced package.

LogInCase.java
package TestNG_Advanced;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class LogInCase {
private static WebDriver driver;

@BeforeTest
public void setUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}

//This LogIn method will access data from dataProvider_Repository class file where dataProvider name Is BothData.
@Test(dataProviderClass=dataProvider_Repository.class,dataProvider="BothData")
public static void LogIn(String UID, String PASS) {
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys(UID);
driver.findElement(By.xpath("//input[@name='pswrd']")).sendKeys(PASS);;
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.switchTo().alert().accept();
}
}

FormSubmit.java
package TestNG_Advanced;

import java.util.concurrent.TimeUnit;

public class FormSubmit {
private static WebDriver driver;

@BeforeTest
public void setUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}

//This Submit method will access data from dataProvider_Repository class file where dataProvider name Is BothData.
@Test(dataProviderClass=dataProvider_Repository.class,dataProvider="BothData")
public static void Submit(String fname, String lname,
String email, String mobile,
String company) {

driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys(fname);
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys(lname);
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys(email);
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys(mobile);
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys(company);
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.switchTo().alert().accept();
}
}

dataProvider_Repository.java
package TestNG_Advanced;

import java.lang.reflect.Method;

import org.testng.annotations.DataProvider;

public class dataProvider_Repository {

//Pass Method name In BothCaseData method.
@DataProvider(name="BothData")
public static Object[][] BothCaseData(Method mtd){

Object detail[][] = null;

//If method name = LogIn, Use this data.
if(mtd.getName().equalsIgnoreCase("LogIn")){

detail = new Object[3][2];
detail[0][0]="UserName1";
detail[0][1]="Password1";

detail[1][0]="UserName2";
detail[1][1]="Password2";

detail[2][0]="UserName3";
detail[2][1]="Password3";
}
//If method name = Submit, Use this data.
else if(mtd.getName().equalsIgnoreCase("Submit")){

detail = new Object[3][5];
detail[0][0]="fName1";
detail[0][1]="lname1";
detail[0][2]="email1@youraccount.com";
detail[0][3]="mobno1";
detail[0][4]="company1";

detail[1][0]="fName2";
detail[1][1]="lname2";
detail[1][2]="email2@youraccount.com";
detail[1][3]="mobno2";
detail[1][4]="company2";

detail[2][0]="fName3";
detail[2][1]="lname3";
detail[2][2]="email3@youraccount.com";
detail[2][3]="mobno3";
detail[2][4]="company3";
}

return detail;
}
}

Test cases and test data are same as described In PREVIOUS EXAMPLE. But way of storing test data and accessing them In test cases Is different, Previously we have created separate @DataProvider method for both test cases. But now we have created single @DataProvider method to store data of both test cases. If else condition will check test method's name and based on that test data will be provided.

Now you can run both test cases one by one to see results.

Tuesday, November 18, 2014

Modulo or Remainder Operator in Java

Modulo Operator is one of the fundamental operator in Java. It's a binary operator i.e. it require two operands. In a division operation the remainder is returned by using modulo operator. It is denoted by % (percentage) sign. For example 5%2 will return 1 because if you divide 5 with 2, remainder will be 1. For a programmer it's very important to know how to use this operator, they are very important to build logic. For example, in many cases like reversing a number or checking if a number is palindrome, you can use modulus operator with 10 to get the last digit, for example 101%10 will return 1 or 1234%10 will return 4, the last digit. It is one of the rather less used arithmetic operator in comparison of +, -, * and /. One of the important point about the remainder operator which is not know by many Java programmer is that it can also be used with floating point numbers. It's surprising because you don't normally think of real number division as producing remainders. However there are some times when it's useful to ask exactly how many times does 2.5 go into 7.5 and what's left over? The answer is that 2.5 goes into 7.5 three times with zero left over, and it's that zero which is the result of 7.5 % 2.5 in Java. Another good use of modulus operator is to check if a number is even or odd. In case of even number, number%2 will return 0, while if a number is odd then number%2 will return 1.
Read more »

Monday, November 17, 2014

JUnit With Selenium WebDriver Interview Questions And Answers

Part 13

58 : Tell me main features of JUnit.

Answer : JUnit features are as bellow.
  • JUnit Is unit software testing framework. So It helps software developers to create and run unit test cases very easily.
  • There are many different annotations available In JUnit. Using all those annotations, we can Identify and configure webdriver software test case very easily.
  • JUnit supports many different assertions using which we can compare webdriver software automation test's expected and actual result.
  • We can create test suite for multiple test cases to run all of them In one go using JUnit.
  • We can generate webdriver test execution HTML reports using JUnit. VIEW EXAMPLE.
59 : What are different assertions supported by JUnit?

Answer : List of JUnit assertions as bellow.
  1. assertEquals
  2. assertFalse
  3. assertTrue
  4. assertNull
  5. assertNotNull
  6. assertSame
  7. assertNotSame
  8. assertArrayEquals
60 : How to create and run JUnit test suite for selenium WebDriver? 

Answer : For creating JUnit software test suite, we have to create test cases class files and one separate test suite file. Then we can write syntax like bellow In test suite file to run test suite.
@RunWith(Suite.class)
@SuiteClasses({ junittest1.class, junittest2.class })
public class junittestsuite {

}

In above example, junittest1.class and junittest2.class are test case class names.
VIEW PRACTICAL EXAMPLE on how to create and run JUnit test suite with selenium WebDriver.


61 : For what purpose, assertTrue and assertFalse assertions are used?

Answer : In selenium webdriver software test automation, We need to assert Boolean conditions true and false. We can assert both these conditions using assertTrue and assertFalse JUnit assertions.


62 : Can you give me example of JUnit assertEquals assertion?

Answer : Example of JUnit assertEquals assertion Is as bellow. It assert that values of actTotal and expTotal are equal or not.

public void sumExample() {
int val1 = 10;
int val2 = 20;
int expTotal = 35;
int actTotal = 0;
actTotal = val1 + val2;
assertEquals(actTotal, expTotal);
}

Sunday, November 16, 2014

Store And Access All DataProviders From Single File For WebDriver Test Cases

We have already learnt how to create and use testng data providers In selenium webdriver test cases In THIS POST. Also we have used testng data providers In Selenium WebDriver Data Driven Framework creation so all you are now very familiar with testng data providers and how to use them In our automation test case creation.

Now supposing you have multiple test cases and each test case has Its own data provider method to store required data for that test case. There Is not any Issue to use data providers In this manner but It Is not good manner. It Is very hard to manage data In this way because If you wants to modify data of few test cases then you have to open all those test cases files one by one and then you can modify them.

Best way to manage and access test data of all test cases very easily Is : Store all data provider method In single file. So whenever you wants to modify test data of one or multiple test cases, You need to open only single file.

I have created simple example to store test data of two different test cases In single file. First test Is LogIn test(LogInCase.java) and second test Is form submission test(FormSubmit.java). Both test cases need different test data to execute test case and I have created separate file (dataProvider_Repository.java) to store data provider methods of both test cases as bellow.

Create bellow give three class file under TestNG_Advanced package In eclipse.

LogInCase.java
package TestNG_Advanced;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class LogInCase {
private static WebDriver driver;

@BeforeTest
public void setUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}

//This LogIn method will access data from dataProvider_Repository.java class file where dataProvider name Is LogInData.
@Test(dataProviderClass=dataProvider_Repository.class,dataProvider="LogInData")
public static void LogIn(String UID, String PASS) {
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys(UID);
driver.findElement(By.xpath("//input[@name='pswrd']")).sendKeys(PASS);;
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.switchTo().alert().accept();
}
}

FormSubmit.java
package TestNG_Advanced;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FormSubmit {
private static WebDriver driver;

@BeforeTest
public void setUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}

//This Submit method will access data from dataProvider_Repository.java class file where dataProvider name Is FormData.
@Test(dataProviderClass=dataProvider_Repository.class,dataProvider="FormData")
public static void Submit(String fname, String lname,
String email, String mobile,
String company) {

driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys(fname);
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys(lname);
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys(email);
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys(mobile);
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys(company);
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.switchTo().alert().accept();
}
}

dataProvider_Repository.java
package TestNG_Advanced;

import org.testng.annotations.DataProvider;

public class dataProvider_Repository {

//Test data to use In LogInCase.java file.
@DataProvider(name="LogInData")
public static Object[][] LogInCaseData(){

Object detail[][] = new Object[3][2];
detail[0][0]="UserName1";
detail[0][1]="Password1";

detail[1][0]="UserName2";
detail[1][1]="Password2";

detail[2][0]="UserName3";
detail[2][1]="Password3";

return detail;
}

//Test data to use In FormSubmit.java file.
@DataProvider(name="FormData")
public static Object[][] FormSubmitData(){

Object detail[][] = new Object[3][5];
detail[0][0]="fName1";
detail[0][1]="lname1";
detail[0][2]="email1@youraccount.com";
detail[0][3]="mobno1";
detail[0][4]="company1";

detail[1][0]="fName2";
detail[1][1]="lname2";
detail[1][2]="email2@youraccount.com";
detail[1][3]="mobno2";
detail[1][4]="company2";

detail[2][0]="fName3";
detail[2][1]="lname3";
detail[2][2]="email3@youraccount.com";
detail[2][3]="mobno3";
detail[2][4]="company3";

return detail;
}
}

You can see that we have created two different @DataProvider methods In dataProvider_Repository.java file and we have accessed them In LogInCase.java and FormSubmit.java files using syntax like bellow.
@Test(dataProviderClass=dataProvider_Repository.class,dataProvider="LogInData")
@Test(dataProviderClass=dataProvider_Repository.class,dataProvider="FormData")

Now If you will run LogInCase.java test then It will access data from LogInData @dataprivider method to execute test and testng out put will looks like bellow at the end of test execution.


Same way, When you run FormSubmit.java file, It will access data from FormData @dataprivider method and test execution result will looks like bellow.


You can save more @dataprivider methods In dataProvider_Repository.java file If you have more such test cases.

Wednesday, November 12, 2014

Selenium WebDriver With JUnit Interview Questions With Answers Part 12

Part 12

53 : Which Is the latest version of JUnit.

Answer : Current latest version of JUnit Is 4.12-beta-2. This can change In future. To check latest released version of JUnit, You can Visit JUnit Official WebSite.
54 : Tell me different JUnit annotations and Its usage.

Answer : JUnit has bellow given different annotations.
  • @Test  : @Test annotation Is useful to Identify method as a Test method from software automation test script.
  • @Before : @Before annotation method will be executed before each and every @Test method.
  • @After : @After annotation method will be executed after each and every @Test method.
  • @BeforeClass : @BeforeClass annotation method will be executed before all @Test methods In a class(Means before first @Test method).
  • @AfterClass : @AfterClass annotation method will be executed after all @Test method In a class(Means after last @Test method).
  • @Ignore : @Ignore annotation Is useful to exclude @Test method from execution. VIEW EXAMPLE
  • @Test(timeout=1000) : You can set @Test method execution timeout. This @Test method fails Immediately when Its execution time cross 1000 milliseconds.
VIEW PRACTICAL EXAMPLE of JUnit annotations with selenium webdriver software testing tool.

55 : Write sample JUnit @Test method that passes when expected ArithmeticException thrown.

Answer : Sample JUnit @Test to pass on expected ArithmeticException Is as bellow.
@Test(expected = ArithmeticException.class)  
public void excOnDivision() {
int i = 5/0;
}

VIEW PRACTICAL EXAMPLE for Junit Timeout And Expected Exception software Test.

56 : Write sample JUnit @Test method that fails when unexpected ArithmeticException thrown.

Answer : Sample JUnit @Test to fail on unexpected ArithmeticException Is as bellow.
@Test  
public void excOnDivision() {
int i = 5/0;
}

57 : What are the advantages of TestNG over JUnit.

Answer : Advantages of TestNG over JUnit JUnit are as bellow.


  • TestNG Annotations are simple and Easy to understand.
  • Easy to parameterize the software test cases In TestNG.
  • Easy to run software automation test cases In parallel.
  • Can generate Interactive XSLT test execution reports using TestNG.



  • My Trading Background - Most Recent Year

    (December 2013-November 2014)


    (If this is your first time reading/this story, read part 1 HERE before reading this, and part 2 HERE)   
    (FYI, this is another long read. I packed almost all of my big moments this year of trading into this post.)


     Near the end of December 2013, I got into a debate with my Dad regarding trading. I ended up making a bet with him: if I could make $200/day for 2 weeks straight, he would give me $1k cash. If I made $1k one day and then lost $500 the next day, but then made $2k the next day, it didn't count. It needed to be $200+, GREEN every single day, for 2 weeks. Basically, I was taking an ideal goal of being green every day for a year (as a steady stream of income) and scaling it down into a smaller time frame. So, as I watched the market open that next Monday morning, I had a brand new mindset that I had never felt before. For the first time, I was more focused on the losing side of the trade rather than the winning side. I was afraid to lose money because I didn't want to lose the bet. I was playing to avoid a loss where before I had always played to win.


        So I traded almost paranoid for the first few days of the bet. I sought out trades with decent setups where I could risk little to no money, and make a quick $100-500. What were those setups that risked no money? Scalping sheep chatroom alerts. Yes, its a shameless admission. I would study and find out the average amount of $ that flowed into a stock after a lame FURU bought a stock. I would do the math quickly in my head, reacting within seconds of the "alert", figuring out a position size that was decent, and taking the trade. Then I’d sell within minutes and make my daily goal. I did this for the first few days, but I knew I couldn't do this for much longer. I felt like I was cheating to win the bet: I wasn’t truly trading and I wasn’t learning anything by doing this. So I moved on to trading "real" setups. I would take a trade, sell within minutes and lock in the fast money, and then quit for the rest of the day to make sure I didn't do anything stupid. After a week of this, I felt near euphoric. What was this feeling? How did this happen? It happened because I was forcing myself to be green on the day and not give it back.


        The next week, the pot stocks started getting action. This was VERY early in their runs and I had no idea how far they would go. I would just very quickly scalp them for a few pennies here and there. The $200/day goal was demolished in minutes by scalping CBIS, MJNA, HEMP, PHOT, etc. I could buy 100k-200k shares,  sell them in under 10 minutes, and usually  make $1-2k. By the end of the second week I had made nearly $8k, which averages out to about $800/day. I'm sure my Dad was surprised, but I was even more surprised. It was amazing to me how much one small tweak in my trading mindset could affect my profits. I asked my Dad to give me the $1k since I had won the bet, but he said he wasn't really serious about giving me that money. I was a little upset at first, but I soon realized that $1k wasn't the real prize from winning the bet. My dad had unknowingly showed me how to open the door to the stock market. I finally learned what the key to success was in trading: consistency. That weekend after the bet was over, I decided to take the bet and move it to a bigger scale. I made an Excel Spreadsheet with two columns: one with a goal of $50k/year, and the other with $100k/year. To accomplish these goals I needed to make $200/day and $400/day, respectively. And after each day, I would mark the day as green if I hit my goal, and red if I didn't. Then I would also mark each week green or red depending on if if I hit or missed weekly goals.


        The next few weeks I started getting more aggressive, holding pot stocks overnight for gap plays and selling them the next day at open. Several times I would be up over $1k in the first 30 seconds of the market open, and I would get up from my computer, walk over to my Dad drinking his coffee at the table, and tell him "I'm up $1k today." Another day, it would be "I'm up 2k today." It was almost TOO easy, I was making money hand-over-fist, and by the end of January 2014, I was up $35k. At the end of February I was up $63k, just shy of $100k YTD. Mid-March I was up $100k in March ALONE, $200k YTD. It was almost too easy to make money and it seemed like every setup worked. To be honest, I think it was a bit of lucky timing that I had this bet with my Dad right when pot stocks started moving. The bet was perfect timing as pot stocks created huge opportunities, which was perfect timing to give me the confidence and boost of mindset to start trading well.


       I was 19 years old, and where less than 6 months ago I was struggling to pick a dime up off the floor,  now 3 months into 2014 I was up $200k. Nothing could stop me, I was on fire and my trading ego was massive. Then came ISR.


    Here's the 1-minute chart on ISR on day 1 of its move:






      My first short was early on, during the first speed up/para to 1.70. I shorted high 1.50s, and covered at 1.44, making about $2k. ‘Nice trade for the day,’ I thought to myself,  ‘maybe I should take the rest of the day off...Nah, I'll short the next bounce and hold for the fade back to low 1s.’ So I shorted 10k shares at 1.52 on the next pop over 1.50, and it held up very well. It then dipped below 1.50 and I thought it was finally done, but then it pushed back over and consolidated for a while. I was being stubborn, risking my gains from the earlier short to potentially make even more. It then grinded back to the HOD and I was back to even on the day. I had to leave soon to go play some music with my friends, but I decided to leave the trade on and monitor it from my phone. I checked it an hour later and it was above 2. I now was down on the day and kind of pissed, but I just let it go. I could just add when I got home . Another hour passed and I came back to my computer to see ISR at 2.45. I was now down about $8k on the day, definitely bad, but I was OK with that. I could just trade out of it eventually, right?


       Eventually, as you see in the chart above, it ripped to 3. Keep in mind that this stock was at 1.10 near market open and was now at 3. Shorts were absolutely screwed, and I was one of them. I ended up adding several times during the grind up and actually nailed the top, shorting 10k more in the 2.90s. But at 2.90, I was down nearly $30k. I had 30k shares at an average of around 2.05.


    ISR had its first real pullback of the day near close, and at one point it hit 2.30. I could have covered there and taken a small $10k loss (ok, it's not that small but definitely small compared to what I was down earlier in the day.) It rebounded back to 2.50, and I wanted to box half or all before close to stay safe overnight. But I was frozen; I couldn't make a decision and I couldn't place the order. I was greedy and I wanted this to gap down the next day and let me out for even. Lesson #1: Don't get greedy on day 1 squeezes of a short, thinking they will go right back down the next day. Especially after a float rotation day. So at close, I was short 30k shares at 2.05 average. Oops. Several times during a/h trading, the stock dipped back below 2.40 and I had SEVERAL opportunities to box my shares, which I should have done before the market closed. But I was still frozen, and helplessly watched every tick of that a/h session.


        Throughout the night, I had several dreams that ISR was up to $4 premarket, and I panicked and woke up terrified. But I realized I was dreaming, because I knew there was no way it could get to $4. Right? I finally woke up before my alarm clock because I couldn't fall asleep, and turned on my computer to see what ISR was really doing. It was sitting around 2.70 premarket, a small gap up. I was pissed I didn't box the day before, but the only thing I could do now was focus on the day ahead of me. Near market open, ISR crept up to 3.20s and I was down more than $30k already. God dammit Nikkos, what are you doing??? I added 10k more shares at 3.20 during premarket and it pulled back into the open, and the action was very strange near open. It was sitting just under 3.10 and there was barely any volume, almost like orders were being held. Then maybe 15-20 minutes in, the volume EXPLODED as well as the price, and I was frozen again. It was back at 3.20, shit...and then it grinded up to 3.69 in the first hour. At the top I was down nearly 80k after adding even more near market open, and I was literally about to pass out. I had to get up from my computer and try to take my mind off of ISR. I was hyperventilating and felt like I was going to throw up. I couldn't do this anymore...why am I even trading?


        ISR ended up going back below 3 in the next few hours, and I had a chance to cover AT LEAST my adds above 3 for small profit to reduce my unrealized loss. But I didn't. Once again I was frozen. Over the course of the next few hours, ISR grinded back to a new HOD above 3.70, and during that grind I panicked and actually went net LONG ISR. I bought 75k ISR, which boxed my 35-40k shares short and made me long about 35k shares of ISR at 3.50. At first, it worked...it hit 3.70 and I made back $7k real quick. I thought about selling and just going back to neutral, so that I had net no position in ISR. But I wanted $4 on ISR, and I remember thinking desperately, “please squeeze to $4 and let me make some money back.” During this part of the trade I was talking with a buddy of mine who was in Investors Underground (IU) chatroom, and I was asking him what the traders in that room were doing with ISR. He told me that they shorted near dead top in the 3.70s, and that it was a HOD stuff. I had several chances to sell my net long position for even, but I ended up selling for a .10 loss. Instead of taking the quick $7k profit on the long, I sold for a $3.5k loss. What the HELL was I doing?????????????????? After market close, I felt mentally and emotionally demolished. I put on my jacket and went on a walk around Boston. I pondered my existence, what was I doing on earth, why was I even trading after I had hit my yearly goals in the first few months of 2014? Money was controlling my life and emotions, and it felt terrible. Lesson #2: There are more important things in life than making money in the stock market. Don't let it take over your life and affect your life outside of trading.


       Eventually, over the next few weeks, I scalped ISR trying to slowly make back my loss. But I failed. Eventually I took the biggest loss of my trading career, -$38k.




       Here's the ISR daily chart over the course of the next several weeks after this incident:




    The next 2 months I was stuck in a rut. I could only think about trading to make back my loss. $500-1k profit on a trade wasn't enough. I wanted $3k, $5k, $10k: enough to make a decent chunk of that loss back. This was the 2nd HUGE turning point/lesson in my trading from a loss, the first being when I was -$10k on the year in 2013 and was only focusing on trying to make back the money I lost. I had to do the same thing I did back then to get back on my feet: STOP trying to make your loss back. It's OVER: quit moaning over the loss, stand the fuck up, and focus on trading well. Forget the loss, because you can't do anything to change it. The only thing you can change is your mindset moving forward. I went back to the mindset I had at the beginning of 2014: stay GREEN every day, no matter how much. ‘Just force yourself to stop trading once you are green on the day,’ I told myself, ‘at least for a few weeks, until your thinking is healthy again and not distorted/out of whack from the big loss.’


        Near the end of April 2014, I decided to join InvestorsUnderground. I had heard and read about that chat room since the beginning of the year, and it seemed like the real deal. All of the best traders are in there, and they traded all the same stocks I did and more. I was and still am very cynical, and I knew all the chat rooms I had been part of before were mostly scams. So I joined the chat room, started watching all the webinars, bought Nate's DVD Textbook Trading, and I felt refreshed. This community of traders wasn't full of dirty bullshit behind the scenes like all the rest. IU, along with the mindset of being GREEN every day, really put me back on track. I spent the rest of my summer connecting with other traders in the chat room, which is the single best part about IU. There are some amazing trades every day in chat no doubt, but that's not the real value of IU in my opinion. It's the fact that you can ask questions to top-notch traders for no extra fee. You can get advice about trading and the massive rollercoaster it is, for no extra fee. I've made some really great trading friends in this chat room and its absolutely amazing the amount of support that flows from them every day. If you are down in a rut, they will pick you up, give you advice, help you out, etc. That's what you don't see advertised about the chat room, and that's the best part about it. There are some genius traders in there, like the one who predicted a move in gold/JDST months before it happened. You can watch and learn from people like that for no extra fee. IU is the best trading community to be a part of, hands down.


        Up until mid August 2014, I was having an amazing summer trading. I was up almost $100k since my ISR loss, putting me at around $250k profits YTD, and I was really starting to find my niche trading: shorting smallcap runners that were garbage. Stocks where the perception of value and reality of value differ immensely. The stocks could be up on news at first, but that's not the reason they are up 100%+: they are up because the float has rotated and shorts are getting squeezed. I really tried to force myself to wait for the backside of the move to swing short (although I would still scalp the front side of the move to build up extra profit). And sometimes stocks are up 100%+ over the course of a week with NO news, just pure sympathy or speculation, just like LAKE and APT recently. It was all float rotation and short squeezes like Nate explained in his float rotation video.


        I was back on track with my trading again, and I felt great. But in August 2014, I had a weird feeling. I noticed that whenever I felt the best about my trading, or the most ecstatic about it, is when I would usually take a huge loss. My account was at all-time highs, and I was doing the best I had ever done in trading, but I decided to ignore this feeling. Then came JRJC. Long story short, it was pretty much just like ISR. Stubborn short, add add add, and I took another big hit, -$34k.




    I knew what I did wrong, and over the next 3 weeks I made back $28k of that $34k loss, by once again NOT trying to make back the $ I lost, and rather focusing on good trading and being consistent. I didn't even realize I made back $28k that fast until I took a step back. I was making $3k here, $4k there, over and over, and somehow it added up.

       Next up was SCOK. You would think I would have learned my lesson by now with shorting these stocks early on and adding adding adding, right? Well I had almost made back my full loss from JRJC, but just as that realization sunk in, I screwed up. I started shorting SCOK early on in the day, and was up $1k real quick. But I didn't take it. This happens often when you are on a hot streak: you don't want to ruin your green streak by taking a small loss. Don't let this happen: the small loss often turns into a huge loser because you are too stubborn. I went back to my old thinking of trying to make back the remainder of my loss from JRJC. NEVER do this. If you learn anything from this post, let it be the fact that you should never let yourself think that you need to make your loss back. FORGET the loss. Anyways...SCOK went back up, and I was down $500. ‘Well,’ I said, ‘I will just wait and cover when I am back to breakeven.’ But it didn't pull back, and then it pushed more and I was down $2k. But since I was so close to making back my JRJC loss, I didn't want to take a $2k loss. I was being stubborn when I shouldn't have. Cut your losses quick, right? MUCH easier said than done, but the faster you can get some damn self-discipline to do this, the quicker you will improve in trading, I am sure. So I ended up being stubborn and taking ANOTHER big hit, -$33k on SCOK.




        Over the course of next month I was stuck in a bad mindset of trying to make back my losses. This time it was different: I was cutting my losses quick but the trades themselves were taken with the mindset of making back some of my recent losses. They weren't taken because they were great entries, necessarily. From mid-August 2014 to September 2014, I had lost over $120k. I felt exactly the same as I did with my ISR loss, except this time it was worse. ISR was a one trade loss. But this was a slooooooow deadly downwards spiral into a dark abyss. I knew I needed to stop trading but I couldn't.


       My Dad called me one day to ask me what was going on with my trading. He told me I needed to stop trading, just like this time about a year ago. ‘Quit while you are ahead,’ he said. ‘You are still up over 100k on this year, and that's AMAZING. Don't feel like you failed, you still did great.’ But in my eyes I failed. This was the lowest I had ever been in my trading career, emotionally. I broke down and started crying (yes, I cried.) I couldn't stop trading: I had put too much effort into this to stop (sound familiar? see previous blog posts) Trading can take a serious toll on your physical and mental health if you let it, and I was letting it. Once again, money was controlling my life. Hadn't I learned my lesson earlier this year?


        I took a break from trading for a week, fully convinced that I was done for the rest of the year, taking my Dad's advice to heart. But over that week of taking a break, I deeply reflected upon my mistakes. And I realized, once again, I had to sneak my way back into trading. I saw APT and LAKE moving up on their first day, and knew the moves weren't  warranted. But as I had learned, that didn't mean they couldn't go higher. At market close October 9th, I ended up with 30k shares of APT shares boxed. I was ready to nail this trade, and be extremely patient for the perfect entry. Over the next few days I did scalp APT intraday, but most of the time only with 10-15k shares. This was still the front side of the move, and I wasn't going to be a stubborn short again. I FORCED myself to wait to swing short this stock. You can't do this again, Nikkos. Exercise some self-discipline this time and nail it when the time is right.
       Over the next several weeks, I had a strong conviction that I wanted to swing this stock back to mid 3s. I missed a lot of the move, as I was scalping it when the Ebola stocks showed their TRUE sign of death, that the short squeeze was finally over.
    I think Brandon/crawfish_poboy sums it up best with this tweet:



     Even though I missed a lot of the initial drop from 9 to 4, I still made a lot of money. But I wasn't done with this greasy pig yet. I lathered it up with oil and let it roll in mud again, waiting for the squeeze-a-roo to re-short. And BOOM: NYC Ebola news hit.
       This was the re-short opportunity of a lifetime, let's do this. I had extreme conviction on this trade, and over the next several weeks the junk known as APT faded off into the dark abyss it had come from. It was my best trade to date:




        During these few weeks I was trading APT, I was also trading other PERFECT setups for swing shorts such as ESI and ZAZA, to name a few. I didn't care about scalping stocks for small profits: I wanted the PERFECT opportunities only, very few trades but very high success rate. I could size in and nail them with conviction. And I did. October 2014 was my best month ever, making over $100k and nearly all my losses from the previous month back. But I couldn't forget what I had told myself just a few weeks ago. I knew I needed to stop trading, at least for a while.


        My life isn't about money. I'm not about money. My goal isn't to make $500k a year from trading; my true passion is music. Since day one, trading has been a way to accomplish bigger goals. Trading is a way to make steady income so that I can focus on what I really love to do and not have to worry about paying bills on time or paying off student loans.  Life is all about goals. Without goals, one is just a lost soul, living a lost cause. I've been at my high points in life when I have a clear vision of my future and my goals. And since earlier this year, I haven't had clear goals. I lost sight of what I really wanted to do. And that's why I'm taking the next few months off from trading. I need to regroup, sit down, take a deep breath, and focus. I need a vision, I need to regain my purpose and passion.


    To sum up the most important lessons I've learned since I started trading, and some advice:


    1) If you are struggling with trading, don't keep digging yourself into a deeper hole. Before trying to work on making a lot of $ trading, one must first work on fixing their mindset. One of the greatest feelings you can have when in a trading slump is ending every day GREEN. It’s the @crawfish_poboy special. It doesn't matter if you were making $500 a day for the last year and all of a sudden you got in a slump and you could barely make $50. Make it a goal to be green every day. $50 profit every day is better than losing, and you can walk away from the computer each and every day feeling like you accomplished something. Make an Excel Spreadsheet; make a bet with a friend that you can trade green every day for 2 weeks straight. Find something with which to hold yourself accountable, so you don't end up making $500 one day and decide to keep trading and then end red on the day. It's a terrible feeling to go from green on the day to red. It's very important that you do not take this "goal" concept the wrong way. It is NOT a number that you MUST hit everyday and therefore will force bad trades just to hit the goal. It IS a number that IF reached, you can stop trading for the rest of the day. If you have a goal to make $200/day and you hit it in the first 30 minutes, why are you still at the computer?


    2) If you are a newer trader, don't expect to make money your first year trading. I'm just being honest, and I'm sure many other more experienced traders would agree. It took me a full year to even smell a whiff of green, and another 6 months to start being somewhat consistent. Your focus shouldn't be on making money at first: it should be on fine-tuning your mindset to trade consistently. You WILL know when you are ready to make the move to trading for profits, but it took me a long time to move from the 'learning' phase to the 'profiting' phase. There's no set time to when this will happen. I can't say if it will take 6 months or 6 years, but you will know when that time comes. There's a feeling I just can't explain. You are in the ZONE, and if you have trained your mind to focus on consistency, you can be in the ZONE every day. The money will come naturally if you trade well.


    3) Don’t jump the gun on trading as a career. As stated above, don't expect to make money your first year trading. I was lucky that I started trading young, and I didn't NEED to make money to pay bills. I'm sure many people start trading because they want to quit their 9-5 job, and they hear about all the glamours of trading, such as buying a fancy car or a fancy watch and a big house. I could care less about those materialistic goods, but some do. But people who quit their jobs to trade might NEED to make money to pay the bills. Don't quit too early while you are still in the learning phase, and make sure you have backup money; I’d recommend a few years of your salary in the bank as a backup plan.


    4) If you just had a huge loss or drawback, forget about trying to make back that loss. I wasted several months of trading trying to make my losses back, and sometimes I lost even MORE while trying to make it back. Go back to the basics; be green every day. There's nothing more rewarding and healthy than being consistently green every day. And then one day in a few months, after trading green every day, you'll look at your account and realize you somehow made $50k, $100k, whatever. It's amazing how fast it adds up.


    Thanks for reading my story, I hope you enjoyed it.
    Nikkos (IU: Nikkorico)