August 19, 2014

Automating menial Browser activity using Selenium

No comments:
Today I stumbled across a marvelous Framework called Selenium which does browser automation. It lets you programmatically control a web browser session which can be used for automating tests or controlling browser to perform menial works.

Here's a small snippet that I put together for myself just to try out selenium's python bindings. Yes, python is the language of my choice currently! :) Selenium binds of various languages are available on their official website at : http://www.seleniumhq.org/

What this script does is open a third party website: way2sms.com, log me in using my username, password and then send a message to any number of my choice. All of this is done programmatically! So all I've to do is fire up a console and enter my username, password, a mobile number and a message and selenium will handle the rest. Of course, this is just an example and one can use this to perform a variety of tasks, boring or otherwise.


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from datetime import datetime

def send(username, password, mobile, message):
  
  driver = webdriver.Firefox()
  driver.get("http://site25.way2sms.com/content/index.html")

  driver.find_element_by_id("username").send_keys(username)
  driver.find_element_by_id("password").send_keys(password)
  driver.find_element_by_id("loginBTN").send_keys(Keys.RETURN)

  driver.execute_script("goToMain('s')")
  driver.execute_script("loadSMSPage('sendSMS')")

  frame = driver.find_element_by_id("frame")
  driver.switch_to_frame(frame)

  driver.find_element_by_id("mobile").send_keys(mobile)
  driver.find_element_by_id("message").send_keys(message)
  driver.find_element_by_id("Send").send_keys(Keys.RETURN)

  driver.switch_to_default_content()
  driver.close()

You can install selenium python binding using:

sudo easy_install selenium

Since I hacked this together in hurry, it doesn't include any comments but the code should be self explanatory and easy to follow because all it does is find a web element (like an input box or a button) and send it a sequence of keys ( string value of action keys like RETURN ).

Automating tasks on a third party website requires a bit of inspection of web elements and javascripts, even stylesheet at times. This can be done using built-in web inspectors available with most of the modern browsers like Chrome, Firefox. As of now Firebug is the inspector of my choice.

Keep automating!
Read More

August 10, 2014

Write a python program for creating virtual file system on Linux environment.

1 comment:

# Developer: Manish Raj (technoslab@gmail.com)
import shelve, time, sys

class File(object):

    def __init__(self, name, type, parent=None, text=''):
        self.list = []
        self.name = name
        self.type = type
        self.time = int(time.time())
        self.parent = parent
        self.text = text

    def is_file(self, name):
        for node in self.list:
            if node.name == name:
                return True
        return False

    def is_dir(self, name):
        if(self.is_file(name)) and self.get(name).type == 'dir':
            return True
        return False

    def get(self, name):
        for node in self.list:
            if node.name == name:
                return node
        
    def add(self, name, type, text=''):
        self.list.append(File(name, type, self, text))
             
    def remove(self, name):
        self.list.remove(self.get(name))
            
    def rename(self, name):
        self.name = name

    def copy(self, src, dest):
        src = self.get(src)
        self.add(dest, src.type, src.text)

    def stat(self):
        print 'Listing', self.name
        for node in self.list:
            print 'Name:', node.name, '; Created:', node.time, '; Type:', node.type
            
    def read(self):
        print 'Reading file:', self.name
        print self.text

