Sunday, March 6, 2011

Some Near duplicate detection

I've been reading a lot about Data Mining recently and today I came across Shingling, a method for near duplicate detection.

The algorithm is simple, it creates a set of consecutive substrings of fixed length on 2 two documents and calculates the Jaccard distance between these two sets. The Jaccard distance is a number between 1 and 0, inclusive, calculated as the size of the intersection of two sets divided by the size of their union. i.e |A ∩ B| / |A U B|. If this distance is 1 then the sets are equal.

Here's a simple implementation of the technique in python:

shingles = lambda s: set(s[i:i+3] for i in range(len(s)-2))
jaccard_distance = lambda seta, setb: len(seta & setb)/float(len(seta | setb))

a = raw_input("Original text: ")
b = raw_input("Other text: ")
sa = shingles(a)
sb = shingles(b)
print "These texts are %.2f%% similar" % (jaccard_distance(sa, sb)*100)

Another article I came across is MinHash which is used for the same purpose.

Saturday, November 20, 2010

A Python script using Tornado web server with the Twitter Streaming API

So today I decided to play with Tornado the open source version of a scalable, non-blocking web server which powers FriendFeed. While doing so I discovered it will probably be cool to play with the Twitter streaming API as well and write a Python script that uses both.

Here's the result of my experiment:

from tornado.httpclient import HTTPClient, HTTPRequest
import simplejson

def handle_tweet_stream(response):
    try:
        # Print the parsed twitter stream.
        print simplejson.loads(response)
    except ValueError:
        return
    print

if __name__ == '__main__':
    req = HTTPRequest(
        "http://stream.twitter.com/1/statuses/filter.json", 
        body='track=google',
        method = "POST",
        auth_username = "username",
        auth_password = "xxxxxxx",
        streaming_callback=handle_tweet_stream)

    client = HTTPClient()
    client.fetch(req)

Thursday, October 21, 2010

Lessons learned from working in large scale

Before my internship with Google, I wasn't a big fan of unit tests, logging and cloud computing. Now I can say there's a degree of doubt in me when I see some new code without tests and that this code claims to do the right thing.

When you're running code in parallel on 1000's of machines in the cloud, machines whose physical location you don't know and machines you don't have shell access to, your idea of project development changes dramatically. Things like logging and unit testing become your friends.

A good blog on this topic is found on Matt Welsh's blog

Thursday, March 25, 2010

A one line Python Quine

OK, Here's a one line Python program that prints its own source code:

s='s=%r;print s%%s';print s%s

This wikipedia article on Quines is a very good place to learn how these things work

Saturday, February 27, 2010

One line quicksort in Python

Here's a one line quicksort in python. I came up with this idea after looking at a 2 lines implementation in Haskel

qsort = lambda seq: [] if not seq else qsort(filter(lambda n: n<=seq[0], seq[1:]))+[seq[0]]+qsort(filter(lambda n: n>seq[0], seq[1:]))

Monday, December 21, 2009

5 Handy python functions (lambdas)

Here's a list of 5 handy python lambda's you may need when solving a quick maths problem

1) The sum of all integers from 1 to n
triangle = lambda n: n*(n+1)/2

2) Factorial
factorial = lambda n: 1 if n<2 else n*factorial(n-1)
3) Get odd numbers
odds = lambda n: [k for k in range(1,n,2)]
4) Test whether a number is prime

is_prime = lambda n: False if n<2 else (0 not in [n%k for k in range(2,int(n**.5)+1)])
A number is prime when it has no factor other than 1 and itself. To determine whether the number is a prime, we need to check that it doesn't leave a reminder of 0 when divided by each number in the range of [2..square root of the number].

5) Primes sieve
This function returns the list of primes in the range [2..N]. It's the most cryptic of all but it makes use of the previous function to add a number to the generated list.
sieve = lambda n: [k for k in range(2,n+1) if (0 not in [k%i for i in range(2,int(k**.5)+1)])]
It could also be written as:

is_prime = lambda n: False if n<2 else (0 not in [n%k for k in range(2,int(n**.5)+1)])
sieve = lambda n: [k for k in range(2,n+1) if is_prime(k)]

Tuesday, December 15, 2009

Let’s cook a simple yet powerful HTML Editor with Delphi

N.B. You might need to read Using Scintilla in Delphi 7 before reading this tutorial.

I'm cooking a simple WYSIWYG HTML Editor which allows editing a webpage from design mode and source mode just like FrontPage and DreamWeaver do. Things like auto-completion, Style editor and flash are beyond the scope of this tutorial.

When cooking a simple IDE, syntax highlighting is the ingredient that makes it different from a text editor like notepad. If syntax highlighting never existed and all we had was notepad, I don't think I would have learnt HTML.

Step 1: Warm the interface
Drop a TScintilla (from the Scintilla tab), a TWebBrowser (from the Internet tab) , 3 buttons and a TOpenDialog on the form.
Set the language of the Scintilla control to HTML. So you should have something like this:


