Tuesday, March 9, 2010

March Madness Challenge - MMC09

Today only a little play around with plotting. I guess tomorrow when I have more time I will plot my own histogram.

1 #! /usr/bin/python
2
3 import matplotlib.pyplot as plt
4
5 plt.plot([0,2,1,3])
6 plt.ylabel('value')
7 plt.xlabel('plot test')
8 plt.show()

Monday, March 8, 2010

March Madness Challenge - MMC08

Image processing at University was not always fun. Today I tried to create a histogram of a gray scale image. I wanted to use an array that has 256 elements. Then I wanted to loop thru the whole image, use the value as index and increase by one in the 256 array. But the histogram function does not like tuples I guess. So this python script is totally inefficient, because it creates an array that has x*y values between 0 and 255 instead of 256 values.

1 #! /usr/bin/python
2
3 from PIL import Image
4 import matplotlib.pyplot as plt
5 import sys
6
7 histo = []
8
9 """for i in range(0,256,1):
10 histo.append([i,0])"""
11
12 img = Image.open(sys.argv[1])
13 pix = img.load()
14
15 width = img.size[0]
16 height = img.size[1]
17
18 for x in range(0,width,1):
19 for y in range(0,height,1):
20 #histo[pix[x,y]][1] += 1
21 histo.append(pix[x,y])
22
23 plt.hist(histo,256)
24 plt.xlabel('Grayvalue')
25 plt.ylabel('Frequency')
26 plt.title('Histogram %s' % sys.argv[1])
27 plt.grid(True)
28 plt.show()
29



Sunday, March 7, 2010

March Madness Challenge - MMC07

Inspired by Adams post I made the FizzBuzz test. I used python and it took me about two Minutes. So I guess I'm ok. ;-)

1 #! /usr/bin/python
2
3 mod3 = False
4 mod5 = False
5
6 for i in range(1,101,1):
7 mod3 = False
8 mod5 = False
9
10 if (i % 3) == 0:
11 mod3 = True
12 if (i % 5) == 0:
13 mod5 = True
14
15 if (mod3 and mod5):
16 print 'fizzbuzz'
17 elif mod3:
18 print 'fizz'
19 elif mod5:
20 print 'buzz'
21 else:
22 print '%d' % i
23

Saturday, March 6, 2010

March Madness Challenge - MMC06

Going to PA today, coming home late. So I have to pull the "Hello World" one.

1 #! /usr/bin/python
2
3 print 'Hello World'
4

Friday, March 5, 2010

March Madness Challenge - MMC05

Today I had absolutely no time. So here is a little bit of bit-shifting for you.
    1 #! /usr/bin/python
2
3 x = 1
4
5 for i in range(8):
6 x <<= 1
7 print x
8

Thursday, March 4, 2010

March Madness Challenge - MMC04

Working with the python documentation some kind of sucks. Maybe its me.... Putting code into blogger is still a problem, will see what I can do about that.

Threading is todays topic. A user specified number of threads are going to sleep for random 1 to 5 seconds and then try to access a shared counter. Whatever number of threads you set as argument, the counter should have the some value. I'm still a little bit confused about when to use "import" or "from x import y".



1 #! /usr/bin python
2
3 import random
4 import thread
5 import time
6
7 counter = 0
8
9 def threadFunc(threadID, lock):
10 print 'Thread %d START' % threadID
11 sleep = random.randint(1,5)
12 print 'Thread %d will sleep for %d seconds' % (threadID,sleep)
13 time.sleep(sleep)
14 lock.acquire()
15 try:
16 global counter
17 counter += 1
18 finally:
19 lock.release()
20 print 'Thread %d END' % threadID
21
22 def runThreads(threadCount):
23 cntLock = thread.allocate_lock()
24
25 for i in range(int(threadCount)):
26 t = Thread(target=threadFunc, args=(i,cntLock))
27 t.start()
28
29 if __name__ == '__main__':
30 print '***** MMC04 *****'
31
32 from threading import Thread
33
34 from optparse import OptionParser
35 parser = OptionParser()
36 parser.add_option("-t", "--threads", dest="threadCount", default='1',
37 help='number of threads')
38 (options, args) = parser.parse_args()
39
40 runThreads(options.threadCount)
41
42 time.sleep(6)
43 print 'Counter = %d' % counter
44

Wednesday, March 3, 2010

March Madness Challenge - MMC03

I wrote a little program that checks if a web server is running at a user specified ip address. While I was browsing to the documentation is saw OptionParse. This is a really nice way to parse arguments. Especially the -h option, that will generate the usage info automatically.

Possible output:

python mmc03.py -i 127.0.0.1 -r /
***** MMC03 *****
Port 80 check successfull!
Webserver is running! Response: 302 Found

python mmc03.py -i 127.0.0.1 -r /
***** MMC03 *****
Port 80 check failed: [Errno 10061] No connection could be made because the target machine actively refused it


1 #! /usr/bin python
2
3 import httplib
4
5 def checkPort(ip, resource):
6 if not resource.startswith('/'):
7 resource = '/' + resource
8
9 try:
10 conn = httplib.HTTPConnection(ip, httplib.HTTP_PORT)
11 conn.request('GET', resource)
12 response = conn.getresponse()
13 print 'Port %s check successfull!' % httplib.HTTP_PORT
14 if (httplib.responses[response.status]):
15 print 'Webserver is running! Response: %s %s' % \
16 (response.status, response.reason)
17 except Exception, e:
18 print 'Port %s check failed: %s' % (httplib.HTTP_PORT, e)
19 return False
20 finally:
21 conn.close()
22
23 if __name__ == '__main__':
24 print '***** MMC03 *****'
25
26 from optparse import OptionParser
27 parser = OptionParser()
28 parser.add_option("-i", "--ip", dest="ip", default='127.0.0.1',
29 help='ip address of server')
30 parser.add_option("-r", "--resource", dest="resource", default="/",
31 help="resource to check")
32 (options, args) = parser.parse_args()
33
34 checkPort(options.ip, options.resource)
35