Thursday, January 6, 2011

SVN

Create a repository -
$svnadmin create ~/repo

Copy existing project files to repository
$svn import ~/project file:///home/username/repo/project

Create a sandbox project directory under version control
$svn co file:///home/repo/project
This will create a directory project in the current directory.

Commit changes
$svn ci -m "...."

Go back to the 3rd commit
$svn revert -r 3

Update local sandbox
$svn update

Tuesday, January 4, 2011

SWIG ; Lets u call C++ functions from Python

SWIG simply put is a program that allows you to call C/C++ functions from Python. What that essentially means you get both the speed of C/C++ and the amazing scriptability of Python. Installing SWIG on debian systems is simple as

$ sudo apt-get install swig

Python.h which is required next can be got by

$ sudo apt-get install build-essential

Lets say you have a C++ file euler.cpp. In order to use SWIG include the following header file #include </usr/include/python2.6/Python.h> at the first line of euler.cpp. Now in order to call euler.cpp functions from Python, we first need to create a interface file called euler.i with the following lines

%module euler
%{
       #include "euler.cpp"
%}
%include "euler.cpp"

The next thing to do is to generate the Python module euler.py by the following commands

$ swig -c++ -python euler.i
$ g++ -c -O3 -fPIC euler_wrap.cxx -I /usr/include/python2.6/
$ g++ -shared -O3 euler_wrap.o -o _euler.so

If there are no errors in your code or what you typed you should see euler.py in the directory. Run python and call your required function by
>>> import euler
>>> euler.requiredfunction()

Glovepie Wiimote as controller for PC

// Type your program here, or click the GUI tab to autogenerate it!

key.X = Wiimote.One
key.C = Wiimote.Two
key.Down = Wiimote.Left
key.Up = Wiimote.Right
key.Right = Wiimote.Down
key.Left = Wiimote.Up
key.Space = Wiimote.A
key.Enter = Wiimote.Plus
var.zz = Wiimote.A

wait 100 ms

Glovepie Wiimote Nunchuk as mouse

if Wiimote.Nunchuk.JoyX<-0.21
Mouse.CursorPosX=Mouse.CursorPosX-9
end if

if Wiimote.Nunchuk.JoyX>0.21
Mouse.CursorPosX=Mouse.CursorPosX+9
end if

if Wiimote.Nunchuk.JoyY<-0.21
Mouse.CursorPosY=Mouse.CursorPosY-9
end if

if Wiimote.Nunchuk.JoyY>0.21
Mouse.CursorPosY=Mouse.CursorPosY+9
end if

if Wiimote.Nunchuk.ZButton=1
Mouse.LeftButton=1
wait 250 ms
Mouse.LeftButton=0
end if

if Wiimote.Nunchuk.CButton=1
Mouse.RightButton=1
wait 250 ms
Mouse.RightButton=0
end if

Glovepie Mouse click

// Type your program here, or click the GUI tab to autogenerate it!
x=1
if x
   Mouse.CursorPosX=1021
   Mouse.CursorPosY=684
   Mouse.LeftButton=1
   wait 200 ms
   Mouse.LeftButton=0
   Mouse.LeftButton=1
   wait 200 ms
   Mouse.LeftButton=0
end if

How to make 1080p Blu Ray movies work

Note - VLC may not work for such high quality mkv files 
# Hehe this is circa 2008. So now it should not be a issue.

1.Install coreavc codec
2.Install gom player
3.gom player settings
Preferences -> Filter -> Use Windows Media source filter
Under Disable Filters -> Enable Quick play
4.Install Audio codec

Recording audio ; windows

from Tkinter import *
root = Tk()

import tkSnack
tkSnack.initializeSnack(root)
import time
f=open("E:\\record.wav","wb")
f.close()

r=tkSnack.Sound(file='e:/record.wav',frequency=11025,channels=1)
r.record(fileformat="WAV")

import threading

def pause():
    r.stop()
    print "Recording over"
   
t=threading.Timer(120.0,pause)
t.start()

VOIP Linux

import socket
import ossaudiodev
dev=ossaudiodev.open("rw")
dev.setfmt(dev.getfmts())
dev.channels(2)
dev.speed(11025)

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 5555))
serversocket.listen(5)
(clientsocket, address)=serversocket.accept()
clientsocket.send("You are connected")
while 1:
        frame=dev.read(500)
        clientsocket.send(frame)
        dev.write(clientsocket.recv(500))   

Send sms from PC with bluetooth sockets

import socket
import messaging

s=socket.socket(socket.AF_BT,socket.SOCK_STREAM)
s.connect(("00:19:7e:d8:ec:4b", 1))

msg=s.recv(160)  # SMS limit is 160 chars
messaging.sms_send('9978453256', msg)

Bluetooth sockets on S60 Nokia mobiles

import socket
import e32
s=socket.socket(socket.AF_BT,socket.SOCK_STREAM)
s.connect(("00:19:7e:d8:ec:4b", 1))
while 1:
    cmd=s.recv(1000)
    e32.reset_inactivity()
    print cmd
    try:
        x=eval(cmd)
        print x
    except:
        try:
            exec(cmd)
        except:
            print "Wrong command"

Get process id ; PID ; windows

import os
def getpid(s):
    im='"IMAGENAME eq %s"'%s
    cmd="tasklist /V /FI %s"%im
    s=os.popen(cmd).read()

    pid=[]

    i=491  ## really bad magic number
    while True:
        pid.append(s[i])
        if s[i+1]==' ':
            break
        i+=1

    return int(pid)

Check for a Key press ; windows ;

import win32api
import time
f=open("D:\\key.txt","w")
keys=[]
            
while len(keys)<50: # Just record the first 50 key presses
    for i in range(1, 256):
        if win32api.GetAsyncKeyState(i):
            if i==8: # 8 is the backspace character.
                keys.pop()
            else:
                keys.append(chr(i))
        time.sleep(0.1)  

for key in keys:
    f.write(key)

f.close()

## If you can understand this code u probably know what it really does and
## hence should not use it !!

Bluetooth sockets using pybluez

#Server Code

import bluetooth

port = 1
server_sock=bluetooth.BluetoothSocket(bluetooth.L2CAP)
server_sock.bind(("",port))
server_sock.listen(1)

client_sock, address = server_sock.accept()
print "Accepted connection from ",address
msg=raw_input("#")
client_sock.send(msg)

#Client Code

import bluetooth

s=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
s.connect(("00:19:7e:d8:ec:4b", 1))
print s.recv(1000)

Webcam ; Videocapture ; windows ; snapshot

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')
def snap(a):
    n="snap" + "%d"%a + ".jpg"
    cam.saveSnapshot(n)   

SSL socket

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 5865))

ssl_sock = socket.ssl(s)
# Set a simple HTTP request -- use httplib in actual code.
ssl_sock.write("""GET / HTTP/1.0\r\n
                            Host: www.verisign.com:443\r\n
                            Proxy-Connection: keep-alive\r\n\r\n""")

data = ssl_sock.read()
print data


# Note that you need to close the underlying socket, not the SSL object.
del ssl_sock
s.close()

Activate a process ; Simulate a keyboard press

import win32com.client

import win32api
import win32con
import os


def maximizewindow():
    # hack for alt+space+x 
    ctrl=0xa2
    alt=0x12
    space=0x20
    X=0x58
    enter=0x0d
    shift=0x10
    win32api.keybd_event(alt,0,0,0)
    win32api.keybd_event(space,0,0,0)
    time.sleep(0.3)
    win32api.keybd_event(alt,0,win32con.KEYEVENTF_KEYUP,0)
    win32api.keybd_event(space,0,win32con.KEYEVENTF_KEYUP,0)
    time.sleep(0.5)
    win32api.keybd_event(X,0,0,0)
    win32api.keybd_event(X,0,win32con.KEYEVENTF_KEYUP,0)


