Since I haven’t posted here in a while, I figured I’d whip up this example real quick. It illustrates the usage of the random function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| #!/usr/bin/python
import random
from time import time
def generateWord():
char_array = 'abcdefghijklmnopqrstuvwxyz'
random.seed(time())
word = ''
for i in range(0, 8): # 8 letter word
word += char_array[random.randint(0, 25)]
return word
if __name__ == '__main__':
print generateWord() |
Took me half a day to figure out matcher.find() had to be called first. Gaah!
RegexTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tester {
public static void main(String args[])
{
Pattern pattern = Pattern.compile("name=\"QTime\">(\\d+)</int>");
Matcher matcher = pattern.matcher("<response><lst name=\"responseHeader\">" +
"<int name=\"status\">0</int><int name=\"QTime\">2</int></lst></response>");
try {
if(matcher.find()) {
System.out.println(matcher.group(1));
}
}
catch (Exception e) {
System.out.println("Couldn't find QTime");
}
}
} |
P.S. I love Python
This snippet illustrates how one can easily build a HTTP Web Server in python. self.args will contain the query parameters.
WebServer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Simple WebServer Illustration
# Pravin Paratey (April 15, 2009) [pravinp at gmail dot com]
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
binaryExtensions = ['.gif', '.png', '.jpg']
contentTypes = {
'.css': 'text/css',
'.gif': 'image/gif',
'.jpg': 'image/jpg',
'.png': 'image/png',
'html': 'text/html',
}
def do_GET(self):
""" Implementing the GET method """
try:
if self.path == '/': self.path = '/index.html'
mode = 'r'
if self.path[-4:] in self.binaryExtensions: mode = 'rb'
fp = open(self.path[1:], mode)
data = fp.read()
fp.close()
# Send response
self.send_response(200)
self.send_header('Content-Type', self.__getContentType())
self.send_header('Transfer-Encoding', 'chunked')
self.end_headers()
self.wfile.write(data)
except IOError:
self.send_error(404, "File not found: %s" % self.path)
def __getContentType(self):
""" Function to figure out content types """
content_type = 'text/plain'
extension = self.path[-4:]
if extension in self.contentTypes:
content_type = self.contentTypes[extension]
return content_type
if __name__ == '__main__':
server = HTTPServer(('', 8000), MyHandler)
server.serve_forever() |
Of late, I have been working with Java. And one of the issues that I faced was XML parsing. With so many libraries available, I decided to stick to jaxp. What follows is sample code to Tree walk over the nodes:
TreeWalk.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Tester {
public static void main(String args[])
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(new File(args[0]));
NodeList nodes1 = doc.getChildNodes();
for(int i=0; i<nodes1.getLength(); i++) {
TreeWalk(nodes1.item(i), 0);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
private static void TreeWalk(Node n, int level)
{
if(n.getNodeType() != Node.TEXT_NODE) {
for(int i=0; i<level; i++)
System.out.print(" ");
System.out.print(n.getNodeName() + ":");
}
else {
System.out.println(n.getNodeValue().trim());
}
NodeList list = n.getChildNodes();
for(int i=0; i<list.getLength(); i++) {
TreeWalk(list.item(i), level+1);
}
}
} |
I was recently asked how I got the wp-syntax plugin to show a header like so:
test.cpp
1
2
3
| int main() {
return 0;
} |
To show the test.cpp file name, I modified the wp-syntax.php file (present in /wp-content/plugins/wp-syntax/) like so:
Changed the regular expression in the wp_syntax_before_filter function from:
wp-syntax.php
function wp_syntax_before_filter($content)
{
return preg_replace_callback(
"/\s*<pre(?:lang=[\"']([\w-]*)[\"']|line=[\"'](\d*)[\"']|escaped=[\"'](true|false)?[\"']|\s)+>(.*)<\/pre>\s*/siU",
"wp_syntax_substitute",
$content
);
}
to
wp-syntax.php
function wp_syntax_before_filter($content)
{
return preg_replace_callback(
"/\s*<pre(?:lang=[\"']([\w-]*)[\"']|line=[\"'](\d*)[\"']|escaped=[\"'](true|false)?[\"']|header=[\"']([\w-\. ]*)[\"']|\s)+>(.*)<\/pre>\s*/siU",
"wp_syntax_substitute",
$content
);
}
And the wp_syntax_highlight function to:
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
| function wp_syntax_highlight($match)
{
global $wp_syntax_matches;
$i = intval($match[1]);
$match = $wp_syntax_matches[$i];
$language = strtolower(trim($match[1]));
$line = trim($match[2]);
$escaped = trim($match[3]);
$header = trim($match[4]);
$code = wp_syntax_code_trim($match[5]);
if ($escaped == "true") $code = htmlspecialchars_decode($code);
$geshi = new GeSHi($code, $language);
$geshi->enable_keyword_links(false);
do_action_ref_array('wp_syntax_init_geshi', array(&$geshi));
$output = "\n<div class=\"wp_syntax\">";
if($header) {
$output .= "<div class=\"wp_syn_hdr\">" . $header . "</div>";
} |
Node the addition of lines 104 and 114-116
All you have to do is add another attribute header="header-text" in your pre tag. ex. <pre lang="php" line="1" header="wp-syntax.php">
The following snippet combines the various opera mbs into one mbox format which can be used by other email clients like Evolution to import mail
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| #!/usr/bin/python
# Quick hack to merge all opera mbs files into mbox format which can
# then be used by other email clients to import Opera email.
# by Pravin Paratey (January 19, 2009)
import os
# Change this value
folder = '/home/pravin/.opera/mail/store/account1/'
fp = open('combined.mbox', 'a')
for d0 in os.listdir(folder):
p0 = os.path.join(folder,d0)
if os.path.isfile(p0): continue
for d1 in os.listdir(p0):
p1 = os.path.join(p0, d1)
for d2 in os.listdir(p1):
p2 = os.path.join(p1, d2)
for f in os.listdir(p2):
fp2 = open(os.path.join(p2, f), 'r')
fp.write(fp2.read())
fp2.close()
fp.close() |
The following snippet returns the euclidean distance between two places on the globe using the Yahoo Maps API. Replace API_KEY with your Yahoo Maps API key.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| #!/usr/bin/env python
# Distance Module
# by Pravin Paratey (pravinp at gmail dot com)
# Code is licenced under Creative Commons Attribution-Noncommercial-Share Alike 2.5 India
# http://creativecommons.org/licenses/by-nc-sa/2.5/in/
import urllib2, cgi, re
from math import sqrt
class Distance:
"""
Using yahoo maps api (http://developer.yahoo.com/maps/rest/V1/geocode.html),
this class is responsible for returning the euclidean distance between
two places
"""
def getDistance(self, start, end):
""" Gets the euclidean distance between start and end """
(start_x, start_y) = self.getCoords(start)
(end_x, end_y) = self.getCoords(end)
# 1 degree = 111.12 kms or 69.047 miles
return sqrt((start_x - end_x) ** 2 + (start_y - end_y) ** 2) * 111.12
def getCoords(self, location):
""" Gets the co-ordinates for the given location """
url = 'http://local.yahooapis.com/MapsService/V1/geocode?appid=' +
API_KEY + '&street=' + urllib2.quote(location)
response = urllib2.urlopen(url)
(x, y) = self._parseXML(response.read())
return float(x), float(y)
def _parseXML(self, xml):
""" Parses XML and returns latitude and longitude """
m = re.findall('<latitude>(\d+.\d+)</latitude><longitude>(\d+.\d+)</longitude>', xml)
# In case of multiple matches, return 1st match
return m[0]
if __name__ == '__main__':
d = Distance()
print 'Distance in kms: '
print d.getDistance("Hiranandani, Powai, Mumbai", "Dadar Station, Mumbai") |
This snippet draws a bar graph that tells you your twitter posting frequency per hour in the last 24 hours.
Screenshot

Instructions
- Download Twitter Timeline Javascript v0.2 (Requires PlotKit and MochiKit).
- Edit TwitterTimeline.js and change the
userid variable to your user-id. You’ll find your user-id at http://twitter.com/account/badge.
- You will need to include the javascript files:
<script type="text/javascript" src="/js/MochiKit/MochiKit.js"></script>
<script type="text/javascript" src="/js/PlotKit/Base.js"></script>
<script type="text/javascript" src="/js/PlotKit/Layout.js"></script>
<script type="text/javascript" src="/js/PlotKit/Canvas.js"></script>
<script type="text/javascript" src="/js/PlotKit/SweetCanvas.js"></script>
<script type="text/javascript" src="/js/TwitterTimeline.js"></script>
- Next, add the following lines where you want the Timeline to appear:
<script type="text/javascript" src="/js/TwitterTimeline.js"></script>
<div><canvas id="graph" height="200" width="400"></canvas></div>
For your reference, TwitterTimeline.js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
| <script type="text/javascript">
<!--
/*
* Twitter Timeline Javascript v0.2 (March 20, 2007)
* Pravin Paratey (http://www.dustyant.com)
* Andrei Virlan (http://its.squeak.in)
*
* Released under Creative Commons Attribution 2.5 Licence
* http://creativecommons.org/licenses/by/2.5/
*
* Changelog:
* 0.2 (Mar 20, 2007) - Moved to PlotKit to draw graphs
* 0.1 (Feb 23, 2007) - Initial Release
*/
var userid = '754023'; // Change this value to your user-id
var timelineArray = new Array();
function drawGraph() {
var layout = new PlotKit.Layout("bar", {});
layout.addDataset("sqrt", timelineArray);
layout.evaluate();
var canvas = MochiKit.DOM.getElement("graph");
var plotter = new PlotKit.SweetCanvasRenderer(canvas, layout, {});
plotter.render();
}
function twitterCallback(obj) {
// Create an array to hold the 24 hours of the day
var hourArray = new Array(24);
// Initialize array
for(var i=0; i<24; i++) {
hourArray[i] = 0;
}
for (var i=0; i<obj.length; i++) {
// Get date
var created_at = new Date(obj[i].created_at);
if(obj[i].user.id == userid) {
// Increment the hour
hourArray[created_at.getHours()]++;
}
}
// Construct the timeline
for(var i=0; i<24; i++) {
timelineArray[i] = new Array(i, hourArray[i]);
}
MochiKit.DOM.addLoadEvent(drawGraph);
}
// Makes the twitter call
document.write('<scr'+'ipt type="text/javascript"' +
'src="http://twitter.com/statuses/friends_timeline/' +
userid + '.json?callback=twitterCallback"></scr'+'ipt>');
-->
</script> |
Synopsis
The following code demonstrates an alien limerick generator. Alien because it does not generate meaningful words. In part II, we’ll see how we can add meaningful words.
Code
You can view the code and see it in action here.
Sample Output
orraxa iz hoxori upifoc awhapo ed
ceva ovat ujbazo arli du caded
uc iqek suenvo
zaek ammiip edbeuvo
moix beak kuefyo irogno iluyox xoiqged
Synopsis
The following code illustrates the use of FindWindow API. This program blanks out the ad in Yahoo Messenger buddy window. It has been tested on Yahoo Messenger 7.5 and 8.0.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| // This code illustrates hiding the Ad in the Buddy window of Yahoo Messenger
//
// Copyright (c) 2006, Pravin Paratey
// pravinp[at]gmail[dot]com (http://dustyant.com)
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpszArgs, int nCmdWnd)
{
HWND hYahooWnd = FindWindowEx(NULL, NULL, "YahooBuddyMain", NULL);
if(hYahooWnd) // Yahoo Messenger is running
{
HWND hAtlWnd = FindWindowEx(hYahooWnd, NULL, "ATL:00821BC0", NULL);
if(hAtlWnd) // Found the window
{
HWND hShellWnd = FindWindowEx(hAtlWnd, NULL, "Shell Embedding", NULL);
if(hShellWnd)
{
HWND hDocObjWnd = FindWindowEx(hShellWnd, NULL, "Shell DocObject View", NULL);
if(hDocObjWnd) // This is the window we must hide
{
ShowWindow(hDocObjWnd, SW_HIDE);
}
}
}
}
else
{
MessageBox(NULL, "No instances of Yahoo Messenger found", "Error", MB_OK);
}
return 0;
} |
Download
You can download the source code or the binary.
Usage
Pretty straight forward. When yahoo messenger is running, double click the exe. The ads window will disappear