Thursday, December 25, 2014

Java program to find the common interval between the meeting intervals of two persons


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Meeting {
 private static List<Double> PS1; // Person 1's Meeting Start times.
 private static List<Double> PE1; // Person 1's Meeting End times.
 private static List<Double> PS2; // Person 2's Meeting Start times.
 private static List<Double> PE2; // Person 2's Meeting End times.
 private static Double maxTime;
 public static void main(String[] args) {
  //TC 1
//  PS1 = Arrays.asList(0D,8D);
//  PE1 = Arrays.asList(1D,23D);
//  PS2 = Arrays.asList(0D,3D,5D,9D);
//  PE2 = Arrays.asList(2D,4D,6D,23D);
  
  //TC 2
  PS1 = Arrays.asList(1D);
  PE1 = Arrays.asList(2D);
  PS2 = Arrays.asList(2D);
  PE2 = Arrays.asList(3D);
  
  //TC3
  PS1 = Arrays.asList(1D,10D,19D,21D,27D);
  PE1 = Arrays.asList(5D,14D,20D,23D,30D);
  PS2 = Arrays.asList(3D,12D,18D,23D);
  PE2 = Arrays.asList(5D,15D,21D,24D);
  
  maxTime = PE1.get(PE1.size() - 1) > PE2.get(PE2.size() - 1) ? PE1.get(PE1.size() - 1) : PE2.get(PE2.size() - 1); 
  
  FreeTimeSlot P1 = findFreeTimeSlot(PS1,PE1);
  System.out.println("Free time slots for person 1 :");
  printTimeSlot(P1);
  
  FreeTimeSlot P2 = findFreeTimeSlot(PS2,PE2);
  System.out.println("Free time slots for person 2 :");
  printTimeSlot(P2);

  FreeTimeSlot commonFreeTimeSlot = findCommonFreeTimeSlot(P1, P2);
  System.out.println("Common free time slots for person 1 and person 2 :");
  printTimeSlot(commonFreeTimeSlot);
 }
 
 public static void printTimeSlot(FreeTimeSlot timeSlot) {
  int i=0;
  for(Double time : timeSlot.S) {
   System.out.println(time + " " + timeSlot.E.get(i));
   i++;
  }
 }
 
 public static FreeTimeSlot findCommonFreeTimeSlot(FreeTimeSlot P1, FreeTimeSlot P2) {
  FreeTimeSlot commonFreeTimeSlot = new FreeTimeSlot();
  int a = 0; int b = 0;
  //a is the index for Person 1
  //b is the index for Person 2
  while (a < P1.S.size() && b < P2.S.size()) {
   //Person 1's time slot lies completely ahead of Person 2's time slot
   /*
    *        a                    b
    * +-----------------+   +----------------+
    */
   if(P1.S.get(a) < P2.S.get(b) && P1.E.get(a) <= P2.S.get(b)) {
    a++;
   }
   //Person 2's time slot lies completely ahead of Person 1's time slot
   /*
    *        b                    a
    * +-----------------+   +----------------+
    */
   else if(P1.S.get(a) > P2.S.get(b) && P1.S.get(a) >= P2.E.get(b)) {
    b++;
   }
   //Start of Person 1's time slot is before start of Person 2's time slot
   /*
    *        a        b
    * +-------------+---+-------+
    */
   else if(P1.S.get(a) <= P2.S.get(b)) {
    commonFreeTimeSlot.S.add(P2.S.get(b));
    Double time = P1.E.get(a) < P2.E.get(b) ? P1.E.get(a) : P2.E.get(b);
    commonFreeTimeSlot.E.add(time);
    if(P2.E.get(b) < P1.E.get(a)) {
     b++;
    }
    else {
     a++;
    }
   }
   //Start of Person 2's time slot is before start of Person 1's time slot
   /*
    *        b        a
    * +-------------+---+-------+
    */
   else if(P1.S.get(a) > P2.S.get(b)) {
    commonFreeTimeSlot.S.add(P1.S.get(a));
    Double time = P2.E.get(b) < P1.E.get(a) ? P2.E.get(b) :  P1.E.get(a);
    commonFreeTimeSlot.E.add(time);
    if(P1.E.get(a) < P2.E.get(b)) {
     a++;
    }
    else {
     b++;
    }
   }
  }
  return commonFreeTimeSlot;
 }
 
 public static FreeTimeSlot findFreeTimeSlot(List<Double> personStart, List<Double> personEnd) {
  double s=0;
  int a = 0;
  FreeTimeSlot freeTimeSlot = new FreeTimeSlot();
  while(a<personStart.size()) {
   if(s < personStart.get(a)) {
    freeTimeSlot.S.add(s);
    freeTimeSlot.E.add(personStart.get(a));
    s = personEnd.get(a);
    a++;
   }
   else if(s == personStart.get(a)) {
    s = personEnd.get(a);
    a++;
   }
  }
  // Adding the remaining time of the day as a free time slot.
  int length = freeTimeSlot.E.size();
  if(freeTimeSlot.E.get(length - 1) < maxTime && personEnd.get(personEnd.size() - 1) < maxTime) {
   freeTimeSlot.S.add(personEnd.get(personEnd.size() - 1));
   freeTimeSlot.E.add(maxTime);
  }
  return freeTimeSlot;
 }
}

class FreeTimeSlot
{
 List<Double> S = new ArrayList<Double>();
 List<Double> E = new ArrayList<Double>();
}

Sunday, December 21, 2014

Print combinations of strings from List of List of Strings

Print combinations of strings from List of List of Strings.
Example input: [[abc, def], [ghi, jkl, mno], [pqr]]
Example output:
abc ghi pqr 
abc jkl pqr 
abc mno pqr 
def ghi pqr 
def jkl pqr 
def mno pqr 

Java Program

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Combinations {
 public static void main(String[] args) {
  int num = 0;
  ArrayList<List<String>> input = new ArrayList<List<String>>();
  input.add(Arrays.asList("abc","def"));
  input.add(Arrays.asList("ghi","jkl","mno"));
  input.add(Arrays.asList("pqr"));
  ArrayList<String> output = new ArrayList<String>();
  combine(num, input, output);
 }
 
 public static void combine(int num, ArrayList<List<String>> input, ArrayList<String> output) {
  if(num == input.size()) {
   for(String string : output) {
    System.out.print(string + " ");
   }
   System.out.println();
  }
  else {
   List<String> current = input.get(num);
   for(String string : current) {
    output.add(string);
    combine(num + 1, input, output);
    output.remove(num);
   }
  }
 }
}

Wednesday, November 26, 2014

Match the columns problem

Problem:
Find the number of intersections of the lines matching the two columns. The first line contains an integer T denoting the number of test-cases.
First line of each test-case contains an integer N denoting the number of elements in each column. N lines follow each containing a character c separated from a number n by a space character.

Sample Input:
1
8
A 3
B 2
C 8
D 1
E 6
F 7
G 4
H 5

Sample Output:
10 

Explanation:




Solution: To come in following days.

Monday, November 24, 2014

Switching between tabs in same browser window using Selenium WebDriver

Recently I was supposed to automate a test-case which needed me to perform the following steps:

1. Open a browser window
2. Navigate to a URL
3. Perform some operations
4. Open a new tab in the "same" browser window
5. Perform some operations in the newly opened tab
6. Switch back to the previously opened tab
7. Perform some operations in this tab

Most of the resources I have come across while I was dealing with this particular problem talked about opening a new browser window (not a new tab in the same window), using windowHandles to switch between the windows.

The typical catch in this problem is:
When you open a new browser window, you get two window handles. Then they can be used to switch between them.
But when you open a new tab, there is a single window handle. So switching between tabs is not achieved by calling driver.switchTo().window(<windowHandle>)

So I used the following work-around:
1. Open a new tab using Ctrl + t
2. Driver control automatically switches to the newly opened tab
3. Perform the required operations here.
4. Next switch back to the old tab using Ctrl + Tab. You need to keep pressing this unless you reach the desired tab.
5. Once the desired tab is reached, then perform the operations in that tab.

Sample Code:
Get the current window handle and open a new tab using Ctrl + t
        driver.get("http://google.com");
        String windowHandle = driver.getWindowHandle();
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

The size of the output of getWindowHandles() is 1 which means that there is one single window handle
        ArrayList tabs = new ArrayList (driver.getWindowHandles());
        System.out.println(tabs.size());
        driver.switchTo().window(tabs.get(0)); 

The control is now in the new tab
        driver.get("http://bing.com");
        //perform other operations.

Switch to the old tab using Ctrl + Tab
        driver.switchTo().window(mainWindowHandle);
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
        driver.switchTo().defaultContent();

Sunday, November 23, 2014

String Problems asked in Programming Interviews

Problem 1:
Find the longest anagram substring of a given string S2 in another string S1.
S1: ascfg
S2: acs
Output: asc



Problem 2:
Find all the anagram substrings of a given string S2 in another string S1.
S1: ascfgsa
S2: cas
Output: {asc, sa}

Saturday, November 22, 2014

Programming problems which can be solved using recursion


Problem 1: 
There is a terrain on which water flows from West to East. As per laws of Physics, water will flow from higher height to lower height. Find the number of possible paths on which water can flow on the terrain.
The terrain is described by a two-dimensional array A of dimensions M x N.
Each element A[i,j] specifies the height of the point.
Water can only flow from one cell to another cell if one of the following conditions satisfy:
1. A[i][j+1] < A[i][j]
2. A[i-1][j+1] < A[i][j]
3. A[i+1][j+1] < A[i][j]

Input: 
The first line of input will consist of a number N which determines the number of test-cases.
The second line contains two space-separated integers M, N denoting the dimensions of the two-dimensional array.
The next M lines contain N space separated integers each denoting the height of each point A[i,j] of the terrain.

Output:
Output should contain N lines each containing the number of possible paths water can flow from West to East (left-to-right).

Example:










Explanation: 
In the diagram above, there are four paths water can flow from left to right.
1. 10 -> 8 -> 6
2. 10 -> 8 -> 7
3. 12 -> 8 -> 6
4. 12 -> 8 -> 7

Saturday, November 1, 2014

Largest sum of any of the paths till row N-1 of a two-dimensional array

Approach explained pictorially:



Initial matrix


After first iteration


After second iteration
public class Matrix {
 public static void main(String[] args) {
  //Taking N = 3, for 3x3 matrix.
  int[][] A = {{1,2,3},
               {6,4,5},
               {9,8,7}};
  
  //Dynamic programming approach.
  //Logic is to compute the current maximum sum at any given point in the two-dimensional array.
  //Time complexity: O(N^2).
  for(int i = 1;i < A.length;i++) {
   for(int j = 0;j < A.length; j++) {
    if(j == 0) {
     A[i][j] = max((A[i][j] + A[i-1][j]),(A[i][j] + A[i-1][j+1]));
    }
    else if(j==A.length - 1) {
     A[i][j] = max((A[i][j] + A[i-1][j]),(A[i][j] + A[i-1][j-1]));
    }
    else {
     A[i][j] = max((A[i][j] + A[i-1][j-1]),(A[i][j] + A[i-1][j]),(A[i][j] + A[i-1][j+1]));
    }
   }
  }
  
  //The maximum sum is present in the last (N-1)th row. Traverse it to find the maximum sum in O(N) time complexity.
  int maxSum = Integer.MIN_VALUE;
  for(int i=0;i<A.length;i++) {
   if(maxSum < A[A.length - 1][i]) {
    maxSum = A[A.length - 1][i];
   }
  }
  
  System.out.println(maxSum);
 }
 
 //Returns the maximum of the two numbers passed as arguments.
 public static int max(int a, int b) {
  return a >= b ? a:b;
 }
 
 //Returns the maximum of the three numbers passed as arguments.
 public static int max(int a, int b, int c) {
  int x = (a >= b ? a:b);
  return c >= x ? c:x;
 }
}


Thursday, October 23, 2014

Some of the best resources to learn about Software Design Patterns

I have listed some of the best resources to learn about design patterns below based on my experience and also from the experience of some of my very talented colleagues.
The Head First Design Patterns book is an ideal book to learn design patterns for everyone, starting from beginners who do not have any prior knowledge of design patterns to experts in design patterns. The biggest positive about this book is that it follows the why, how and what sequence of developing systems.

1. At first it explains why a design pattern should be used. This part concentrates on motivating the reader about to learn and use design patterns in regular software development. It starts with a problem in hand and various methods to solve it.

2. Next it explains the design pattern and concentrates on how to implement it using OO principles and other best practices of Software Development.

3. At the end, it reveals what is the outcome of using these design pattern and how it is a better solution than a solution developed without using design patterns.

The content of the book is quite interactive and illustrative. It brings in real world situations and with funny caricatures, it keeps you from feeling bored at any point of time.

Buy on Amazon:

Sunday, August 3, 2014

Number of ways to obtain a number n by adding numbers from 1 to n

Problem
Given a number n, find the different combinations of numbers from 1 to n, which can be added to obtain the number n.
Sample Input
5
Sample Output
1. 1,1,1,1,1
2. 1,1,1,2
3. 1,1,3
4. 1,2,2
5. 1,4
6. 2,3
7. 5
Java Code

import java.util.ArrayList;

