analitics

Pages

Wednesday, October 21, 2009

MD5 - password generator

Why do we need this script?
Internet is full of generating MD5.
The Internet has and dictionaries for decrypting md5.
So safe is our script.
You must use the code line:
p = md5.new ()

otherwise if you use:
pass = md5.new ()

you get the following error:
>>> pass = md5.new()
File "", line 1
pass = md5.new()
^
SyntaxError: invalid syntax

pass is a python keyword.
You'll need a different name for the variable.
And now to see the code:
import md5 
p = md5.new()
p.update("password")
p.hexdigest()
'5f4dcc3b5aa765d61d8327deb882cf99'

This is all you need.

Wednesday, October 7, 2009

Pyglet - simple example

First i wanted to make a simple example. Then I saw George Oliver googlegrups question. This made me change my little script.Official Site address is: www.pyglet.org.
Documentation of this module is to: www.pyglet.org/documentation.html.
There is also a Google group for this mode where you can ask questions.
My example does nothing more than:
- Create a fereasta;
- To put a background color;
- Displaying an image.
Image i use it, name it "20000.jpg" is this:

Put in folder with your script.
In the future I will come with more complex examples.
Change the following sequence of lines of code example:
  win.clear ()
img1.blit (5, 5)

You will see that the order matters for pyglet.
Who studied OpenGL knows why.

import pyglet
from pyglet.gl import *
#set colors with red,green,blue,alpha values
colors = {
'playfield' : (255, 255, 255, 255),
'red' : (255, 0, 0, 255,0),
'sub_red' : (255, 50, 20, 255),
'green' : (0, 255, 0, 255),
'sub_green' : (20, 255, 50, 255),
'blue' : (0, 0, 255, 255),
'sub_blue' : (20, 50, 255, 255)}
#give img1 the place of image
img1= pyglet.image.load('20000.jpg')
#w , h the size of image
w = img1.width+15
h = img1.height+10
# create the 640x480 window size
win = pyglet.window.Window(640, 480, resizable=True, visible=True)
#or use next line to see with size of image
#win=pyglet.window.Window(width=w, height=h)

# set caption of window
win.set_caption("TEST")
#use * to unpack tuple and set background color
pyglet.gl.glClearColor(*colors['red'])

@win.event

def on_draw():
win.clear()
img1.blit(5, 5)
# to run application
pyglet.app.run()

If you use the code line:
win = pyglet.window.Window(640, 480, resizable=True, visible=True)

you see:

If you use the code line:
win=pyglet.window.Window(width=w, height=h)

you see:

Thursday, September 17, 2009

Random words from lists and text

Sometimes it is necessary to choose random words from lists or texts.
Example below illustrates this:

import random
list_input = """ Apple
Crabapple
Hawthorn
Pear
Apricot
""".strip().split("\n")
text_input = "This is a text without newline char".split()
print "List is =", list_input
print "---------------------------------------"
list_result = random.choice(list_input)
print "Random list result is =", list_result
print "---------------------------------------"
print "Text is =", text_input
print "---------------------------------------"
text_result = random.choice(text_input)
print "Random word result is =", text_result

We have two variables "list_input" and "text_input" containing a list of words separated by newline char and a simple string ending in newline char.
Its separation is made with function ".strip ()" .
This function separates the items in the list after this particular bracket expression. The result of the expression in brackets vanishes from the list.
The result of scripts is :

List is = ['Apple', ' Crabapple', ' Hawthorn', ' Pear', ' Apricot']
---------------------------------------
Random list result is = Pear
---------------------------------------
Text is = ['This', 'is', 'a', 'text', 'without', 'newline', 'char']
---------------------------------------
Random word result is = is

Friday, September 11, 2009

How to use "try" ... "except"

Any program will be given over to error checking.
Python provides an exception handling capability.
There are two parts : "error checking" "catching exceptions".
Now let's try a simple example:

>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string 12
>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string aaa
This is not a number

The code :
input_str = int(input ("string "))

The code readed input will be convert in integer .
If types a value that's not an integer, the exception is caught.
In this case will print " This is not a number ".
This is very important because it generates more errors while running a program.
So, simply try to perform you action, and define what's to be done.
On except block if the action you want can't be completed.

Saturday, August 8, 2009

Permutation of chars with python

It is a simple example of using python language to permutation of chars.
It uses a list generator and "yield":

#!/usr/bin/env python
def permut(lst):
remove = lambda lst0, index: lst0[:index] + lst0[index+1:]
if lst:
for index, x in enumerate(lst):
for y in permut(remove(lst, index)):
yield (x,)+y
print y

else: yield ()
lst='catalin'
for p in permut(['c','a','t','a','l','i','n']):
print p

Example can be modified so output will be a file.

Saturday, August 1, 2009

Google and Python Stuff

I want share this scripts.
Is just two scripts and i think is beautifull.
First is a youtube script :
import gdata.youtube
import gdata.youtube.service

client_yt = gdata.youtube.service.YouTubeService()
query = gdata.youtube.service.YouTubeVideoQuery()
query.vs = "%s" % ('News')
feed = client_yt.YouTubeQuery(query)

for entry in feed.entry:
print entry.title.text
for link in entry.link:
if link.rel == 'alternate':
print link.href

Second is a picassa script :
import gdata.photos
import gdata.photos.service
import urllib
p_client = gdata.photos.service.PhotosService()

query_parameters = map(urllib.quote, ['Sexy','Bucharest']);
feed = p_client.GetFeed("/data/feed/api/all?q=%s%s&max-results=10" % ('Sexy','Girl'))

for entry in feed.entry:
print entry.title.text
for link in entry.link:
if link.rel == 'alternate':
print link.href

I hope you like this little scripts.