The first button will be for loading the file you want to edit, the second for refreshing the Preview and the third for switching to design mode.

Step 2 (Add some code)
In order to get juice out of the TWebBrowser component, you must add the mshtml unit to the code. This unit is interesting because it exposes some of the stuff that make up the engine used by Internet Explorer and other Microsoft programs. An expert HTML user will be very familiar with some of the methods and properties in this module. Here’s the code:
implementation
{$R *.dfm}
uses
  mshtml;
Step 2 (Loading the HTML file)
the first button will simply load an html file onto the webbrowser. Add this code for the Click Event on button1:
procedure TForm1.Button1Click(Sender: TObject);
var
  doc: IHTMLDocument2;
begin
  if not OpenDialog1.Execute then
     Exit;

  WebBrowser1.Navigate(OpenDialog1.FileName);
  doc:= WebBrowser1.Document as IHTMLDocument2;

  while doc.readyState <> 'complete' do Application.ProcessMessages;

  Scintilla1.Lines.Text:= doc.body.innerHTML;
end;
To load the file I used WebBrowser1.Navigate(OpenDialog1.FileName);
Because I’ll need to retrieve the text from the WebBrowser at some stage, I used a IHTMLDocument2 interface to allow me to read the innerHTML of the document’s body. The head isn’t much needed here. Unfortunately the outerHTML property of the body is read-only. This pauses a problem because I can’t edit attributes set in the tag. You can use file handling routines or another method to be able to access the full source code but we'll stick to this simple method from its simplicity.

The line while doc.readyState <> 'complete' do Application.ProcessMessages; is useful because we’ll get an exception if we try to use the body element because it becomes ready.

Running the program should give you something like this:



Step 3 (I can smell it)
Now I can edit the html but nothing will happen if I try to preview.
So to connect the two controls, I’ll write the code for button2. It copies the text  from the scintilla control into the innerHTML of the document’s body.
procedure TForm1.Button2Click(Sender: TObject);
var
  doc: IHTMLDocument2;
begin
  doc:= WebBrowser1.Document as IHTMLDocument2;
  doc.body.innerHTML:= Scintilla1.Lines.Text;
end;
Now you can test the source code editor. But get the WYSISWYG part we got to the Next step…

Step 4 (The food is ready)
The last button will switch the designMode ‘on’ for the WebBrowser:
procedure TForm1.Button3Click(Sender: TObject);
var
  doc: IHTMLDocument2;
begin
  doc:= WebBrowser1.Document as IHTMLDocument2;
  doc.designMode:= 'on';
end;
 OK, That's it! We get this:

Using Scintilla in Delphi 7

Scintilla is a cool open source text editing control which supports syntax highlighting, code folding, auto-indentation, line numbers and many more features.

