Monday, November 21, 2016

Remove the line numbers in source code using notepad++


A sample code with line numbers:

01<!DOCTYPE html>
02<html>
03<head>
04 <meta http-equiv="X-UA-Compatible" content="IE=edge">
05 <meta charset="utf-8">
06 <title>Hello App!</title>
07 <script>


To remove the numbers in each line of code, do the following:


  • Copy the code into notepad++
  • Type Ctrl + H
  • Under Search Mode choose Regular Expression.
  • In Find What :Enter ^\d+
  • Leave the Replace with: as blank
  • Now click Replace All


Now the code looks like:


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>Hello App!</title>
<script>



Saturday, November 12, 2016

It ebooks Rest Api

Itebooks which is one of the popular sources for programming books.

They have exposed couple of REST Apis as GET request.

One of it is send request to it based on the book id.

Below is the code to get the details of the book:


Monday, November 7, 2016

Huffman Decode

Huffman coding assigns code words to fixed length characters based on frequency.
More frequent characters are given shorter code words and less frequent with longer.


Java program for a given string that has encoded and a tree structure,  decode the characters .

To find Nth maximum salary

To find nth max salary using correlated query

Saturday, October 22, 2016

DB details from properties file using Java


Reusuable class to get db details from properties file.
Now the helper function that reads from the property file and return the value from the property file.

Sunday, September 25, 2016

git commands

List of git commands that we might need when working with git.

In local machine after installing git:

git log #Log of our repo

git clone repo #To take a copy from repository in git hub to our local machine

git checkout <commitid> #To a detached headstate

For details on detached head state  please check this link

git diff <first commit id> < second commit id>

git init

git status

--Commands to add files to staging area

git add 'filename1'
git add 'filename2'

git status

git commit -m "Comment"

git diff <workingdir> <Staging dir>

git diff --staged #to diff between staging and repo

git reset --hard #to revert to previous commit ,to make master point to some previous commit

Branches:

git branch <branch-name>
git checkout <branch-name>

git log --graph --oneline branchname branchaname

[git checkout  -b <branchname>

equals to following two commands

git branch <newbranchname>
git checkout <newbranchname>]

Merge :

git merge <b1> <b2>

Diff between a commit and parent with out knowing it's parent id

git show <commitid>

Delete a branch:

git branch -d <branchname>

Remote branch:

git remote  add origin url
git remote
git remote -v

git push origin master

Pull branch:

git pull origin master

git log  #to update the remote to local and check if updates happens.

Fork a repo:

Merging remote changes:

If remote and local has changes on same file.During conflicts, use fetch.

git fetch origin
git merge master origin/master

origin/master points to the remote repository on git hub

Pull request commands:

git branch newbranchname
git checkout newbranchname

git checkout master

git add 'filename'
git commit
git push origin <newbranchname>


Clone Remote and cross -repo conflicts:

git remote add upstream 'original repo'
git checkout master
git pull upstream master

git checkout 'anotherbranch'

origin - forked repo
upstream - original repo

Merge newbranch with master

git merge master 'anotherbranch'

git add
git commit
git push origin 'anotherbranch'

Delete a remote branch:

git branch --remote
git push origin --delete <branch-name> 


List of Programming languages from A- Z

A - Ada
B - Bash
C - C
D - D
E - Erlang
F - Fortan
G - go
H - Haskell
I - Icon
J - Java
K - K
L - Lisp
M - MATLAB
N - NSIS
O - Octave
P - Python
Q - Q
R - R
S - Scala
T - Tcl
U - Unix
V - Verilog
W - Whitespace
X - xBase
Y - Yorick
Z - ZShell

Project Euler #8 - Largest Product in a series - Python

n = map(int, raw_input().split()) #To read the number of digits and 
                                  #k consecutive numbers