class FileSystem(object):
    
    COMMANDS = ['ls', 'mkdir', 'chdir', 'cd', 'rmdir', 'create', 'read', 'rm', 'mv', 'cp', 'help', 'exit']
    
    def __init__(self):
        self.io = shelve.open('file.sys', writeback=True)
        if self.io.has_key('fs'):
            self.root = self.io['fs']
        else:
            self.root = File('/', 'dir')
        self.curr = self.root

    def mkdir(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'mkdir - make directory'
            print 'usage: mkdir <dir_name>'
        else:
            name = cmd[1]
            if self.curr.is_file(name) == False:
                self.curr.add(name, 'dir')
            else:
                print name, ' - already exists.';

    def chdir(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'chdir - change directory.'
            print 'usage: chdir <dir_name>'
        else:
            name = cmd[1]
            if name == '..':
                if self.curr.parent is not None:
                    self.curr = self.curr.parent
            elif self.curr.is_dir(name):
                self.curr = self.curr.get(name)
            else:
                print name, ' - invalid directory.'

    def rmdir(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'rmdir - remove directory'
            print 'usage: rmdir <dir_name>'
        else:
            name = cmd[1]
            if self.curr.is_dir(name):
                self.curr.remove(name)
                print 'Directory deleted.'
            else:
                print name, ' - invalid directory.'
                
    
    def rm(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'rm - remove file'
            print 'usage: rm <file_name>'
        else:
            name = cmd[1]
            if self.curr.is_file(name) and not self.curr.is_dir(name):
                self.curr.remove(name)
                print 'File deleted.'
            else:
                print name, ' - invalid file.'

    def ls(self, cmd):
        if(len(cmd) > 1):
            print 'ls - list stats'
            print 'usage: ls'
        self.curr.stat()

    def create(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'create - create a file'
            print 'usage: create <file_name>'
        else:
            name = cmd[1]
            self.curr.add(name, 'file', raw_input('Enter file context: '))
            
    def read(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'read - read a file'
            print 'usage: read <file_name>'
        else:
            name = cmd[1]
            if self.curr.is_file(name):
                self.curr.get(name).read()
            else:
                print name, 'invalid file'

    def mv(self, cmd):
        if len(cmd) < 3 or cmd[1] == '':
            print 'mv - rename a file'
            print 'usage: mv <old_name> <new_name>'
        else:
            old_name = cmd[1]
            new_name = cmd[2]
            if self.curr.is_file(old_name):
                self.curr.get(old_name).rename(new_name)
            else:
                print old_name, 'invalid file'

    def cp(self, cmd):
        if len(cmd) < 3 or cmd[1] == '':
            print 'cp - copy a file'
            print 'usage: cp <src> <dest>'
        else:
            src = cmd[1]
            dest = cmd[2]
            if self.curr.is_file(src):
                self.curr.copy(src, dest)
            else:
                print src, 'invalid file'
    
    def save(self):
        self.io['fs'] = self.root
        self.io.sync()
            
    def help(self, cmd):
        print 'COMMANDS: mkdir, ls, chdir, rmdir, create, read, mv, cp, rm, exit'

    def exit(self, cmd):
        sys.exit(0)

def main():
    fs = FileSystem()
    while True:
        cmd = raw_input('> ').split(' ');
        method = None
        try:
            method = getattr(fs, cmd[0])
        except AttributeError:
            print 'Invalid command. Type "help".'
        if method is not None and cmd[0] in FileSystem.COMMANDS and callable(method):
            method(cmd)
            fs.save()
        else:
            print 'Invalid command. Type "help".'
main()
Read More

August 07, 2014

Capture/Record webcam, desktop and audio under Ubuntu 14.04

No comments:


Bash script:

fname=`date +"%d.%m.%Y_%H:%M:%S_%P"`.'_screencast.mp4'
vlc --qt-minimal-view v4l2:///dev/video0 &
vlc --qt-minimal-view screen:// :screen-fps=20 :screen-follow-mouse :live-caching=300 :input-slave=alsa://hw:0,0 :sout="#transcode{vcodec=h264,vb=384,fps=5,acodec=mpga}:duplicate{dst=std{mux=mp4,access=file,dst='$fname'}}" &

These set of commands start two instances of VLC.
The first command fires up a minimal view of VLC with video source "/dev/video0" (the default location of webcamera in most general cases).

The second command starts another minimal VLC instance with video from screen:// (desktop) and audio from default built-in microphone "hw:0,0". Output is encoded and saved in current directory as an mp4 file.

Recording stops when you close VLC instances.
Read More

February 09, 2014

OOMP Assignment#4

No comments:
/*
Aim: Design a C++ Class "Complex" with data members for real and imaginary part. Provide
default and parametrized constructors. Write a program to perform arithmetic operations
of two complex numbers using operator overloading (using either member functions or
friend functions).
*/

#include <iostream>
#include <math.h>
using namespace std;

class Complex{
 public:
   int a;
   int b;
   Complex(){
     Complex(0, 0);
   }
   Complex(int x, int y){
     a = x;
     b = y;
   }
   void get(){
     cout << endl << "Enter real part: ";
     cin >> a;
     cout << endl << "Enter imaginary part: ";
     cin >> b;
     print();
   }
   void print(){
     cout << endl << a << " " << (b >= 0 ? "+" : "-") << " " << abs(b) << "i";
   }
   Complex operator + (Complex c){
     return Complex(a + c.a, b + c.b);
   }
   Complex operator - (Complex c){
     return Complex(a - c.a, b - c.b);
   }
   Complex operator *(Complex c){
     return Complex(a * c.a - b * c.b, a*c.b + c.a * b);
   }
   Complex operator /(Complex c){
     return Complex((a * c.a + b * c.b)/(c.a * c.a + c.b * c.b), (b * c.a - a * c.b)/(c.a * c.a + c.b * c.b));
   }
};

int main(){
 int choice;
 Complex c1, c2, c3;
 do{
   cout << endl << "-- Complex Numbers --";
   cout << endl << "1. Input numbers";
   cout << endl << "2. Display numbers";
   cout << endl << "3. Add";
   cout << endl << "4. Subtract";
   cout << endl << "5. Multiply";
   cout << endl << "6. Divide";
   cout << endl << "7. Exit";
   cout << endl << "Enter your choice: ";
   cin >> choice;
   switch(choice){
     case 1 : c1.get(); c2.get(); break;
     case 2 : c1.print(); c2.print(); break;
     case 3 :
       c3 = c1 + c2;
       cout << endl << "Result of addition: ";
       c3.print();
       break;
     case 4 :
       c3 = c1 - c2;
       cout << endl << "Result of subtraction: ";
       c3.print();
       break;
     case 5 :
       c3 = c1 * c2;
       cout << endl << "Result of multiplication: ";
       c3.print();
       break;
     case 6 :
       c3 = c1 / c2;
       cout << endl << "Result of division: ";
       c3.print();
       break;
     default : cout << endl << "Invalid choice!"; break;
   }
 }while(choice != 7);
 return 0;
}

/*
---------------------------------------
             OUTPUT
---------------------------------------

-- Complex Numbers --
1. Input numbers
2. Display numbers
3. Add
4. Subtract
5. Multiply
6. Divide
7. Exit
Enter your choice: 1

Enter real part: 10

Enter imaginary part: 20

10 + 20i
Enter real part: -15

Enter imaginary part: -25

-15 - 25i
-- Complex Numbers --
1. Input numbers
2. Display numbers
3. Add
4. Subtract
5. Multiply
6. Divide
7. Exit
Enter your choice: 2

10 + 20i
-15 - 25i
-- Complex Numbers --
1. Input numbers
2. Display numbers
3. Add
4. Subtract
5. Multiply
6. Divide
7. Exit
Enter your choice: 3

Result of addition:
-5 - 5i
-- Complex Numbers --
1. Input numbers
2. Display numbers
3. Add
4. Subtract
5. Multiply
6. Divide
7. Exit
Enter your choice: 4

Result of subtraction:
25 + 45i
-- Complex Numbers --
1. Input numbers
2. Display numbers
3. Add
4. Subtract
5. Multiply
6. Divide
7. Exit
Enter your choice: 5

Result of multiplication:
350 - 550i
-- Complex Numbers --
1. Input numbers
2. Display numbers
3. Add
4. Subtract
5. Multiply
6. Divide
7. Exit
Enter your choice: 6

Result of division:
0 + 0i
-- Complex Numbers --
1. Input numbers
2. Display numbers
3. Add
4. Subtract
5. Multiply
6. Divide
7. Exit
Enter your choice: 7
*/
Read More

OOMP Assignment#3

No comments:
/*
Aim: Develop an object oriented program in C++ to create a database of the personnel
information system containing the following information: Name, Date of Birth, Blood
group, Height, Weight, Insurance Policy, number, Contact address, telephone number,
driving license no. etc Construct the database with suitable member functions for
initializing and destroying the data viz constructor, default constructor, copy, constructor,
destructor, static member functions, friend class, this pointer, inline code and dynamic
memory allocation operators-new and delete.
*/

#include <iostream>
#define MAX_RECORDS 50
using namespace std;

class Information{
 friend class Records;
 private:
   string name, dateOfBirth, bloodGroup, contactAddress;
   float height, weight;
   double policyNumber, telephoneNumber, licenseNumber;
 public:
   Information(string n, string dob, string bg, string ca, int h, int w, double pn, double tn, double ln){
     this->name = string(n);
     this->dateOfBirth = string(dob);
     this->bloodGroup = string(bg);
     this->contactAddress = string(ca);
     this->height = h;
     this->weight = w;
     this->policyNumber = pn;
     this->telephoneNumber = tn;
     this->licenseNumber = ln;
   }
   Information(){
     Information("", "", "", "", 0, 0, 0, 0, 0);
   }
   Information(const Information& otherInfo){
     this->name = otherInfo.name;
     this->dateOfBirth = otherInfo.dateOfBirth;
     this->bloodGroup = otherInfo.bloodGroup;
     this->contactAddress = otherInfo.contactAddress;
     this->height = otherInfo.height;
     this->weight = otherInfo.weight;
     this->policyNumber = otherInfo.policyNumber;
     this->telephoneNumber = otherInfo.telephoneNumber;
     this->licenseNumber = otherInfo.licenseNumber;
   }
   inline void acceptValues(){
     cout << endl << "Enter personal details: ";
     cout << endl << "Name: ";
     cin >> this->name;
     cout << endl << "Date Of Birth: ";
     cin >> this->dateOfBirth;
     cout << endl << "Blood Group: ";
     cin >> this->bloodGroup;
     cout << endl << "Contact Address: ";
     cin >> this->contactAddress;
     cout << endl << "Height: ";
     cin >> this->height;
     cout << endl << "Weight: ";
     cin >> this->weight;
     cout << endl << "Policy Number: ";
     cin >> this->policyNumber;
     cout << endl << "Telephone Number: ";
     cin >> this->telephoneNumber;
     cout << endl << "License Number: ";
     cin >> this->licenseNumber;
   }
   inline void display(){
     cout << endl << "Personal details: " << endl;
     cout << endl << "Name: " << this->name;
     cout << endl << "Date Of Birth: " << this->dateOfBirth;
     cout << endl << "Blood Group: " << this->bloodGroup;
     cout << endl << "Contact Address: " << this->contactAddress;
     cout << endl << "Height: " << this->height;
     cout << endl << "Weight: " << this->weight;
     cout << endl << "Policy Number: " << this->policyNumber;
     cout << endl << "Telephone Number: " << this->telephoneNumber;
     cout << endl << "License Number: " << this->licenseNumber << endl;
   }
};

class Records{
 private:
   Information * records[MAX_RECORDS];
 public:
   static int COUNT;
   static int getCount(){
     return COUNT;
   }
   static void incCount(){
     COUNT++;
   }
   void add(){
     records[Records::getCount()] = new Information();
     records[Records::getCount()]->acceptValues();
     Records::incCount();
   }
   void display(){
     for(int i = 0; i < Records::getCount(); i++){
       records[i]->display();
     }
   }
   ~Records(){
     for(int i = 0; i < Records::getCount(); i++){
       delete records[i];
     }
   }
};

int Records::COUNT = 0;

int main(){
 int choice;
 Records * rs = new Records();
 do{
   cout << endl << "-- Personal Information --";
   cout << endl << "1. Add information";
   cout << endl << "2. Display information";
   cout << endl << "3. Exit";
   cout << endl << "Your choice: ";
   cin >> choice;
   switch(choice){
     case 1 : rs->add(); break;
     case 2 : rs->display(); break;
   }
 }while(choice != 3);
 delete rs;
 return 0;
}

/*
---------------------------------------
             OUTPUT
---------------------------------------

-- Personal Information --
1. Add information
2. Display information
3. Exit
Your choice: 1

Enter personal details:
Name: Man

Date Of Birth: 4/4/1994

Blood Group: O+

Contact Address: Pune

Height: 160

Weight: 65

Policy Number: 7766554433

Telephone Number: 9988776655

License Number: 123456890

-- Personal Information --
1. Add information
2. Display information
3. Exit
Your choice: 1

Enter personal details:
Name: Tau

Date Of Birth: 5/5/1995

Blood Group: AB-

Contact Address: Mumbai

Height: 160

Weight: 45

Policy Number: 1234554321

Telephone Number: 9988006677

License Number: 0987654321

-- Personal Information --
1. Add information
2. Display information
3. Exit
Your choice: 2

Personal details:

Name: Man
Date Of Birth: 4/4/1994
Blood Group: O+
Contact Address: Pune
Height: 160
Weight: 65
Policy Number: 7.76655e+009
Telephone Number: 9.98878e+009
License Number: 1.23457e+008

Personal details:

Name: Tau
Date Of Birth: 5/5/1995
Blood Group: AB-
Contact Address: Mumbai
Height: 160
Weight: 45
Policy Number: 1.23455e+009
Telephone Number: 9.98801e+009
License Number: 9.87654e+008

-- Personal Information --
1. Add information
2. Display information
3. Exit
Your choice: 3
*/
Read More