def click(i,j):
    win32api.SetCursorPos((i,j))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,i,j,0,0)
    time.sleep(0.2)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,i,j,0,0)
   
os.chdir('C:\Program Files\Internet Explorer')
os.popen('start iexplore.exe http://192.168.1.1/')

shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate(pid)

FFmpeg video to images

ffmpeg.exe -y -i E:\pcd.mpg -an -r 15 -y -s 640x480 video%d.jpg

UDP sendto recvfrom

import socket
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
msg="GET http://www.google.co.in/ HTTP/1.0\r\n\r\n"
s.sendto(msg,("www.google.co.in", 80))
reply, add=s.recvfrom(1024)

# Hehe nice try cause google accepts only tcp !!

Find IPv6 address on windows

import os
f=os.popen("ipconfig").read()
z=f.split()
has_ipv6 = False
ip6=""
for i in range(len(z)):
    if z[i]=='IPv6':
        has_ipv6 = True
    if has_ipv6:
        if len(z[i])>20:
            if z[i].find('::')>0:
                ip6=z[i]
                break

Smoothen images ; PIL ; Laplacian

from PIL import Image
from numpy import zeros
import time
#file=raw_input('Enter file name ')
im=Image.open('sourceimage.jpg')
im=im.convert("L")
pix=im.load()

N=1
t1=time.time()
for k in range(N):
    for i in range(1,im.size[0]-1):
        for j in range(1,im.size[1]-1):
            sum=(pix[i-1,j]+pix[i+1,j]+pix[i,j-1]+pix[i,j+1])
            pix[i,j]=int(0.25*sum)

t2=time.time()
print t2-t1
im.save('smoothenedimage.jpg')

Webcam Videocapture pygame psyco (Make ur code fast!!)

import pygame
from PIL import Image

import psyco
psyco.full()


from VideoCapture import Device

cam=Device()
cam.setResolution(320,240)
im=cam.getImage()

pygame.init()
screen=pygame.display.set_mode(im.size)

pix=im.load()
a=pygame.image.frombuffer(im.tostring(), im.size, im.mode)
screen.blit(a, (0,0))
pygame.display.flip()

Show image PIL Tkinter

from PIL import Image as Im
from Tkinter import *
import Image

import ImageTk

# See PIL for valid modes
print x,y,mode
im=Im.new(mode, (x, y))
root=Tk()
canvas = Canvas(root, height=y, width=x)
canvas.pack(side=LEFT,fill=BOTH,expand=1)
root.update()

# st is a image string.
im.fromstring(st)
photo = ImageTk.PhotoImage(im)
item = canvas.create_image(0,0,anchor=NW, image=photo)
root.update()

Screen shot in windows

import ImageGrab


a=ImageGrab.grab()
a.mode
x, y=a.size
st=a.tostring()

ImageGrab.grab().save('screenshot.jpg')
a.save('screenshot.jpg')


# print screen in windows aka screenshot

Simulate mouse click and check button press

import win32api
import win32con
import time

#Code to simulate mouse click
x,y = win32api.GetCursorPos()
win32api.SetCursorPos((x, y))
#Left click
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
time.sleep(0.05)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
#Right click
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,x,y,0,0)
time.sleep(0.05)
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,x,y,0,0)

#Code to check if mouse was clicked
a=win32api.GetAsyncKeyState(0x01)
b=win32api.GetAsyncKeyState(0x02)
if a==1:
    # Left button is pressed
else:
    # Left button not pressed
if b==1:
    # Right button pressed 
else:
    # You know

Thread

import os
import thread

def run_vlc():
    os.chdir("C:\Program Files\VideoLAN\VLC")
    os.system("vlc")
def close_vlc():
    #code to close vlc

thread.start_new_thread(run_vlc, ())

t=threading.Timer(120.0,close_vlc)
t.start()