public class Sum {
private static int count = 0;
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
int n = 5;
long start = System.currentTimeMillis();
find(n,array,1);
long end = System.currentTimeMillis();
System.out.println("Time taken for " + n + " is " + (end - start) + " milliseconds.");
}
public static void find(int n, ArrayList<Integer> array,int start) {
int sum = 0;
for(int i=0;i<array.size();i++) {
sum += array.get(i);
}
if(sum == n) {
System.out.print(count + ".\t");
for(int i=0;i<array.size();i++) {
if(i != array.size() - 1) {
System.out.print(array.get(i) + ",");
}
else {
System.out.print(array.get(i));
}
}
System.out.println();
count++;
return;
}
else if(sum > n) {
return;
}
else {
for(int ele = start; ele <= n; ele++) {
if(sum + ele <= n) {
array.add(ele);
find(n,array,ele);
array.remove(array.get(array.size() - 1));
}
else {
break;
}
/*array.add(ele);
find(n,array,ele);
array.remove(array.get(array.size() - 1));*/
}
}
}
}


Saturday, April 5, 2014

Connecting to Wordpress Database and manipulating post content using PHP

The sample code below covers the following:
1. Connecting to database using PHP.
2. File uploading and reading in PHP.
3. Parsing and splitting operations on Strings in PHP.
Sample Code


<?php
function replaceTitleWithHyperlink($content, $hospGuid, $title)
{
$parts = explode(" ", $content);
$arrlength = count($parts);

$inFound = False;
$asFound = False;
$hospitalName = "";

$indexOfFirstIn = 0;
$indexOfRequiredAs = 0;

for($i=0;$i<$arrlength;$i++)
{
if(strcmp($parts[$i],"in") == 0)
{
$inFound = True;
$indexOfFirstIn = $i;
}
else if($inFound == True and strcmp($parts[$i],"as") == 0)
{
$asFound = True;
$indexOfRequiredAs = $i;
}
else if($asFound == False and $inFound == True)
{
$hospitalName = $hospitalName . " " . $parts[$i];
}
else if($asFound == True and $inFound == True)
{
break;
}
}

$indexOfMatch=1;
$numberOfMatches = 0;

for($i=1;$i<count($hospGuid);$i++)
{
if(strcasecmp(trim($title[$i]), trim($hospitalName)) == 0)
{
$indexOfMatch = $i;
$numberOfMatches++;
}
}
echo "<br>numberOfMatches: " . $numberOfMatches . "<br>";

$finalDocPost = "";

if($numberOfMatches > 1)
{
return $finalDocPost;
}

$parts[$indexOfRequiredAs - 1] = "<a href=\"" . $hospGuid[$indexOfMatch] . "\">" . $hospitalName . "</a>";

for($i=0;$i<$arrlength;$i++)
{
if($i>$indexOfFirstIn and $i<$indexOfRequiredAs-1)
{
}
else
{
$finalDocPost .= " " . $parts[$i];
}
}

echo "<br> Final Doctor Post: " . $finalDocPost . "<br>";
return $finalDocPost;
}

//Fetch values from the form.
$db_url = $_POST["db_url"];
$db_user = $_POST["db_user"];
$db_password = $_POST["db_password"];
$db_name = $_POST["db_name"];
$file_name = $_POST["file"];
$csv_indices = $_POST["indices"];
$update_pref = $_POST["update_pref"];

// Create connection
$con=mysqli_connect($db_url,$db_user,$db_password,$db_name);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error() . "<br>";
}
else
{
echo "Successfully connected to the database<br>";
}

//Array of unique-ids.
$indices = array("dummy");

if(strlen($csv_indices) > 0)
{
$parts = explode(",", $csv_indices);
for($i=0; $i< count($parts); $i++)
{
array_push($indices, trim($parts[$i]));
}
array_push($indices, "");
}

else
{
echo $_FILES["file"]["name"] . "<br>";
$allowedExtensions = array("txt");
$temp = explode(".", $_FILES["file"]["name"]);

$extension = end($temp);

if(in_array($extension, $allowedExtensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "Error: " . $_FILES["file"]["error"] . "</p><br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$file = fopen($_FILES["file"]["tmp_name"], "r") or exit("<br>Unable to open file!");
echo "<br>";
while(!feof($file))
{
$line = fgets($file);
echo $line. "<br>";
array_push($indices, trim($line));
}
fclose($file);
}
else
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "<br>File type not supported</p><br>";
}
}

$arrlength = count($indices);
$hospGuid = "";

for($i=1;$i<$arrlength-1;$i++)
{
echo "<br>";
echo "The value in indices is: " . $indices[$i] . " is the value";
}
echo "<br>";
echo "<br>";

for($i=1;$i<$arrlength-1;$i++)
{
$docSelect = "select wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.ID, wp_posts.guid, wp_posts.post_content from wp_posts inner join wp_postmeta on wp_posts.ID = wp_postmeta.post_id where wp_postmeta.meta_key='index' and wp_posts.post_status = 'publish' and wp_posts.post_type = 'post' and wp_postmeta.meta_value = '{$indices[$i]}' and wp_posts.ID in (select object_id from wp_term_relationships where term_taxonomy_id = (select term_taxonomy_id from wp_term_taxonomy inner join wp_terms on wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id where wp_term_taxonomy.taxonomy='category' and wp_terms.name='Doctors'))";

$hospSelect = "select wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.ID, wp_posts.guid, wp_posts.post_title from wp_posts inner join wp_postmeta on wp_posts.ID = wp_postmeta.post_id where wp_postmeta.meta_key='index' and wp_posts.post_status = 'publish' and wp_posts.post_type = 'post' and wp_postmeta.meta_value = '{$indices[$i]}' and wp_posts.ID in (select object_id from wp_term_relationships where term_taxonomy_id = (select term_taxonomy_id from wp_term_taxonomy inner join wp_terms on wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id where wp_term_taxonomy.taxonomy='category' and wp_terms.name='Hospitals'))";

echo "<strong>Hospitals query: " . $hospSelect . "</strong>";

$hospSet = mysqli_query($con,$hospSelect);

echo "<table border='1'>
<tr>
<th>Hospital Post ID</th>
<th>GUID</th>
</tr>";

$hospTitle = array("");
$hospGuid = array("");
$numOfHospitals = 1;

while($row = mysqli_fetch_array($hospSet))
{
array_push($hospGuid, $row['guid']);
array_push($hospTitle, $row['post_title']);
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $hospGuid[$numOfHospitals] . "</td>";
echo "</tr>";
$numOfHospitals++;
}
echo "</table>";
echo "<br>";

echo "<strong>Doctors query: " . $docSelect . "</strong>";
$docSet = mysqli_query($con,$docSelect);

$numOfDoctors = 0;

echo "<table border='1'>
<tr>
<th>Doctor Post ID</th>
<th>GUID</th>
<th>Content</th>
</tr>";

while($row = mysqli_fetch_array($docSet) and $numOfDoctors < 1)
{
$post_content = $row['post_content'];
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['guid'] . "</td>";
echo "<td>" . $post_content . "</td>";
echo "</tr>";
$numOfDoctors++;

$finalDocPost = replaceTitleWithHyperlink($post_content, $hospGuid, $hospTitle);

if(strlen($finalDocPost) > 0)
{
$docUpdate = "update wp_posts set post_content = '" . $finalDocPost . "' where ID = " . $row['ID'];

echo "<br><br> The update statement is: " . $docUpdate;

if($update_pref == "Yes")
{
mysqli_query($con,$docUpdate);
}
}
else
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "<br>There was ambiguity found while matching hospitals.</p><br>";
}
}
echo "<br><br>Number of doctors found: " . $numOfDoctors . "<br>";