A list of projects using scintilla can be found on their website (http://www.scintilla.org/ScintillaRelated.html).
To use Scintilla in Delphi you must install Delphi Scintilla Interface Components
 a.k.a delphisci which is no longer under development but since Delphi 7 itself is older, this shouldn’t be a problem.

Step 0
I’ll use the following names in this tutorial:
 - DELPHI_INSTALLATION_FOLDER: The folder where your Delphi is installed
 - SYSTEM32: C:\Windows\System32
 - DELPHI_SCI_FOLDER: The folder where you unzip delphisci

Step 1 (Getting ready)
Get a copy of delphisci from sourceforge, unzip it and inside the unzipped folder, there should be a zip file called scilexer_precompiled_171CVS which contains scilexer.dll (the only external dependency) and put this scilexer.dll in SYSTEM32 if there isn’t one yet.

Step 2 (Installation)
In DELPHI_SCI_FOLDER, there's file names INSTALL which has the instructions for installing delphisci. Follow those instructions. If you struggle with that make sure you:
  1. Compiled the right project group for the version of Delphi you are using.
  2. Installed the package into Delphi (Components->Install Package-> [choose scitD7.bpk from DELPHI_INSTALLATION_FOLDER\Projects\Bpl or go to Tools->Environment Options->Library and ckeck where your Bpl Output Directory is])
Step 3 (Successfully running it)
If you successfully followed those instructions you should have a Scintilla tab on the components pallette but if you try to run any project using these Scintilla components you get a “[Fatal Error] … File not found: SciLexer.dcu”. That happens because you haven’t added the DELPHI_SCI_FOLDER \d7dcu folder to the Environment yet so Delphi is unable to locate these.

Step 3.14
To add the DELPHI_SCI_FOLDER \d7dcu folder to the Environment I’d normally create a folder in DELPHI_INSTALLATION_FOLDER\Scintilla and copy all the files from DELPHI_SCI_FOLDER \d7dcu into this new folder.

Step 3.5
Now on Delphi, go to Tools->Environment Options->Library and add DELPHI_INSTALLATION_FOLDER\Scintilla to the Library Path

Step 4 (Testing)
Now to test the installation, create a new application, drop some Scintilla controls to the form and Run it.


Step 5 (Using syntax highlighting)
When you first drop a TScintilla components on a form, it has no language set and getting the syntax highlighting to work took some working until I realised that you have to Right click on the control -> Select Prefered Languages -> Choose a language and press OK. Then on the property editor, expand the LanguageManager and on the SelectedLanguage drop-down pick the language you chose earlier.
And that's it!


Proceed to Let’s cook a simple yet powerful HTML Editor with Delphi for some action.

FIN

Tuesday, January 6, 2009

How to get a 3G modem working on Ubuntu 8.04 and other ubuntu's

In a blog post at tectonic that shows how to access to the internet with a 3G card through vodafone-mobile-connect-card-driver, I left a comment for those people struggling to get a permanent connection...

The instructions are found here

Here's my addition:

1. Plug in the card and restart the computer
2. On a terminal type: dir /dev/ttyUSB* and make sure you get something like this:
/dev/ttyUSB0
/dev/ttyUSB1
I found that the software seems to work perfectly only when /dev/ttyUSB0 and /dev/ttyUSB1 both refer to your 3G card. Other ttyUSB's don't seem to work for me
3. type sudo poff to make sure that all previous connections are closed. I used sudo because the vodafone-mobile-connect-card-driver-for-linux violates many permission rules when run as a normal user (the documentation told me that). Therefore sudo will grant him all the rights he needs.
4. type sudo vodafone-mobile-connect-card-driver-for-linux-debug so that you can see what’s going on. If the program seems to stop printing stuff on the terminal without having printed your contacts list yet, Try closing it and repeat steps 3 and 4.

Enjoy the web!

How to download Ubuntu packages from windows without dependency problems

I've finally managed to download ubuntu packages from windows without worrying about unsatisfied dependencies.

Today I woke up with one aim: download eclipse. But the problem is that eclipse comes with a host of dependencies, so looking over them in Synpatic, I saw this link that says "Generate downlaod script"
1. Mark the required package for installation
2. Generate a download script and remove the first line that says "#!/bin/sh"
3. Download wget for windows from http://users.ugent.be/~bpuype/wget/#download
4. Add the ".bat" extension to the script you generated
5. On a windows machine, double click on the script and watch it as it works its way through the packages.

wget, Linux, Ubuntu, Synaptic, these things are cool!

Friday, September 12, 2008

How to download music or videos online. (Without RealPlayer)

How to download music/video from websites which will just not let you save their contents on your computer using the menu File->Save as...

Ever wonderer how to download a funny video you're watching online? Well there's a solution called “Real Player” but before I discovered that I always had suspecions concerning internet streams.

Last year I asked a friend to download a video on YouTube for me. His answer was shoking but interesting. He told me: “The computer boffin is out of his mind. He thinks that it's possible to download stuff off YouTube”

This answer shocked me. It revealed my ignorance concerning these streaming flash videos. Still I answered with an arrogant tone: “Sure you can, all you need is to write a little program that captures the stream”.

Here's my theoretical solution which works with Internet Explorer 6 and 7. I still have to explore Firefox – I just don't have enough freedom, bandwidth and time to write a program that automates this but it shouldn't be hard to write.
All you need is patience.

Step 1: Know your browser. IE stores temporary files in a super hidden folder which accumulates lots of junk as you make your way through the net. I presume these files accelerate things like refresh. The mysterious folder is under YOURUSERNAME\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\Content.IE5 or YOURUSERNAME\Local Settings\temporary internet files\content.ie5
Firefox (on my compter at least) stores its cache at YOURUSERNAME\AppData\Local\Mozilla\Firefox\Profiles\ejomzlqb.default\Cache
For the sake of simplicity I'll call content.ie5 Cache

Step 2: Clear the cache. As you surf the net this folder only gets larger. It can reach a Gig or more without you noticing so I recommand clearing all temporary internet files and manually deleting all the subfolders/files in Cache before doing your thing.

Step 3: Go to the page you wanna download the video from and let the video play until it reaches the end

Step 4: Close your webbrowser immediately and search for the largest file in all of Cache's child folders. This largest file should normally be the video file which is generally encoded in FLV format. In case of music files it's often .MP3 files. So to make it play on your computer just add the appropriate extension to your file (i.e .FLV for videos, .mp3 for music) et Voila! this method works for almost anything for me be it video or audio. When it doesn't work there's a probability the file is encoded differently so just play with common media formats like .swf, .wmv, .mp4 etc... or simply open the file with something like notepad++ and check the header.

My friend's challenge was a good one! He helped me download more internet streams than I ever imagined. Fortunately Real Media released a plugin for IE users which allows them to download any FLV video. But this plugin doesn't always appear when you want it...