num = int(raw_input()) # To read the digit
#print n[1]
#print num
stri = str(num)
product = 0
for i in xrange(len(stri) - n[1] + 1):
        temp = 1
        k = i
        for j in range(n[1]):        
            temp = temp * int(stri[k])
            k = k + 1
           
        if(temp > product):
            product = temp
            #print product
print product  

Saturday, August 27, 2016

Longest Increasing Sequence using python


import sys
import copy

#Binary search
def binary(s, num):
#print "in binary s:"  + str(s)
#print "in binary num:" + str(num)
    l = len(s)
    mid = l/2
    #print "in binary s:" + str(s)
    #print "in binary num:" + str(num)
    #print "s[mid]:" + str(s[mid])
    if((l!=0) and  (l == 1)):
    if(s[mid] < num):
    return s[mid]

    if((l!=0) and (l != 1)):
   if ((s[mid] >= num) and (s[mid - 1 ] < num)):
       return s[mid - 1]
   elif ((s[mid] > num) and (s[mid - 1] > num)):
       return binary(s[:mid -1] , num)
   else:
       return binary(s[mid:], num)
     
 
 
t = int(raw_input())
for p in xrange(0,t):
    n = int(raw_input())
    arr = map(int, raw_input().split())
#maxlen in  worst case would be 1 and end element index is 0.
    maxlen = 1
    bestend = 0

    s = []
    LIS = []
    s.append(arr[bestend])
    LIS.append(s)
    #LIS[-1].append(s)
    #print s
    #print LIS

    #To get last elements of all lists
    #print max(LIS, key=len)[-1]
    # to get the last element of the max length in the list
     
 
    for i in xrange(1,n):
        #print "arr[i]:" + str(arr[i])
        #print "list end element to compare:" + str(max(LIS, key=len)[-1])
        if(arr[i] > max(LIS, key=len)[-1]):
         
            seq = copy.deepcopy(LIS)
         
            max(seq, key=len).append(arr[i])        

            LIS.append(max(seq, key=len))
            #print "post updated LIS:" + str(LIS)
         
         
     
        else:
         
            seq = copy.deepcopy(LIS)
            last_elem = [x[-1] for x in seq]
            val_greater_elem = binary(sorted(last_elem), arr[i])
            if val_greater_elem in last_elem:
                ind = last_elem.index(val_greater_elem)
                #print "Index of ele:" + str(ind)# to get index of the ele to append
                #print "seq ind to append:" + str(seq[ind][-1])
                seq[ind].append(arr[i])#replace element
                #print "updated seq:" + str(seq)
                #print "updated seq index:" + str(seq[ind])
                #print "Length of seq:" + str(len(seq[ind]))
                len_of_updated = len(seq[ind])
                k = [x for x in LIS if (len(x) == len_of_updated)]
                [LIS.remove(l) for l in k]
                #print "post discard LIS:" + str(LIS)
                LIS.append(seq[ind])
                #print "post updated LIS:" + str(LIS)
     
    print len(max(LIS, key=len))
    print "Final subseq:" + str(max(LIS, key=len))
 
     
stdin:
1
16
0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15            

Output:
6
Final subseq: [0 2 6 9 11 15]
    

Binary search to find largest smaller element than given value python

import sys
def binary(s, num):
    l = len(s)
    mid = l/2
    #print "in binary s:" + str(s)
    #print "in binary num:" + str(num)
    #print "s[mid]:" + str(s[mid])
    if((l!=0) and  (l == 1)):
     if(s[mid] < num):
     return s[mid]
        #else:
#return None
    if((l!=0) and (l != 1)):
    if ((s[mid] >= num) and (s[mid - 1 ] < num)):
        return s[mid - 1]
    elif ((s[mid] > num) and (s[mid - 1] > num)):
        return binary(s[:mid -1] , num)
    else:
        return binary(s[mid:], num)


lst = [8,0]

print binary(sorted(lst), 4)

Output:

0

Sunday, June 19, 2016

Artificial Intelligence using python

The below code is to reach a goal in a board game with robot at position with value 'r' and goal with value 'g' in the row* column board.

