DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
>>> from winsound import *
>>> f = "C:/Windows/Media/chimes.wav"
>>> PlaySound(f, SND_FILENAME)
>>> PlaySound("SystemExit", SND_ALIAS)
See <a href=http://docs.python.org/lib/module-winsound.html>documentation</a>.
From Greg Jorgensen's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52213>recipe</a>.
def soundex(name, len=4):
# digits holds the soundex values for the alphabet
digits = '01230120022455012623010202'
sndx = ''
fc = ''
# translate alpha chars in name to soundex digits
for c in name.upper():
if c.isalpha():
if not fc: fc = c # remember first letter
d = digits[ord(c)-ord('A')]
# duplicate consecutive soundex digits are skipped
if not sndx or (d != sndx[-1]):
sndx += d
sndx = fc + sndx[1:] # replace first digit with first char
sndx = sndx.replace('0','') # remove all 0s
return (sndx + (len * '0'))[:len] # padded to len characters
Similar words will return the same soundex
>>> soundex('hello')
'H400'
>>> soundex('hola')
'H400'
From Jeff Bauer's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52218>recipe</a>.
# server.py
import socket
port = 8081
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "waiting on port:", port
while 1:
data, addr = s.recvfrom(1024)
print data
# client.py
import socket
port = 8081
host = "localhost"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", 0))
s.sendto("Holy Guido! It's working.", (host, port))
import zipfile
z = zipfile.ZipFile("zipfile.zip", "r")
for filename in z.namelist():
print filename
bytes = z.read(filename)
print len(bytes)
Sometimes, I need to find a ratio approximation of a number.
Like 640 / 480 (vga) or similar number. I learn about farey
series a few years ago (1994).
The <a href=http://en.wikipedia.org/wiki/Farey_sequence>idea</a> is actually quite simple.
>>> farey(math.pi,100) (22, 7)
Get the implementation <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317>here</a>.
from struct import unpack
f = open('data.bin', 'rb')
b = f.read(1)
b2 = f.read(2)
b4 = f.read(4)
n = ord(b) # from char to int
n4 = unpack('>L', b4) # big endian
n4 = unpack('<L', b4) # little endian
n = unpack('>h', b2) # big endian short
From Sami Hangaslammi's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66009>recipe</a>.
import re
def cw2us(x): # capwords to underscore notation
return re.sub(r'(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', r"_\g<0>", x).lower()
def mc2us(x): # mixed case to underscore notation
return cw2us(x)
def us2mc(x): # underscore to mixed case notation
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)
def us2cw(x): # underscore to capwords notation
s = us2mc(x)
return s[0].upper()+s[1:]
Result
>>> cw2us("PrintHTML")
'print_html'
>>> cw2us("IOError")
'io_error'
>>> cw2us("SetXYPosition")
'set_xy_position'
>>> cw2us("GetX")
'get_x'
In python for series 60, the use of e32.ao_sleep is encourage
over time.sleep. AO stands for 'Active Object' approach to
cooperative multi-tasking. When an object go to 'ao_sleep'
other active objects can run.
import e32 e32.ao_sleep(5) # sleep for 5 seconds
There is another usage ao_sleep(interval, callback) where ao_sleep will return immediately but the callback will be called after the interval (in another thread?) This could be used to create a repeat loop for every interval. I show this in <a href=http://bigbold.com/snippets/posts/show/730>a previous snippet</a>.
import e32, time def showtime(): print time.clock() e32.ao_sleep(1, showtime) # sleep then call itself again showtime() # start the loop
From Alex's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207>recipe</a>.
# Put in const.py...:
class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)"%name
self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()
that's all -- now any client-code can
import const const.magic = 23 # bind an attribute ONCE const.magic = 88 # raises const.ConstError if re-bind
Get the code for createhtmlmail(html, text, subject) <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67083>here</a>.
import smtplib
html = open("newsletter.html").read()
text = open("newsletter.txt").read()
subject = "Today's Newsletter!"
message = createhtmlmail(html, text, subject)
server = smtplib.SMTP("localhost")
server.sendmail('my@dress.com', 'your@dress.com', message)
server.quit()
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
What a pythonic way to use Singleton. It uses shared-state approach where you can actually have many instances as you want but they all share the same state. See Alex's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531>recipe</a>.
>>> b = Borg() >>> b.x = 1 >>> c = Borg() >>> c.x 1
The code is too long. I'd rather just make a <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/93025>link</a>.
It uses MS Speech SDK 5.1 via COM.
>>> import win32com.client
>>> s = win32com.client.Dispatch("SAPI.SpVoice")
>>> s.Speak('Hello, how are you?')
You need MS Speech SDK installed. See <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216>recipe</a>.
From Kevin Parks's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117241>recipe</a>
import random def w_choice(lst): n = random.uniform(0, 1) for item, weight in lst: if n < weight: break n = n - weight return item
Usage, similar to random.choice but must specify probabilities.
>>> x = w_choice( [('one',0.25), ('two',0.25), ('three',0.5)] )
I learn to use 2 different types of Canvas callbacks
in the <a href=http://www.bigbold.com/snippets/posts/show/730>last snippet</a>.
Typically, when I wrote a non-OO code, I will use
app.body = c = Canvas()
where I already had
from appuifw import *
The shortcoming is that I need to define callbacks first, then pass it to the constructor c = Canvas(redraw_callback, event_callback) By using OO, the canvas is created in __init__() and it can access other methods that come later in the code. In this case, I use Canvas(self.update) which means that the self.update will be used to redraw screen. The secode way to use callback is Canvas.bind() method. I have always been using this approach to binding any event callback to a canvas. In some case, the event_callback in the constructor maybe more elegant, though. Notice my use of
self.canvas.bind(EKeySelect, self.toggle)
Here I can bind the select key to self.toggle whose definition will follow. This is more convenient than having to define it first. So, I think OO code is easier to write in this way. I also use class variables instead of instance variables. I found declaring it outside __init__() is more natural and similar to my previous non-OO approach. (still easy to read, with variable & def declarations) When I write self.myvar inside __init__(), I feel the code is somewhat bloated. The class will have only 1 instance anyway.