echo "</table>";
echo "<br>";
echo "<br>";
}
mysqli_close($con);
?>

Using TableLayout and dynamically populating views in Android

Useful links are follow: http://forum.codecall.net/topic/70354-tablelayout-programatically/

Sample Code:

public void drawScreen(ArrayList<Product> products) {
tl.removeAllViews();
sv.removeAllViews();

TableRow.LayoutParams params = new TableRow.LayoutParams();
params.gravity = Gravity.CENTER_VERTICAL;

for(int i=0;i<products.size();i++) {
TableRow tr = new TableRow(this);
//View v = (RelativeLayout)findViewById(R.layout.product_row);
TextView tv = new TextView(this);
ImageView iv = new ImageView(this);
CheckBox cb = new CheckBox(this);
cb.setOnClickListener(this);
checkboxes.add(cb);
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
cb.setLayoutParams(params);
//cb.setOnCheckedChangeListener(this);
tv.setText(products.get(i).getAsin());
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setWidth(200);
tr.addView(iv);
tr.addView(tv);
tr.addView(cb);
tr.setGravity(Gravity.CENTER);
tr.setBackground(getResources().getDrawable(R.drawable.rectangle));
tl.addView(tr);
}
TableRow tr = new TableRow(this);
tr.setGravity(Gravity.CENTER);
compareButton = new Button(this);
compareButton.setText("Compare");
compareButton.setOnClickListener(this);
tr.addView(compareButton);
tl.addView(tr);
sv.addView(tl);
setContentView(sv);
}

Communicating non-primitive data objects between Android Activities

Non-primitive types such as ArrayLists can be communicated between Activities in Android using Parcelable interface.
Sample Example:
Class Definition:


package com.example.comparisonapp;

import android.os.Parcel;
import android.os.Parcelable;

public class Product implements Parcelable{
private String asin;
private String imageUrl;
private String description;
private String title;
private Double rating = 0.0;

public String getAsin() {
return asin;
}
public void setAsin(String asin) {
this.asin = asin;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}

public Product() {;}

public Product(Parcel in) {
this.asin = in.readString();
this.imageUrl = in.readString();
this.description = in.readString();
this.title = in.readString();
this.rating = in.readDouble();
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
arg0.writeString(asin);
arg0.writeString(imageUrl);
arg0.writeString(description);
arg0.writeString(title);
arg0.writeDouble(rating);
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Product createFromParcel(Parcel in) {
return new Product(in);
}
public Product[] newArray(int size) {
return new Product[size];
}
};
}


Caution:
1. The order of reading data from the Parcel in Parcel argument constructor must be the same as order of writing the data in the Parcel in the writeToParcel method.

Initializing the objects of the class and sending as intent.

products = new ArrayList<Product>();
for(int i=0;i<3;i++) {
Product product = new Product();
product.setAsin("asin " + i);
product.setTitle("Title " + i);
product.setDescription("description " + i);
product.setRating(4.5);
product.setImageUrl("imageUrl");
products.add(product);
}
intent.putExtra("products", products);
startActivity(intent);


Reading the data from the intent

Intent intent = getIntent();
ArrayList<Product> products = intent.getExtras().getParcelableArrayList("products");
for(int i=0;i<products.size();i++) {
Toast.makeText(getApplicationContext(), "Got: " + String.valueOf(products.get(i).getAsin()), Toast.LENGTH_SHORT).show();
}

Thursday, March 27, 2014

Interview Questions and their approach

1. Find if there is a loop in a single linked-list and if yes, remove it.
Approach-1: Take a slow and fast pointer and see if they ever meet.
Time Complexity: O(n)
Space Complexity: O(1)

Approach-2: Go on storing all the addresses and if a stored address is met.
Time Complexity: O(n)
Space Complexity: O(n)

Approach-3: Reverse the linked-list. And then again reverse the linked-list.
Time Complexity: O(n)
Space Complexity: O(1)

2. Given an array of integers, find the pair of integers that add up to a given number.
Approach-1: Store the integers in a hash-table and see if the difference is present in the hash-table.
Time Complexity: O(n)
Space Complexity: O(n)

Approach-2: Find all the possible pairs in the array.
Time Complexity: O(n-square)
Space Complexity: O(1)

Approach-3:
a) Sort all the numbers (Time: nlogn Space: O(1)).
b) At each element, search for the difference using binary search in the same array (Time: nlogn Space: O(1))
Total time-complexity: O(nlogn)

3. Given a single linked-list, find out if it is a palindrome or not.
Approach-1: Push half the nodes in a stack and traverse the rest of the linked-list, while popping the elements from the stack. At any point, if there is a mismatch, then it is not a palindrome.
Time Complexity: O(n)
Space Complexity: O(n)

Approach-2: Reach the mid element of the linked-list. And reverse the rest of the linked-list. Then traverse both the linked lists in parallel. At any point, if there is a mismatch, then it is not a palindrome.
Time Complexity: O(n)
Space Complexity: O(1)

4. Given a string S and a number n, rotate the string the given number of times.
Example input: S: abcdef, n: 2
Example output: efabcd

Approach-1: Start a loop at twice the given number from the end of the string. Swap the next n characters with the nth character from current position. Repeat this till the starting point reaches the beginning of the string.
Time Complexity: O(n)
Space Complexity: O(1)

Approach-2: Reverse the entire string. Then reverse the characters between 0 to n. And then reverse the characters between n+1 to length of string.
Time Complexity: O(n)
Space Complexity: O(1)  
  

Saturday, February 15, 2014

Uploading data from a file to WordPress blog using Selenium and Java-2

Doctors

package com.nueve.review.hreview;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.w3c.dom.Element;

public class PostWriter {
private static WebDriver driver;
private static String baseUrl;
private static boolean acceptNextAlert = true;
private static StringBuffer verificationErrors = new StringBuffer();
private static LinkedHashMap<String,String> columnsMap = new LinkedHashMap<String,String>();
private static Boolean upload = true;//Variable that controls the uploading part of code.
private static String[] membershipArray = {"Membership1", "Membership2", "Membership3", "Membership4"};
private static String[] experienceArray = {"Experience 1", "Experience 2", "Experience 3", "Experience 4"};

public static void main(String[] args) {
//Template creation.
columnsMap.put("Unique ID", "");
columnsMap.put("First Name", "Dr. <first name>");
columnsMap.put("Middle Name", " <middle name>");
columnsMap.put("Last Name", " <last name>");
columnsMap.put("Main area of Expertise", " works as a <main area of expertise>");
columnsMap.put("Name of Hospital 1", " in <name of hospital>");
columnsMap.put("H1 Employment Type", " as <H1 Employement type>.");
columnsMap.put("H1 Fee (Rs.)", "\nConsultation Fee: Rs. <fee>");
columnsMap.put("Other areas of expertise", "\nIs also specialized in <other areas of expertise>\n");
columnsMap.put("Graduation Degree", "\nGraduation: <graduation degree>");
columnsMap.put("Graduation College", " <graduation college>");
columnsMap.put("Post Graduation Degree", "\nPost graduation: <post graduation degree>");
columnsMap.put("Post Graduation Area", "-<Post Graduation Area>");
columnsMap.put("Post Graduation College", " <Post Graduation College>");
columnsMap.put("Specialization Degree", "\nSpecialization: <Specialization degree>");
columnsMap.put("Specialization Area", " <specialization college>");
columnsMap.put("Specialization College", "-<Specialization Area>");
columnsMap.put("Super Specialization Degree", "\nSuper Specialization: <Super Specialization degree>");
columnsMap.put("Super Specialization Area", "-<super specialization area>");
columnsMap.put("Super Specialization College", " <Super Specialization College>");
String priorExperienceString = "\n\n<strong>Prior Experience:</strong>\n";
columnsMap.put("Total Experience","<total experience>\n");
for(int i = 0; i < experienceArray.length; i++) {
String key = experienceArray[i];
String value = "<" + experienceArray[i] + ">\n";
columnsMap.put(key, value);
}
String awardsString = "\n\n<strong>Awards and Membership:</strong>\n";
columnsMap.put("Awards and Recognitions", "<Awards and Recognitions>");
for(int i = 0; i < membershipArray.length; i++) {
String key = membershipArray[i];
String value = "<" + membershipArray[i] + ">\n";
columnsMap.put(key, value);
}
String otherHospitalsString = "\n\n<strong>Other Hospitals where doctor is available:</strong>\n";
columnsMap.put("Name of Hospital 2", " <Name of Hospital 2>");
columnsMap.put("H2 Employment Type", " as <H2 Employment Type>");
columnsMap.put("H2 Fee (Rs.)", "\nConsultation fee: Rs. <h2 fee>.\n");
columnsMap.put("Name of Hospital 3", " <Name of Hospital 3>");
columnsMap.put("H3 Employment Type", " as <H3 Employment Type>");
columnsMap.put("H3 Fee (Rs.)", "\nConsultation fee: Rs. <h3 fee>.\n");

String[] column = new String[10];
String csvFileName = "/Users/dsourabh/Downloads/Sample Data 26Jan14.csv";
//String csvFileName = "/Users/dsourabh/Documents/SampleDoctor.csv";
try {
BufferedReader csvReader = new BufferedReader(new FileReader(csvFileName));
StringTokenizer stringTokenizer = null;
String curLine = csvReader.readLine();
int fieldCount = 0;
String[] csvFields = null;
if(curLine != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
if(fieldCount > 0)
{
csvFields = new String[fieldCount];
int i=0;
while(stringTokenizer.hasMoreElements())
csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
}
}
if(upload) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://nueve.co.in/doctors/");
//Logging in and opening the Admin page.
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys("username");
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("password");
driver.findElement(By.id("wp-submit")).click();
}
int cnt = 1;
while((curLine = csvReader.readLine()) != null)
{
System.out.println("Doctor: "+cnt);
cnt++;
StringBuilder titleString = new StringBuilder();
StringBuilder sb = new StringBuilder();
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
LinkedHashMap<String, String> valuesMap = new LinkedHashMap<String, String>();
//System.out.println("fieldCount = "+fieldCount);
if(fieldCount > 0)
{
int i=0;
while(stringTokenizer.hasMoreElements())
{
try
{
String curValue = String.valueOf(stringTokenizer.nextElement());
//System.out.println(curValue);
valuesMap.put(csvFields[i], curValue);
}
catch(Exception exp)
{
//System.out.println(csvFields[i]);
exp.printStackTrace();
}
i++;
}
if(valuesMap.get("First Name") != null && !valuesMap.get("First Name").equals("blank")) {
titleString.append("Dr. ");
titleString.append(valuesMap.get("First Name"));
}
if(valuesMap.get("Middle Name") != null && !valuesMap.get("Middle Name").equals("blank")) {
titleString.append(" ");
if(valuesMap.get("First Name").equals("blank")) {
titleString.append("Dr. ");
}
titleString.append(valuesMap.get("Middle Name"));
}
if(valuesMap.get("Last Name") != null && !valuesMap.get("Last Name").equals("blank")) {
titleString.append(" ");
if(valuesMap.get("First Name").equals("blank") && valuesMap.get("Middle Name").equals("blank")) {
titleString.append("Dr. ");
}
titleString.append(valuesMap.get("Last Name"));
}

Set<String> keySet = valuesMap.keySet();
Iterator<String> keySetIterator = keySet.iterator();

while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
try {
if(!valuesMap.get(key).equals("blank")) {
String templateValue = columnsMap.get(key);
String actualValue = templateValue.replaceAll("<(.*)>", valuesMap.get(key));
sb.append(actualValue);
}
if(key.equals("Super Specialization College")) {
Boolean toAppend = false;
for(int j = 0; j < experienceArray.length; j++) {
if(!valuesMap.get(experienceArray[j]).equals("blank")) {
toAppend = true;
}
}
if(!valuesMap.get("Total Experience").equals("blank")) {
toAppend = true;
}
if(toAppend) {
sb.append(priorExperienceString);
}
}
else if(key.equals(experienceArray[experienceArray.length - 1])) {
Boolean toAppend = false;
for(int j = 0; j < membershipArray.length; j++) {
if(!valuesMap.get(membershipArray[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(awardsString);
}
}
else if(key.equals(membershipArray[membershipArray.length - 1])) {
if(valuesMap.get("Name of Hospital 2") != null && !valuesMap.get("Name of Hospital 2").equals("blank")) {
sb.append(otherHospitalsString);
}
}
} catch (NullPointerException e){
System.out.println(key);
e.printStackTrace();
}
}
System.out.println(sb);
}
if(upload) {
baseUrl = "http://nueve.co.in/doctors/wp-admin/post-new.php";
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);

//baseUrl = "http://nueve.co.in/doctors/wp-admin/";
//Adding a new post with the required parameters.
//driver.get(baseUrl + "/doctors/wp-admin/");
driver.findElement(By.id("title-prompt-text")).click();
driver.findElement(By.id("title")).clear();
driver.findElement(By.id("title")).sendKeys(titleString);
//driver.findElement(By.id("content_ifr")).clear();

driver.findElement(By.id("content-html")).click();
driver.findElement(By.id("content")).clear();
driver.findElement(By.id("content")).sendKeys(sb);

/*
driver.findElement(By.id("acf-field-speciality")).clear();
driver.findElement(By.id("acf-field-speciality")).sendKeys("Speciality");
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
driver.findElement(By.id("acf-since")).click();
//driver.findElement(By.id("acf-since")).clear();
driver.findElement(By.id("acf-since")).sendKeys("24 Jan");
//driver.findElement(By.id("dp1390624043131")).click();
driver.findElement(By.id("acf-field-phone")).click();
driver.findElement(By.id("acf-field-phone")).clear();
driver.findElement(By.id("acf-field-phone")).sendKeys("99999999999");
driver.findElement(By.id("acf-field-address")).clear();
driver.findElement(By.id("acf-field-address")).sendKeys("Address");
*/
if (valuesMap.get("Main area of Expertise") != null && !valuesMap.get("Main area of Expertise").equals("blank")) {
driver.findElement(By.id("new-tag-post_tag")).clear();
driver.findElement(By.id("new-tag-post_tag")).sendKeys(valuesMap.get("Main area of Expertise"));
driver.findElement(By.cssSelector("input.button.tagadd")).click();
}

driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.linkText("Main")).click();
new Select(driver.findElement(By.id("ta_post_review_rating"))).selectByVisibleText("4");
driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.name("ta_post_repeatable[0][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][title]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][desc]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[1][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][title]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][desc]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[2][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][title]")).sendKeys("Waiting Time");
driver.findElement(By.name("ta_post_repeatable[2][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][desc]")).sendKeys("Waiting Time");
driver.findElement(By.name("ta_post_repeatable[2][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[3][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][title]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][desc]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][rating]")).sendKeys("0");

driver.findElement(By.id("in-category-105")).click();

synchronized (driver) {
try {
driver.wait(4000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

if(valuesMap.get("Unique ID") != null && !valuesMap.get("Unique ID").equals("blank")) {
driver.findElement(By.id("acf-field-index")).click();
driver.findElement(By.id("acf-field-index")).clear();
driver.findElement(By.id("acf-field-index")).sendKeys(valuesMap.get("Unique ID"));
}
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
if(valuesMap.get("First Name") != null && !valuesMap.get("First Name").equals("blank")) {
driver.findElement(By.id("acf-field-first_name")).click();
driver.findElement(By.id("acf-field-first_name")).clear();
driver.findElement(By.id("acf-field-first_name")).sendKeys(valuesMap.get("First Name"));
}
//driver.findElement(By.id("acf-since")).clear();
//driver.findElement(By.id("acf-since")).sendKeys("24 Jan");
//driver.findElement(By.id("dp1390624043131")).click();
if(valuesMap.get("Middle Name") != null && !valuesMap.get("Middle Name").equals("blank")) {
driver.findElement(By.id("acf-field-middle_name")).click();
driver.findElement(By.id("acf-field-middle_name")).clear();
driver.findElement(By.id("acf-field-middle_name")).sendKeys(valuesMap.get("Middle Name"));
}
if(valuesMap.get("Last Name") != null && !valuesMap.get("Last Name").equals("blank")) {
driver.findElement(By.id("acf-field-last_name")).click();
driver.findElement(By.id("acf-field-last_name")).clear();
driver.findElement(By.id("acf-field-last_name")).sendKeys(valuesMap.get("Last Name"));
}

synchronized (driver) {
try {
driver.wait(6000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
driver.findElement(By.id("publish")).click();
}
sb = null;
titleString = null;
}
if(upload) {
driver.close();
}
csvReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchElementException nse) {
nse.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Uploading data from a file to Wordpress blog using Selenium and Java-1

Hospitals

package com.nueve.review.hreview;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class HospitalPostWriter {
private static WebDriver driver;
private static String baseUrl;
private static boolean acceptNextAlert = true;
private static StringBuffer verificationErrors = new StringBuffer();
private static LinkedHashMap<String,String> columnsMap = new LinkedHashMap<String,String>();
private static Boolean upload = true;//Variable that controls the uploading part of code.
private static String[] contactNumbers = {"Alternate Contact Number 1","Alternate Contact Number 2"};
private static String[] membershipArray = {"Awards & Recognition", "Membership2", "Membership3"};
private static String[] emailIds = {"Email Id", "Alternate Email Id"};
private static String[] extensionNumbers = {"Extension Number 1", "Extension Number 2"};

private static String opps_map = "[oppso-map";
private static String map_id = " map_id=\"123\"";
private static String map_type = " map_type=\"ROADMAP\"";
private static String bubble = " bubble=\"\"";
private static String height = " height=\"350px\"";
private static String width = " width=\"400px\"";
private static String zoom = " zoom=\"14\"";
private static String lat = " lat=\"\"";
private static String lon = " lon=\"\"]";

//[oppso-map map_id="123" map_type="ROADMAP" bubble="" height="350px" width="400px" zoom="14" lat="12.95223" lon="77.52879"]

public static void main(String[] args) {
//Template creation.
columnsMap.put("Unique ID", "");
columnsMap.put("Hospital Name", "");
columnsMap.put("Full Address", " is located at ");
columnsMap.put("City", " ");
columnsMap.put("State", ", ");
columnsMap.put("Pincode", ", ");
columnsMap.put("Nearest Landmark", "\nNearest Landmark: ");
columnsMap.put("Locality", " in ");
columnsMap.put("Primary Contact Number", "\nFor booking appointments, please call ");

String alternateContactsString = "\n\nAlternative Contact Numbers\n";
for(int i = 0; i < contactNumbers.length; i++) {
String key = contactNumbers[i];
String value = "<" + contactNumbers[i] + ">\n";
columnsMap.put(key, value);
}

String emailString = "\nEmail ID: \n";
for(int i = 0; i < emailIds.length; i++) {
String key = emailIds[i];
String value = "<" + emailIds[i] + ">\n";
columnsMap.put(key, value);
}

String extensionString = "\n\nExtension Numbers: ";
for(int i = 0; i < extensionNumbers.length; i++) {
String key = extensionNumbers[i];
String value = "<" + extensionNumbers[i] + ">\n";
columnsMap.put(key, value);
}
columnsMap.put("Fax Number", "\nFax Number: ");
columnsMap.put("Hospital Website", "\nWebsite: ");

String aboutHospitalString = "\n\nAbout the hospital\n";

columnsMap.put("Hospital Description", "\n\n");
columnsMap.put("Hospital Speciality", "\n");

String awardsString = "\n\nAwards and Membership:\n";
for(int i = 0; i < membershipArray.length; i++) {
String key = membershipArray[i];
String value = "<" + membershipArray[i] + ">\n";
columnsMap.put(key, value);
}
columnsMap.put("Latitude", "\nLatitude: ");
columnsMap.put("Longitude", "\nLongitude: ");

String csvFileName = "/Users/dsourabh/Downloads/HospitalTrial.csv";
//String csvFileName = "/Users/dsourabh/Documents/SampleDoctor.csv";
try {
BufferedReader csvReader = new BufferedReader(new FileReader(csvFileName));
StringTokenizer stringTokenizer = null;
String curLine = csvReader.readLine();
int fieldCount = 0;
String[] csvFields = null;
if(curLine != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
if(fieldCount > 0)
{
csvFields = new String[fieldCount];
int i=0;
while(stringTokenizer.hasMoreElements())
csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
}
}
if(upload) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://nueve.co.in/doctors/");
//Logging in and opening the Admin page.
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys("username");
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("passsword");
driver.findElement(By.id("wp-submit")).click();
}
int cnt = 1;
while((curLine = csvReader.readLine()) != null)
{
System.out.println("Hospital: "+cnt);
cnt++;
StringBuilder mapString = new StringBuilder();
StringBuilder titleString = new StringBuilder();
StringBuilder sb = new StringBuilder();
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
LinkedHashMap<String, String> valuesMap = new LinkedHashMap<String, String>();
//System.out.println("fieldCount = "+fieldCount);
if(fieldCount > 0)
{
int i=0;
while(stringTokenizer.hasMoreElements())
{
try
{
String curValue = String.valueOf(stringTokenizer.nextElement());
//System.out.println(curValue);
valuesMap.put(csvFields[i], curValue);
}
catch(Exception exp)
{
//System.out.println(csvFields[i]);
exp.printStackTrace();
}
i++;
}
if(valuesMap.get("Hospital Name") != null && !valuesMap.get("Hospital Name").equals("blank")) {
titleString.append(valuesMap.get("Hospital Name"));
}

Set keySet = valuesMap.keySet();
Iterator keySetIterator = keySet.iterator();
//[oppso-map map_id="123" map_type="ROADMAP" bubble="" height="350px" width="400px" zoom="14" lat="12.95223" lon="77.52879"]
while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
try {
if(!valuesMap.get(key).equals("blank")) {
String templateValue = columnsMap.get(key);
String actualValue = templateValue.replaceAll("<(.*)>", valuesMap.get(key));
if(key.equals("Latitude")) {
sb.append("\n\n");
String actualLat = lat.replaceAll("<(.*)>", valuesMap.get("Latitude"));
String actualLon = lon.replaceAll("<(.*)>", valuesMap.get("Longitude"));
sb.append(opps_map + map_id + map_type + bubble + height + width + zoom + actualLat + actualLon);
break;
}
sb.append(actualValue);
}
if(key.equals("Primary Contact Number")) {
Boolean toAppend = false;
for(int j = 0; j < contactNumbers.length; j++) {
if(!valuesMap.get(contactNumbers[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(alternateContactsString);
}
}
else if(key.equals(contactNumbers[contactNumbers.length - 1])) {
Boolean toAppend = false;
for(int j = 0; j < emailIds.length; j++) {
if(!valuesMap.get(emailIds[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(emailString);
}
}
else if(key.equals(emailIds[emailIds.length - 1])) {
Boolean toAppend = false;
for(int j = 0; j < extensionNumbers.length; j++) {
if(!valuesMap.get(extensionNumbers[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(extensionString);
}
}
else if(key.equals("Hospital Website")) {
Boolean toAppend = false;
if((valuesMap.get("Hospital Description") != null && !valuesMap.get("Hospital Description").equals("blank"))
|| (valuesMap.get("Hospital Speciality") != null && !valuesMap.get("Hospital Speciality").equals("blank"))) {
toAppend = true;
}
if(toAppend) {
sb.append(aboutHospitalString);
}
}
else if(key.equals("Hospital Speciality")) {
Boolean toAppend = false;
if((valuesMap.get("Awards & Recognition") != null && !valuesMap.get("Awards & Recognition").equals("blank"))) {
toAppend = true;
}
if(toAppend) {
sb.append(awardsString);
}
}
} catch (NullPointerException e){
System.out.println(key);
e.printStackTrace();
}
}
System.out.println(sb);
}
if(upload) {
baseUrl = "http://nueve.co.in/doctors/wp-admin/post-new.php";
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);

//baseUrl = "http://nueve.co.in/doctors/wp-admin/";
//Adding a new post with the required parameters.
//driver.get(baseUrl + "/doctors/wp-admin/");
driver.findElement(By.id("title-prompt-text")).click();
driver.findElement(By.id("title")).clear();
driver.findElement(By.id("title")).sendKeys(titleString);
//driver.findElement(By.id("content_ifr")).clear();

driver.findElement(By.id("content-html")).click();
driver.findElement(By.id("content")).clear();
driver.findElement(By.id("content")).sendKeys(sb);

/*
driver.findElement(By.id("acf-field-speciality")).clear();
driver.findElement(By.id("acf-field-speciality")).sendKeys("Speciality");
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
driver.findElement(By.id("acf-since")).click();
//driver.findElement(By.id("acf-since")).clear();
driver.findElement(By.id("acf-since")).sendKeys("24 Jan");
//driver.findElement(By.id("dp1390624043131")).click();
driver.findElement(By.id("acf-field-phone")).click();
driver.findElement(By.id("acf-field-phone")).clear();
driver.findElement(By.id("acf-field-phone")).sendKeys("99999999999");
driver.findElement(By.id("acf-field-address")).clear();
driver.findElement(By.id("acf-field-address")).sendKeys("Address");
*/
if (valuesMap.get("Hospital Speciality") != null && !valuesMap.get("Hospital Speciality").equals("blank")) {
driver.findElement(By.id("new-tag-post_tag")).clear();
driver.findElement(By.id("new-tag-post_tag")).sendKeys(valuesMap.get("Hospital Speciality"));
driver.findElement(By.cssSelector("input.button.tagadd")).click();
}

driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.linkText("Main")).click();
new Select(driver.findElement(By.id("ta_post_review_rating"))).selectByVisibleText("4");
driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.name("ta_post_repeatable[0][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][title]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][desc]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[1][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][title]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][desc]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[2][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][title]")).sendKeys("Quality of facilities and equipments");
driver.findElement(By.name("ta_post_repeatable[2][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][desc]")).sendKeys("Quality of facilities and equipments");
driver.findElement(By.name("ta_post_repeatable[2][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[3][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][title]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][desc]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][rating]")).sendKeys("0");

driver.findElement(By.id("in-category-106")).click();
synchronized (driver) {
try {
driver.wait(4000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

if(valuesMap.get("Unique ID") != null && !valuesMap.get("Unique ID").equals("blank")) {
driver.findElement(By.id("acf-field-index")).click();
driver.findElement(By.id("acf-field-index")).clear();
driver.findElement(By.id("acf-field-index")).sendKeys(valuesMap.get("Unique ID"));
}
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
if(valuesMap.get("Hospital Name") != null && !valuesMap.get("Hospital Name").equals("blank")) {
driver.findElement(By.id("acf-field-full_name")).click();
//driver.findElement(By.id("acf-since")).clear();
driver.findElement(By.id("acf-field-full_name")).clear();
driver.findElement(By.id("acf-field-full_name")).sendKeys(valuesMap.get("Hospital Name"));
}
//driver.findElement(By.id("dp1390624043131")).click();
if(valuesMap.get("Full Address") != null && !valuesMap.get("Full Address").equals("blank")) {
driver.findElement(By.id("acf-field-full_address")).click();
driver.findElement(By.id("acf-field-full_address")).clear();
driver.findElement(By.id("acf-field-full_address")).sendKeys(valuesMap.get("Full Address"));
}
//driver.findElement(By.id("acf-field-address")).clear();
//driver.findElement(By.id("acf-field-address")).sendKeys("Address");

synchronized (driver) {
try {
driver.wait(6000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
driver.findElement(By.id("publish")).click();
}
sb = null;
titleString = null;
}
if(upload) {
driver.close();
}
csvReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchElementException nse) {
nse.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Sunday, February 2, 2014

Given a sorted array, convert it into a balanced binary search tree

#include<iostream>
using namespace std;

struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* createnode(int x)
{
struct node* new_node=new struct node;
new_node->data=x;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}
int height(struct node* root)
{
if(root==NULL)
{
return 0;
}
else
{
int lheight=1+height(root->left);
int rheight=1+height(root->right);
return lheight>rheight?lheight:rheight;
}
}
struct node* createBST(int *A, int low, int high)
{
if(low>high)
{
return NULL;
}
else
{
int mid = (low + high)/2;
struct node* root = createnode(A[mid]);
root->left = createBST(A, low, mid - 1);
root->right = createBST(A, mid + 1, high);
return root;
}
}
void levelorderprint(struct node* root,int level)
{
if(root && level==0)
{
cout<<root->data<<" ";
}
else if(root)
{
levelorderprint(root->left,level-1);
levelorderprint(root->right,level-1);
}
}
void levelorder(struct node* root)
{
int h=height(root);
for(int i=0;i<h;i++)
{
levelorderprint(root,i);
cout<<endl;
}
}
int main()
{
int A[6] = {1,2,3,4,5,6};
int n = 5;
struct node* treeRoot = createBST(A,0,n-1);
levelorder(treeRoot);
}

Tuesday, January 28, 2014

JavaScript 1





var aax_size='300x250';

var aax_pubname = 'studio444-20';

var aax_channel = '1100';

var aax_passback = "";



Sunday, January 19, 2014

Magic array

Problem
Given an array of +ve as well as -ve numbers, find out whether it is possible or not to convert it to 0 by adding/subtracting operations on all the elements.

Examples
arr[]={1,2,3}
1+2-3 = 0
Hence ans = YES

arr[]={3,6,2}
3+6-2 != 0
3-6-2 !=0
-3-6-2 !=0
-3-6+2 !=0
-3+6-2 !=0
-3+6+2 !=0
3-6+2 !=0
3+6+2 !=0
Hence ans= NO

Input/Output format:
First line will contain the number of test-cases t.
First line of each test-case contains a non-negative number n, the number of elements in the array.
Next line contains n positive or negative numbers.

#include <iostream>
using namespace std;

int main()
{
int t,A[100],n;
cin>>t;
while(t--)
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>A[i];
}
int sum=0;
for(int i=0;i<n;i++)
{
sum+=A[i];
}
if(sum == 0)
{
cout<<"Possible"<<endl;
}
else if(n > 1 && sum % 2 == 0)
{
cout<<"Possible"<<endl;
}
else
{
cout<<"Not possible"<<endl;
}
}
return 0;
}


Input:
5
5
1 2 3 4 5
4
-4 3 2 1
1
1
1
2
1
0

Output:
Not possible
Possible
Not possible
Not possible
Possible

Saturday, January 18, 2014

Given a binary tree find out whether the left and right sub-trees are mirror images of each other

#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* createnode(int x)
{
struct node* new_node=(struct node*)malloc(sizeof(struct node*));
new_node->data=x;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}

int isMirror(struct node* node1, struct node* node2)
{
if(node1 == NULL && node2 != NULL)
{
return 0;
}
else if(node1 != NULL && node2 == NULL)
{
return 0;
}
else if(node1 == NULL && node2 == NULL)
{
return 1;
}
else if(node1->data != node2->data)
{
return 0;
}
return isMirror(node1->left, node2->right) && isMirror(node1->right, node2->left);
}


int height(struct node* root)
{
if(root==NULL)
{
return 0;
}
else
{
int lheight=1+height(root->left);
int rheight=1+height(root->right);
return lheight>rheight?lheight:rheight;
}
}

void levelorderprint(struct node* root,int level)
{
if(root && level==0)
{
printf("%d ",root->data);
}
else if(root)
{
levelorderprint(root->left,level-1);
levelorderprint(root->right,level-1);
}
}

void levelorder(struct node* root)
{
int h=height(root);
for(int i=0;i<h;i++)
{
levelorderprint(root,i);
printf("\n");
}
}

int main()
{
struct node* root1=createnode(1);
root1->left=createnode(2);
root1->right=createnode(2);
root1->left->right=createnode(4);
root1->left->left=createnode(3);
root1->right->right=createnode(3);
root1->right->left=createnode(4);
//root1->right->right->left=createnode(8);
printf("The input tree is:\n");
levelorder(root1);
int result = 0;
result = isMirror(root1, root1);
if(result == 1)
{
printf("The left and right subtrees are mirror images\n");
}
else
{
printf("The left and right subtrees are not mirror images\n");
}
return 0;
}

Sunday, January 5, 2014

Setting up Apache, PHP and MySQL on MAC

Useful links:
http://coolestguidesontheplanet.com/install-configure-apache-mysql-php-phpmyadmin-osx-10-8-mountain-lion/

http://coolestguidesontheplanet.com/how-to-install-php-mysql-apache-on-os-x-10-6/