Below are the conventions for the code to solve the problem.


m - size of grid
grid - position of the board(in row * col)
g - goal position
r - robot current postion in the board


#!/bin/python
def find_m_position(grid):
for row in range(m):
for col in range(m):
if grid[row][col] == 'r':
return (row,col)

def find_p_postion(grid):
for row in range(m):
for col in range(m):
if grid[row][col] == 'g':
return (row, col)


def PathtoGoal(n,grid):
#print all the moves here
#pass
row_m, col_m = find_m_position(grid)
row_p, col_p = find_p_postion(grid)

while((row_m != row_p) and (col_m != col_p)):
diff_row = row_m - row_p
diff_col = col_m - col_p
if(diff_row < 0):
print "DOWN"
row_m = row_m + 1


else:
print "UP"
row_m = row_m - 1

if(diff_col > 0):
print "LEFT"
col_m = col_m - 1
else:
print "RIGHT"
col_m = col_m + 1


return None

m = input()

grid = []
for i in xrange(0, m):
grid.append(raw_input().strip())

#print grid

PathtoGoal(m,grid)



Sunday, March 6, 2016

Project Euler - Problem 2 - Sum of even Fibonaaci numbers

def euler2(n):

su = 0
lst = []
for i in xrange(1,n,3):
    if(i == 1):
        res = 2
    elif (i == 4):
        res = 8
    else:
        res = 4* lst[-1]+ lst[-2]


    if(res < n):
        lst.append(res)

    else:
        break


print sum(lst)

Count the Squares between any two numbers

import math

def get_squares(n1, n2): #Given n1, n2 are the numbers both inclusive

       print int(math.floor(math.sqrt(n2)) - math.ceil(math.sqrt(n1))) + 1

Sunday, February 21, 2016

Cashless transaction with local Transport - part 3


package JavaSMSProject;


import java.net.*;

public class CopyOfSMSclass {
public void sendSMS(Integer amount, Integer bal, String recipient) {
        try {
                //String recipient = "918888899999"; // Receipietnt mobile number
                String message = "Your account has been deducted with" + amount + "your current balance is" + bal;
                String username = "xxx";  //Username that you have registered with OzekiNG
                String password = "xxx"; // Password that you have registered with OzekiNG
                String originator = "918888866666"; // Sender mobile number

                String requestUrl  = "http://127.0.0.1:9501/api?action=sendmessage&" +
    "username=" + URLEncoder.encode(username, "UTF-8") +
    "&password=" + URLEncoder.encode(password, "UTF-8") +
    "&recipient=" + URLEncoder.encode(recipient, "UTF-8") +
    "&messagetype=SMS:TEXT" +
    "&messagedata=" + URLEncoder.encode(message, "UTF-8") +
    "&originator=" + URLEncoder.encode(originator, "UTF-8") +
    "&serviceprovider=HTTPServer0" +
    "&responseformat=html";
             
                //GSMModem1



                URL url = new URL(requestUrl);
                HttpURLConnection uc = (HttpURLConnection)url.openConnection();

                System.out.println(uc.getResponseMessage());

                uc.disconnect();

        } catch(Exception ex) {
                System.out.println(ex.getMessage());

        }
}


}


This class triggers SMS gateway and sends the information to the customer.

A basic application to work with SMS along with cashless transaction with local transport and it has few enhancements to work on.






Cashless transaction with local Transport - part 2

Readdatabase.class

package JavaSMSProject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



