Skip to content

Instantly share code, notes, and snippets.

@gennad
gennad / sieve.py
Created July 4, 2011 08:41
Eratosthene's sieve
n = input("n = ")
a = range(n+1)
a[1] = 0
lst = []
i = 2
while i <= n:
if a[i] != 0:
lst.append(a[i])
for j in xrange(i, n+1, i):
@gennad
gennad / randhash.py
Created June 10, 2011 09:07
Generate random hashcode in Python
import random
random.seed()
hash = random.getrandbits(128)
print "hash value: %016x" % hash
@gennad
gennad / json.py
Created June 10, 2011 08:28
Send json POST request
import urllib2
import json
# Whatever structure you need to send goes here:
jdata = json.dumps({"username":"...", "password":"..."})
urllib2.urlopen("http://www.example.com/", jdata)
@gennad
gennad / timestamp.py
Created June 10, 2011 07:15
Python string to timestamp
import datetime
import time
def from_string_to_timestamp(st):
if st.find('-') != -1:
splitted = st.split('-')
else:
splitted = st.split('.')
try:
@gennad
gennad / tray.py
Created June 7, 2011 05:19
Tray example in gnome
#!/usr/bin/python
# Copyright (C) 2009 Mauricio Teixeira.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
@gennad
gennad / quicksort.py
Created May 29, 2011 16:22
Quikcosrt Python
#Three-way QuickSort in Python
def quicksort(a):
if len(a) == 0:
return []
p = a[(len(a)-1)//2]
less = quicksort([x for x in a if x < p])
greater = quicksort([x for x in a if x > p])
equal = [x for x in a if x == p]
return less + equal + greater
@gennad
gennad / quicksort.py
Created May 29, 2011 15:56
Quikcosrt Python
#Three-way QuickSort in Python
def quicksort(a):
if len(a) == 0:
return []
p = a[(len(a)-1)//2]
less = quicksort([x for x in a if x < p])
greater = quicksort([x for x in a if x > p])
equal = [x for x in a if x == p]
return less + equal + greater
@gennad
gennad / mergesort.py
Created May 29, 2011 15:55
Mergesort Python
#Merges two sorted lists into one sorted list. recursively
def merge(left, right):
if len(left) == 0 and len(right) == 0:
return []
elif len(left) == 0:
return right
elif len(right) == 0:
return left
else:
if left[0] <= right[0]:
@gennad
gennad / decorators.py
Created May 28, 2011 20:01
Decorators
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
f() # Prove that function definition has completed
def __call__(self):
print "inside myDecorator.__call__()"
@myDecorator
@gennad
gennad / meta.py
Created May 28, 2011 19:54
Metaclasses in Python
def make_hook(f):
"""Decorator to turn 'foo' method into '__foo__'"""
f.is_hook = 1
return f
class MyType(type):
def __new__(cls, name, bases, attrs):
if name.startswith('None'):
return None