Sqlite and Python

These script explore the Python Sqlite modules available for database administration.
Sometime you need to use extraction, processing, storage and presentation of your data.
This is a short example :
#!/usr/bin/python

import sqlite3

def select_db():
print "Select database"

co=sqlite3.connect("cata2.db")
cursor=co.execute("CREATE TABLE report (nr INT,user VARCHAR(20),descriere VARCHAR(100));")
cursor=co.execute("INSERT INTO report (nr,user,descriere) VALUES (1,'root','root administration');")
cursor=co.execute("SELECT * FROM report;")

print cursor.fetchall()

This python script will be create cata.db file on your folder.
The table of database is 'report' and add next values "1,'root','root administration'".
If you want create new database , use :
co=sqlite3.connect("new_database.db")
cursor=co.execute("CREATE TABLE tabela (some_value_integer INT,some_value_chars VARCHAR(20));")

If you want show it , use this :
cursor=co.execute("SELECT * FROM new_database;")

Thank you !

Saturday, July 4, 2009

resize images to create thumbnails

First you have many images.
If you want to create thumbnail for each one this is python script:

import glob 
import PIL
from PIL import Image
for infile in glob.glob("*.jpg"):
 img = Image.open(infile)
 dim_percent=(100/float(img.size[0]))
 dim_size=int((float(img.size[1])*float(dim_percent)))
 img = img.resize((100,dim_size),PIL.Image.ANTIALIAS)
 if infile[0:2] != "trumb_":
  img.save("trumb_" + infile, "JPEG")

Sunday, June 21, 2009

PyGTK and GdkPixbuf

What is GdkPixbuf?
* An object holding information about images in memory.
Constructor
GdkPixbuf (GdkColorspace colorspace, bool has_alpha, int bits_per_sample, int width, int height);

Example:

>>> import pygtk
>>> import pygtk
>>> pixbuf = gtk.gdk.Pixbuf( gtk.gdk.COLORSPACE_RGB, False,8, 200, 100)
>>> pixbuf.save('/home/net/cc/a.jpg','jpeg', {'quality':'100'})

The output is :

PyGTK 2.15.2 - unstable

As you know, PyGTK is a set of Python wrappers.
Now PyGTK easily create programs with a graphical user interface using the Python programming language.
The new PyGTK version 2.15.2 and is on PyGTK 2.15.2 source.
From http://pygtk.org
"What's new since 2.15.0?
- (Add HSV support to gtk.gdk.Color objects)
- Add floating-point support to gtk.gdk.Color (Paul)
- Retire hand-written ChangeLog; autocreate from Git history (Paul)
- Fix conditional in docs/Makefile.am (Frederic Peters)
- Document that gtk.gdk.GC coordinates are not related to allocation (Paul)
- Make pygtk_boxed_unref_shared() also handle Py_None (Paul)
- Make gtk.MenuItem.set_submenu accept None (Paul)
- Don't run 'fixxref.py' if documentation is not built (Björn Lindqvist)
- Apply libtool 2.2 compatibility patch (Gian)
- Plug reference leak on main signal watch source (Paul)
- Add extra warning against accidental misuse of tree model columns (Paul)
- Wrap gtk.Border attributes and constructor (Mariano Suárez-Alvarez)
- Make gtk.gdk.Event.time accept 'long' in assignments (Paul)
- Wrap gtk.RcStyle attributes (Paul)

PyGTK requires GTK+ >= 2.8.0 and Python >= 2.3.5 to build."

Tuesday, March 24, 2009

Python - random passwords

This program generates passwords on the size of 10 characters.
By using a function called "random_password" that creates a password of size 10 characters.
This function called "write_file" creates a file with automatic redial function "random_password. It contains a table of 10 X 10 random passwords.

from random import *
import string
chars = string.ascii_letters + string.digits
def random_password():
a = "".join(choice(chars) for x in range(randint(10, 10)))
b = a + ' | '
return b
def write_file():
f = open('random_pass.txt', 'wr+')
for c in range(10):
rand=''
for r in range(10):
rand = rand + random_password()
randpass=rand + random_password() + '\n'
f.write(str(randpass))
f.close()
write_file()

Friday, February 27, 2009

Python and xml

Python is an excellent choice for writing programs that process XML data.
XML's is a simplified subset of the Standard Generalized Markup Language (SGML).
He set of tools helps developers in creating web pages.
This is one simple example which I use with "conky":

from xml.dom import minidom as dom
import urllib2
def fetchPage(url):
a = urllib2.urlopen(url)
return ''.join(a.readlines())
def extract(page):
a = dom.parseString(page)
item2 = a.getElementsByTagName('SendingDate')[0].firstChild.wholeText
print "DATA ",item2
item = a.getElementsByTagName('Cube')
for i in item:
if i.hasChildNodes() == True:
e = i.getElementsByTagName('Rate')[8].firstChild.wholeText
d = i.getElementsByTagName('Rate')[18].firstChild.wholeText
print "EURO ",e
print "DOLAR ",d

if __name__=='__main__':
page = fetchPage("http://www.bnro.ro/nbrfxrates.xml")
extract(page)

First step ...and some examples

So the first step to use python is how to load module.
This is simple one:

import sys
import math
from math import sin
dir(math)

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

Next is two examples with calendar module.

import calendar
time_cal=calendar.TextCalendar(calendar.FRIDAY)
print time_cal.formatmonth(2009,02)
February 2009
Fr Sa Su Mo Tu We Th
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

If i use this into web page this is the solution:

import calendar
html_cal=calendar.HTMLCalendar(calendar.MONDAY)
print html_cal.formatmonth(2009,02)










February 2009
MonTueWedThuFriSatSun






1
2345678
9101112131415
16171819202122
232425262728