public class ReadDatabase {

public void writeToExcel(String fileName, String uid, String amount) throws IOException {

Integer cellValue = 0;
Integer cellAmount = 0;
Integer bal = 0;
Integer phoneNumber = 0;

FileInputStream fsIP= new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook(fsIP);
XSSFSheet sheet = workbook.getSheetAt(0);

int count = sheet.getPhysicalNumberOfRows();
System.out.println(count);

List<String> list = new ArrayList<String>();
/*int size = list.size(); */

  for(int i=0; i < count - 1; i++){

  XSSFRow row1 = sheet.getRow(i + 1);
  Cell cell1 = row1.getCell(0);

  cellValue = (int)Math.round(cell1.getNumericCellValue());

  System.out.println("UserId:" + cellValue);

  String matchuid = cellValue.toString();

  if(uid.equalsIgnoreCase(matchuid)){

  Cell cell2 = row1.getCell(1);

  cellAmount = (int)Math.round(cell2.getNumericCellValue());

  System.out.println("Amount:" + cellAmount);

  bal = cellAmount - Integer.parseInt(amount);

  System.out.println("Bal remaning:" + bal);

  Cell cell3 = row1.getCell(2);

  phoneNumber = (int)Math.round(cell3.getNumericCellValue());

  System.out.println("Phone number:" + phoneNumber);

  cell2.setCellValue(bal.doubleValue());

 
  CopyOfSMSclass sms = new CopyOfSMSclass();
  sms.sendSMS(Integer.parseInt(amount), bal, phoneNumber.toString());

  break;



  }//if


  //list.add(cell1.getStringCellValue());

  }//for

  System.out.println("Sorry no such user found");

  fsIP.close();
 try (FileOutputStream outputStream = new FileOutputStream(new File(fileName))) {
 workbook.write(outputStream);
}

catch (FileNotFoundException e) {
   
       e.printStackTrace();
   }


}

}

Cashless transaction with local Transport

The goal of this project is to send SMS to people who have been registered with an local transport organization where  they pay amount in advance and travel through out the year as  long as they have balance available.

For this project I have used OzekiNG to simulate SMS.


Here are the class files:

Deduct balance.class


package JavaSMSProject;

import java.io.IOException;
import java.util.Scanner;


public class Deductbalance {


public static void main(String[] args) throws IOException {

Scanner in  = new Scanner(System.in);
System.out.println("Enter the user id:");
String user_id = in.next();
//in.close();

Scanner in2  = new Scanner(System.in);
System.out.println("Enter the amount:");
String amount = in2.next();
//sin2.close();

String workingDir = System.getProperty("user.dir");
String fileName = workingDir + "\\resources\\Localtransportdatabase.xlsx";
//String path =

ReadDatabase rd = new ReadDatabase();

rd.writeToExcel(fileName, user_id, amount);


}





}

Other classes are in next posts.





Reading csv file using python

import unicodecsv

with open(filename , 'rb') as f:
    read_data = unicodecsv.DictReader(f)
    data = list(read_data )
   
print data [:]

Saturday, January 23, 2016

Print triangle shape using python


k = 5
for j in range(5 ,0, -1):
 if(j < k):
  print ((" " * (k - j)) + ("*" + " ") * (j))
 else:
  print  ("*" + " ") * (j)
#print "Done with descending"
for x in range(1, 6):

 if(x < k):
  print ((" " * (k - x - 1)) + ("*" + " ") * (x + 1))

Program to print shape "X" in python

k = 5
for j in range(5 ,0, -1):
 if(j < k):
  #print ((" " * (k - j)) + ("*" + " ") * (j))
  if (j - 2 > 0):
    print ((" " * (k - j)) + "*" + (" " * ((j - 2) * 2 + 1)) + "*")
  else:
   print ((" " * (k - j)) + ("*" + " ") * (j))
 else:
  #print  ("*" + (" " * (j -2))) * 2
  print "*" + (" " * ((j - 2) * 2 + 1)) + "*"
#print "Done with descending"
for x in range(1, 6):

 if(x < k):

  if(x - 2 >= 0):
   print ((" " * (k - x - 1)) + "*" + (" " * ((x - 1) * 2 + 1)) + "*")
  else:
   print ((" " * (k - x - 1)) + ("*" + " ") * (x + 1))
 
   
Output:

*       *
 *     *
  *   *
   * *
    *
   * *
  *   *
 *     *
*       *