Commit bb6cbc79 authored by Guido van Rossum's avatar Guido van Rossum

Mass patch by Ka-Ping Yee:

    1. Comments at the beginning of the module, before
       functions, and before classes have been turned
       into docstrings.

    2. Tabs are normalized to four spaces.

Also, removed the "remove" function from dircmp.py, which reimplements
list.remove() (it must have been very old).
parent efd4af85
# A multi-producer, multi-consumer queue.
"""A multi-producer, multi-consumer queue."""
# define this exception to be compatible with Python 1.5's class
# exceptions, but also when -X option is used.
......
# class StringIO implements file-like objects that read/write a
# string buffer (a.k.a. "memory files").
#
# This implements (nearly) all stdio methods.
#
# f = StringIO() # ready for writing
# f = StringIO(buf) # ready for reading
# f.close() # explicitly release resources held
# flag = f.isatty() # always false
# pos = f.tell() # get current position
# f.seek(pos) # set current position
# f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
# buf = f.read() # read until EOF
# buf = f.read(n) # read up to n bytes
# buf = f.readline() # read until end of line ('\n') or EOF
# list = f.readlines()# list of f.readline() results until EOF
# f.write(buf) # write at current position
# f.writelines(list) # for line in list: f.write(line)
# f.getvalue() # return whole file's contents as a string
#
# Notes:
# - Using a real file is often faster (but less convenient).
# - fileno() is left unimplemented so that code which uses it triggers
# an exception early.
# - Seeking far beyond EOF and then writing will insert real null
# bytes that occupy space in the buffer.
# - There's a simple test set (see end of this file).
"""File-like objects that read from or write to a string buffer.
This implements (nearly) all stdio methods.
f = StringIO() # ready for writing
f = StringIO(buf) # ready for reading
f.close() # explicitly release resources held
flag = f.isatty() # always false
pos = f.tell() # get current position
f.seek(pos) # set current position
f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
buf = f.read() # read until EOF
buf = f.read(n) # read up to n bytes
buf = f.readline() # read until end of line ('\n') or EOF
list = f.readlines()# list of f.readline() results until EOF
f.write(buf) # write at current position
f.writelines(list) # for line in list: f.write(line)
f.getvalue() # return whole file's contents as a string
Notes:
- Using a real file is often faster (but less convenient).
- fileno() is left unimplemented so that code which uses it triggers
an exception early.
- Seeking far beyond EOF and then writing will insert real null
bytes that occupy space in the buffer.
- There's a simple test set (see end of this file).
"""
import string
......
# A more or less complete user-defined wrapper around dictionary objects
"""A more or less complete user-defined wrapper around dictionary objects."""
class UserDict:
def __init__(self, dict=None):
......
# A more or less complete user-defined wrapper around list objects
"""A more or less complete user-defined wrapper around list objects."""
class UserList:
def __init__(self, list=None):
......
This diff is collapsed.
"""Classes for manipulating audio devices (currently only for Sun and SGI)"""
error = 'audiodev.error'
class Play_Audio_sgi:
......
#! /usr/bin/env python
# Conversions to/from base64 transport encoding as per RFC-1521.
#
"""Conversions to/from base64 transport encoding as per RFC-1521."""
# Modified 04-Oct-95 by Jack to use binascii module
import binascii
......@@ -9,69 +9,71 @@ import binascii
MAXLINESIZE = 76 # Excluding the CRLF
MAXBINSIZE = (MAXLINESIZE/4)*3
# Encode a file.
def encode(input, output):
while 1:
s = input.read(MAXBINSIZE)
if not s: break
while len(s) < MAXBINSIZE:
ns = input.read(MAXBINSIZE-len(s))
if not ns: break
s = s + ns
line = binascii.b2a_base64(s)
output.write(line)
"""Encode a file."""
while 1:
s = input.read(MAXBINSIZE)
if not s: break
while len(s) < MAXBINSIZE:
ns = input.read(MAXBINSIZE-len(s))
if not ns: break
s = s + ns
line = binascii.b2a_base64(s)
output.write(line)
# Decode a file.
def decode(input, output):
while 1:
line = input.readline()
if not line: break
s = binascii.a2b_base64(line)
output.write(s)
"""Decode a file."""
while 1:
line = input.readline()
if not line: break
s = binascii.a2b_base64(line)
output.write(s)
def encodestring(s):
import StringIO
f = StringIO.StringIO(s)
g = StringIO.StringIO()
encode(f, g)
return g.getvalue()
"""Encode a string."""
import StringIO
f = StringIO.StringIO(s)
g = StringIO.StringIO()
encode(f, g)
return g.getvalue()
def decodestring(s):
import StringIO
f = StringIO.StringIO(s)
g = StringIO.StringIO()
decode(f, g)
return g.getvalue()
"""Decode a string."""
import StringIO
f = StringIO.StringIO(s)
g = StringIO.StringIO()
decode(f, g)
return g.getvalue()
# Small test program
def test():
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print """usage: basd64 [-d] [-e] [-u] [-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: decode string 'Aladdin:open sesame'"""
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test1(); return
if args and args[0] != '-':
func(open(args[0], 'rb'), sys.stdout)
else:
func(sys.stdin, sys.stdout)
"""Small test program"""
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print """usage: basd64 [-d] [-e] [-u] [-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: decode string 'Aladdin:open sesame'"""
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test1(); return
if args and args[0] != '-':
func(open(args[0], 'rb'), sys.stdout)
else:
func(sys.stdin, sys.stdout)
def test1():
s0 = "Aladdin:open sesame"
s1 = encodestring(s0)
s2 = decodestring(s1)
print s0, `s1`, s2
s0 = "Aladdin:open sesame"
s1 = encodestring(s0)
s2 = decodestring(s1)
print s0, `s1`, s2
if __name__ == '__main__':
test()
test()
This diff is collapsed.
This diff is collapsed.
# Bisection algorithms
"""Bisection algorithms."""
# Insert item x in list a, and keep it sorted assuming a is sorted
def insort(a, x, lo=0, hi=None):
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x)
"""Insert item x in list a, and keep it sorted assuming a is sorted."""
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x)
# Find the index where to insert item x in list a, assuming a is sorted
def bisect(a, x, lo=0, hi=None):
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo
"""Find the index where to insert item x in list a, assuming a is sorted."""
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo
###############################
# Calendar printing functions #
###############################
"""Calendar printing functions"""
# Revision 2: uses funtions from built-in time module
......@@ -22,149 +20,149 @@ February = 2
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Full and abbreviated names of weekdays
day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', \
'Friday', 'Saturday', 'Sunday']
day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday']
day_abbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
# Full and abbreviated names of months (1-based arrays!!!)
month_name = ['', 'January', 'February', 'March', 'April', \
'May', 'June', 'July', 'August', \
'September', 'October', 'November', 'December']
month_abbr = [' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', \
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
month_name = ['', 'January', 'February', 'March', 'April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December']
month_abbr = [' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# Return 1 for leap years, 0 for non-leap years
def isleap(year):
return year % 4 == 0 and (year % 100 <> 0 or year % 400 == 0)
"""Return 1 for leap years, 0 for non-leap years."""
return year % 4 == 0 and (year % 100 <> 0 or year % 400 == 0)
# Return number of leap years in range [y1, y2)
# Assume y1 <= y2 and no funny (non-leap century) years
def leapdays(y1, y2):
return (y2+3)/4 - (y1+3)/4
"""Return number of leap years in range [y1, y2).
Assume y1 <= y2 and no funny (non-leap century) years."""
return (y2+3)/4 - (y1+3)/4
# Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31)
def weekday(year, month, day):
secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
tuple = localtime(secs)
return tuple[6]
"""Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31)."""
secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
tuple = localtime(secs)
return tuple[6]
# Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month
def monthrange(year, month):
if not 1 <= month <= 12: raise ValueError, 'bad month number'
day1 = weekday(year, month, 1)
ndays = mdays[month] + (month == February and isleap(year))
return day1, ndays
"""Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month."""
if not 1 <= month <= 12: raise ValueError, 'bad month number'
day1 = weekday(year, month, 1)
ndays = mdays[month] + (month == February and isleap(year))
return day1, ndays
# Return a matrix representing a month's calendar
# Each row represents a week; days outside this month are zero
def _monthcalendar(year, month):
day1, ndays = monthrange(year, month)
rows = []
r7 = range(7)
day = 1 - day1
while day <= ndays:
row = [0, 0, 0, 0, 0, 0, 0]
for i in r7:
if 1 <= day <= ndays: row[i] = day
day = day + 1
rows.append(row)
return rows
# Caching interface to _monthcalendar
"""Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero."""
day1, ndays = monthrange(year, month)
rows = []
r7 = range(7)
day = 1 - day1
while day <= ndays:
row = [0, 0, 0, 0, 0, 0, 0]
for i in r7:
if 1 <= day <= ndays: row[i] = day
day = day + 1
rows.append(row)
return rows
_mc_cache = {}
def monthcalendar(year, month):
key = (year, month)
if _mc_cache.has_key(key):
return _mc_cache[key]
else:
_mc_cache[key] = ret = _monthcalendar(year, month)
return ret
# Center a string in a field
"""Caching interface to _monthcalendar."""
key = (year, month)
if _mc_cache.has_key(key):
return _mc_cache[key]
else:
_mc_cache[key] = ret = _monthcalendar(year, month)
return ret
def _center(str, width):
n = width - len(str)
if n <= 0: return str
return ' '*((n+1)/2) + str + ' '*((n)/2)
"""Center a string in a field."""
n = width - len(str)
if n <= 0: return str
return ' '*((n+1)/2) + str + ' '*((n)/2)
# XXX The following code knows that print separates items with space!
# Print a single week (no newline)
def prweek(week, width):
for day in week:
if day == 0: s = ''
else: s = `day`
print _center(s, width),
"""Print a single week (no newline)."""
for day in week:
if day == 0: s = ''
else: s = `day`
print _center(s, width),
# Return a header for a week
def weekheader(width):
str = ''
if width >= 9: names = day_name
else: names = day_abbr
for i in range(7):
if str: str = str + ' '
str = str + _center(names[i%7][:width], width)
return str
# Print a month's calendar
"""Return a header for a week."""
str = ''
if width >= 9: names = day_name
else: names = day_abbr
for i in range(7):
if str: str = str + ' '
str = str + _center(names[i%7][:width], width)
return str
def prmonth(year, month, w = 0, l = 0):
w = max(2, w)
l = max(1, l)
print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1),
print '\n'*l,
print weekheader(w),
print '\n'*l,
for week in monthcalendar(year, month):
prweek(week, w)
print '\n'*l,
"""Print a month's calendar."""
w = max(2, w)
l = max(1, l)
print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1),
print '\n'*l,
print weekheader(w),
print '\n'*l,
for week in monthcalendar(year, month):
prweek(week, w)
print '\n'*l,
# Spacing of month columns
_colwidth = 7*3 - 1 # Amount printed by prweek()
_spacing = ' '*4 # Spaces between columns
_colwidth = 7*3 - 1 # Amount printed by prweek()
_spacing = ' '*4 # Spaces between columns
# 3-column formatting for year calendars
def format3c(a, b, c):
print _center(a, _colwidth),
print _spacing,
print _center(b, _colwidth),
print _spacing,
print _center(c, _colwidth)
"""3-column formatting for year calendars"""
print _center(a, _colwidth),
print _spacing,
print _center(b, _colwidth),
print _spacing,
print _center(c, _colwidth)
# Print a year's calendar
def prcal(year):
header = weekheader(2)
format3c('', `year`, '')
for q in range(January, January+12, 3):
print
format3c(month_name[q], month_name[q+1], month_name[q+2])
format3c(header, header, header)
data = []
height = 0
for month in range(q, q+3):
cal = monthcalendar(year, month)
if len(cal) > height: height = len(cal)
data.append(cal)
for i in range(height):
for cal in data:
if i >= len(cal):
print ' '*_colwidth,
else:
prweek(cal[i], 2)
print _spacing,
print
# Unrelated but handy function to calculate Unix timestamp from GMT
"""Print a year's calendar."""
header = weekheader(2)
format3c('', `year`, '')
for q in range(January, January+12, 3):
print
format3c(month_name[q], month_name[q+1], month_name[q+2])
format3c(header, header, header)
data = []
height = 0
for month in range(q, q+3):
cal = monthcalendar(year, month)
if len(cal) > height: height = len(cal)
data.append(cal)
for i in range(height):
for cal in data:
if i >= len(cal):
print ' '*_colwidth,
else:
prweek(cal[i], 2)
print _spacing,
print
EPOCH = 1970
def timegm(tuple):
year, month, day, hour, minute, second = tuple[:6]
assert year >= EPOCH
assert 1 <= month <= 12
days = 365*(year-EPOCH) + leapdays(EPOCH, year)
for i in range(1, month):
days = days + mdays[i]
if month > 2 and isleap(year):
days = days + 1
days = days + day - 1
hours = days*24 + hour
minutes = hours*60 + minute
seconds = minutes*60 + second
return seconds
"""Unrelated but handy function to calculate Unix timestamp from GMT."""
year, month, day, hour, minute, second = tuple[:6]
assert year >= EPOCH
assert 1 <= month <= 12
days = 365*(year-EPOCH) + leapdays(EPOCH, year)
for i in range(1, month):
days = days + mdays[i]
if month > 2 and isleap(year):
days = days + 1
days = days + day - 1
hours = days*24 + hour
minutes = hours*60 + minute
seconds = minutes*60 + second
return seconds
This diff is collapsed.
# Module 'cmp'
"""Efficiently compare files, boolean outcome only (equal / not equal).
# Efficiently compare files, boolean outcome only (equal / not equal).
# Tricks (used in this order):
# - Files with identical type, size & mtime are assumed to be clones
# - Files with different type or size cannot be identical
# - We keep a cache of outcomes of earlier comparisons
# - We don't fork a process to run 'cmp' but read the files ourselves
Tricks (used in this order):
- Files with identical type, size & mtime are assumed to be clones
- Files with different type or size cannot be identical
- We keep a cache of outcomes of earlier comparisons
- We don't fork a process to run 'cmp' but read the files ourselves
"""
import os
cache = {}
def cmp(f1, f2, shallow=1): # Compare two files, use the cache if possible.
# Return 1 for identical files, 0 for different.
# Raise exceptions if either file could not be statted, read, etc.
s1, s2 = sig(os.stat(f1)), sig(os.stat(f2))
if s1[0] <> 8 or s2[0] <> 8:
# Either is a not a plain file -- always report as different
return 0
if shallow and s1 == s2:
# type, size & mtime match -- report same
return 1
if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother
# types or sizes differ -- report different
return 0
# same type and size -- look in the cache
key = (f1, f2)
try:
cs1, cs2, outcome = cache[key]
# cache hit
if s1 == cs1 and s2 == cs2:
# cached signatures match
return outcome
# stale cached signature(s)
except KeyError:
# cache miss
pass
# really compare
outcome = do_cmp(f1, f2)
cache[key] = s1, s2, outcome
return outcome
def cmp(f1, f2, shallow=1):
"""Compare two files, use the cache if possible.
Return 1 for identical files, 0 for different.
Raise exceptions if either file could not be statted, read, etc."""
s1, s2 = sig(os.stat(f1)), sig(os.stat(f2))
if s1[0] <> 8 or s2[0] <> 8:
# Either is a not a plain file -- always report as different
return 0
if shallow and s1 == s2:
# type, size & mtime match -- report same
return 1
if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother
# types or sizes differ -- report different
return 0
# same type and size -- look in the cache
key = (f1, f2)
try:
cs1, cs2, outcome = cache[key]
# cache hit
if s1 == cs1 and s2 == cs2:
# cached signatures match
return outcome
# stale cached signature(s)
except KeyError:
# cache miss
pass
# really compare
outcome = do_cmp(f1, f2)
cache[key] = s1, s2, outcome
return outcome
def sig(st): # Return signature (i.e., type, size, mtime) from raw stat data
# 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid
# 6-9: st_size, st_atime, st_mtime, st_ctime
type = st[0] / 4096
size = st[6]
mtime = st[8]
return type, size, mtime
def sig(st):
"""Return signature (i.e., type, size, mtime) from raw stat data
0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid
6-9: st_size, st_atime, st_mtime, st_ctime"""
type = st[0] / 4096
size = st[6]
mtime = st[8]
return type, size, mtime
def do_cmp(f1, f2): # Compare two files, really
bufsize = 8*1024 # Could be tuned
fp1 = open(f1, 'rb')
fp2 = open(f2, 'rb')
while 1:
b1 = fp1.read(bufsize)
b2 = fp2.read(bufsize)
if b1 <> b2: return 0
if not b1: return 1
def do_cmp(f1, f2):
"""Compare two files, really."""
bufsize = 8*1024 # Could be tuned
fp1 = open(f1, 'rb')
fp2 = open(f2, 'rb')
while 1:
b1 = fp1.read(bufsize)
b2 = fp2.read(bufsize)
if b1 <> b2: return 0
if not b1: return 1
This diff is collapsed.
# Helper to provide extensibility for pickle/cPickle.
"""Helper to provide extensibility for pickle/cPickle."""
dispatch_table = {}
safe_constructors = {}
......
This diff is collapsed.
This diff is collapsed.
# General floating point formatting functions.
"""General floating point formatting functions.
# Functions:
# fix(x, digits_behind)
# sci(x, digits_behind)
Functions:
fix(x, digits_behind)
sci(x, digits_behind)
# Each takes a number or a string and a number of digits as arguments.
# Parameters:
# x: number to be formatted; or a string resembling a number
# digits_behind: number of digits behind the decimal point
Each takes a number or a string and a number of digits as arguments.
Parameters:
x: number to be formatted; or a string resembling a number
digits_behind: number of digits behind the decimal point
"""
import re
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment