1. python_mirrors
  2. cpython-fullhistory

Commits

cvs2svn  committed 20f984c

This commit was manufactured by cvs2svn to create tag 'release101'.

  • Participants
  • Parent commits bafc533
  • Branches legacy-trunk
  • Tags v1.0.1

Comments (0)

Files changed (459)

File Demo/Makefile

  • Ignore whitespace
-all:
-		@echo Nothing to make in this directory.
-
-clean:
-		find . '(' -name '*.pyc' -o -name '*.fdc' \
-			-o -name core -o -name '*~' \
-			-o -name '[@,#]*' -o -name '*.old' \
-			-o -name '*.orig' -o -name '*.rej' \
-			-o -name '*.bak' ')' \
-			-print -exec rm -f {} ';'
-
-clobber:	clean

File Demo/README

  • Ignore whitespace
-This directory contains various demonstrations of what you can do with
-Python.  Most demos are grouped sub(sub*)directories according to
-required optional built-in modules or specific platform; there is also
-a set of generally useful scripts and there are some more-or-less
-complete applications.
-
-classes		Some examples of how to use classes.
-
-embed		An example of embedding Python in another application.
-
-ibrowse		An Emacs info file browser (uses stdwin).
-		See also ../doc (the Python library documentation can
-		be converted to info format).
-
-md5test		Test program for the optional md5 module.
-
-rpc		A set of classes for building clients and servers for
-		Sun RPC.
-
-rsa		An RSA public-key cryptosystem (needs mpz and md5).
-
-scripts		Some useful Python scripts that I put in my bin
-		directory.  No optional built-in modules needed.
-
-sockets		Examples for the new built-in module 'socket'.
-
-sgi		Demos that only run on Silicon Graphics machines.
-		These require at least one of the optional built-in
-		modules that only make sense for the SGI, such as
-		'gl', 'al', and 'sv'.  Split in subdirectories
-		per subject.
-
-stdwin		Demos that use the STDWIN library.  Require the 'stdwin'
-		built-in module.
-
-threads		Demos that use the 'thread' module.  (Currently these
-		only run on SGIs, but this may change in the future.)
-
-WARNING: many scripts are executable and have a first line saying
-
-	#! /usr/local/bin/python
-
-This is unlikely to give good results unless you've really installed
-the latest version python there.  Edit the first line before
-installing such scripts; to try them out, you can just say "python
-foo.py" or enter python interactively and say "import foo".

File Demo/classes/Complex.py

  • Ignore whitespace
-# Complex numbers
-
-
-from math import sqrt
-
-
-class complex:
-
-	def __init__(self, re, im):
-		self.re = float(re)
-		self.im = float(im)
-
-	def __coerce__(self, other):
-		if type(other) == type(self):
-			if other.__class__ == self.__class__:
-				return self, other
-			else:
-				raise TypeError, 'cannot coerce to complex'
-		else:
-			# The cast to float() may raise an exception!
-			return self, complex(float(other), 0.0)
-
-	def __repr__(self):
-		return 'complex' + `self.re, self.im`
-
-	def __cmp__(a, b):
-		a = a.__abs__()
-		b = b.__abs__()
-		return (a > b) - (a < b)
-
-	def __float__(self):
-		if self.im:
-			raise ValueError, 'cannot convert complex to float'
-		return float(self.re)
-
-	def __long__(self):
-		return long(float(self))
-
-	def __int__(self):
-		return int(float(self))
-
-	def __abs__(self):
-		# XXX overflow?
-		return sqrt(self.re*self.re + self.im*self.im)
-
-	def __add__(a, b):
-		return complex(a.re + b.re, a.im + b.im)
-
-	def __sub__(a, b):
-		return complex(a.re - b.re, a.im - b.im)
-
-	def __mul__(a, b):
-		return complex(a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re)
-
-	def __div__(a, b):
-		q = (b.re*b.re + b.im*b.im)
-		re = (a.re*b.re + a.im*b.im) / q
-		im = (a.im*b.re - b.im*a.re) / q
-		return complex(re, im)
-
-	def __neg__(self):
-		return complex(-self.re, -self.im)
-
-
-def test():
-	a = complex(2, 0)
-	b = complex(3, 4)
-	print a
-	print b
-	print a+b
-	print a-b
-	print a*b
-	print a/b
-	print b+a
-	print b-a
-	print b*a
-	print b/a
-	i = complex(0, 1)
-	print i, i*i, i*i*i, i*i*i*i
-	j = complex(1, 1)
-	print j, j*j, j*j*j, j*j*j*j
-	print abs(j), abs(j*j), abs(j*j*j), abs(j*j*j*j)
-	print i/-i
-
-test()

File Demo/classes/Dates.py

  • Ignore whitespace
-# Class Date supplies date objects that support date arithmetic.
-#
-# Date(month,day,year) returns a Date object.  An instance prints as,
-# e.g., 'Mon 16 Aug 1993'.
-#
-# Addition, subtraction, comparison operators, min, max, and sorting
-# all work as expected for date objects:  int+date or date+int returns
-# the date `int' days from `date'; date+date raises an exception;
-# date-int returns the date `int' days before `date'; date2-date1 returns
-# an integer, the number of days from date1 to date2; int-date raises an
-# exception; date1 < date2 is true iff date1 occurs before date2 (&
-# similarly for other comparisons); min(date1,date2) is the earlier of
-# the two dates and max(date1,date2) the later; and date objects can be
-# used as dictionary keys.
-#
-# Date objects support one visible method, date.weekday().  This returns
-# the day of the week the date falls on, as a string.
-#
-# Date objects also have 4 (conceptually) read-only data attributes:
-#   .month  in 1..12
-#   .day    in 1..31
-#   .year   int or long int
-#   .ord    the ordinal of the date relative to an arbitrary staring point
-#
-# The Dates module also supplies function today(), which returns the
-# current date as a date object.
-#
-# Those entranced by calendar trivia will be disappointed, as no attempt
-# has been made to accommodate the Julian (etc) system.  On the other
-# hand, at least this package knows that 2000 is a leap year but 2100
-# isn't, and works fine for years with a hundred decimal digits <wink>.
-
-# Tim Peters   tim@ksr.com
-# not speaking for Kendall Square Research Corp
-
-_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
-		 'June', 'July', 'August', 'September', 'October',
-		 'November', 'December' ]
-
-_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday',
-	       'Tuesday', 'Wednesday', 'Thursday' ]
-
-_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
-
-_DAYS_BEFORE_MONTH = []
-dbm = 0
-for dim in _DAYS_IN_MONTH:
-    _DAYS_BEFORE_MONTH.append(dbm)
-    dbm = dbm + dim
-del dbm, dim
-
-_INT_TYPES = type(1), type(1L)
-
-def _is_leap( year ):		# 1 if leap year, else 0
-    if year % 4 != 0: return 0
-    if year % 400 == 0: return 1
-    return year % 100 != 0
-
-def _days_in_year( year ):	# number of days in year
-    return 365 + _is_leap(year)
-
-def _days_before_year( year ):	# number of days before year
-    return year*365L + (year+3)/4 - (year+99)/100 + (year+399)/400
-
-def _days_in_month( month, year ):	# number of days in month of year
-    if month == 2 and _is_leap(year): return 29
-    return _DAYS_IN_MONTH[month-1]
-
-def _days_before_month( month, year ):	# number of days in year before month
-    return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year))
-
-def _date2num( date ):		# compute ordinal of date.month,day,year
-    return _days_before_year( date.year ) + \
-	   _days_before_month( date.month, date.year ) + \
-	   date.day
-
-_DI400Y = _days_before_year( 400 )	# number of days in 400 years
-
-def _num2date( n ):		# return date with ordinal n
-    if type(n) not in _INT_TYPES:
-	raise TypeError, 'argument must be integer: ' + `type(n)`
-
-    ans = Date(1,1,1)	# arguments irrelevant; just getting a Date obj
-    ans.ord = n
-
-    n400 = (n-1)/_DI400Y		# # of 400-year blocks preceding
-    year, n = 400 * n400, n - _DI400Y * n400
-    more = n / 365
-    dby = _days_before_year( more )
-    if dby >= n:
-	more = more - 1
-	dby = dby - _days_in_year( more )
-    year, n = year + more, int(n - dby)
-
-    try: year = int(year)		# chop to int, if it fits
-    except ValueError: pass
-
-    month = min( n/29 + 1, 12 )
-    dbm = _days_before_month( month, year )
-    if dbm >= n:
-	month = month - 1
-	dbm = dbm - _days_in_month( month, year )
-
-    ans.month, ans.day, ans.year = month, n-dbm, year
-    return ans
-
-def _num2day( n ):	# return weekday name of day with ordinal n
-    return _DAY_NAMES[ int(n % 7) ]
-
-
-class Date:
-    def __init__( self, month, day, year ):
-	if not 1 <= month <= 12:
-	    raise ValueError, 'month must be in 1..12: ' + `month`
-	dim = _days_in_month( month, year )
-	if not 1 <= day <= dim:
-	    raise ValueError, 'day must be in 1..' + `dim` + ': ' + `day`
-	self.month, self.day, self.year = month, day, year
-	self.ord = _date2num( self )
-
-    def __cmp__( self, other ):
-	return cmp( self.ord, other.ord )
-
-    # define a hash function so dates can be used as dictionary keys
-    def __hash__( self ):
-	return hash( self.ord )
-
-    # print as, e.g., Mon 16 Aug 1993
-    def __repr__( self ):
-	return '%.3s %2d %.3s ' % (
-	      self.weekday(),
-	      self.day,
-	      _MONTH_NAMES[self.month-1] ) + `self.year`
-
-    # automatic coercion is a pain for date arithmetic, since e.g.
-    # date-date and date-int mean different things.  So, in order to
-    # sneak integers past Python's coercion rules without losing the info
-    # that they're really integers (& not dates!), integers are disguised
-    # as instances of the derived class _DisguisedInt.  That this works
-    # relies on undocumented behavior of Python's coercion rules.
-    def __coerce__( self, other ):
-	if type(other) in _INT_TYPES:
-	    return self, _DisguisedInt(other)
-	# if another Date, fine
-	if type(other) is type(self) and other.__class__ is Date:
-	    return self, other
-
-    # Python coerces int+date, but not date+int; in the former case,
-    # _DisguisedInt.__add__ handles it, so we only need to do
-    # date+int here
-    def __add__( self, n ):
-	if type(n) not in _INT_TYPES:
-	    raise TypeError, 'can\'t add ' + `type(n)` + ' to date'
-	return _num2date( self.ord + n )
-
-    # Python coerces all of int-date, date-int and date-date; the first
-    # case winds up in _DisguisedInt.__sub__, leaving the latter two
-    # for us
-    def __sub__( self, other ):
-	if other.__class__ is _DisguisedInt:	# date-int
-	    return _num2date( self.ord - other.ord )
-	else:
-	    return self.ord - other.ord		# date-date
-
-    def weekday( self ):
-	return _num2day( self.ord )
-
-# see comments before Date.__add__
-class _DisguisedInt( Date ):
-    def __init__( self, n ):
-	self.ord = n
-
-    # handle int+date
-    def __add__( self, other ):
-	return other.__add__( self.ord )
-
-    # complain about int-date
-    def __sub__( self, other ):
-	raise TypeError, 'Can\'t subtract date from integer'
-
-def today():
-    import time
-    local = time.localtime(time.time())
-    return Date( local[1], local[2], local[0] )
-
-DateTestError = 'DateTestError'
-def test( firstyear, lastyear ):
-    a = Date(9,30,1913)
-    b = Date(9,30,1914)
-    if `a` != 'Tue 30 Sep 1913':
-	raise DateTestError, '__repr__ failure'
-    if (not a < b) or a == b or a > b or b != b or \
-	  a != 698982 or 698982 != a or \
-	  (not a > 5) or (not 5 < a):
-	raise DateTestError, '__cmp__ failure'
-    if a+365 != b or 365+a != b:
-	raise DateTestError, '__add__ failure'
-    if b-a != 365 or b-365 != a:
-	raise DateTestError, '__sub__ failure'
-    try:
-	x = 1 - a
-	raise DateTestError, 'int-date should have failed'
-    except TypeError:
-	pass
-    try:
-	x = a + b
-	raise DateTestError, 'date+date should have failed'
-    except TypeError:
-	pass
-    if a.weekday() != 'Tuesday':
-	raise DateTestError, 'weekday() failure'
-    if max(a,b) is not b or min(a,b) is not a:
-	raise DateTestError, 'min/max failure'
-    d = {a-1:b, b:a+1}
-    if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
-	raise DateTestError, 'dictionary failure'
-
-    # verify date<->number conversions for first and last days for
-    # all years in firstyear .. lastyear
-
-    lord = _days_before_year( firstyear )
-    y = firstyear
-    while y <= lastyear:
-	ford = lord + 1
-	lord = ford + _days_in_year(y) - 1
-	fd, ld = Date(1,1,y), Date(12,31,y)
-	if (fd.ord,ld.ord) != (ford,lord):
-	    raise DateTestError, ('date->num failed', y)
-	fd, ld = _num2date(ford), _num2date(lord)
-	if (1,1,y,12,31,y) != \
-	   (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
-	    raise DateTestError, ('num->date failed', y)
-	y = y + 1

File Demo/classes/Dbm.py

  • Ignore whitespace
-# A wrapper around the (optional) built-in class dbm, supporting keys
-# and values of almost any type instead of just string.
-# (Actually, this works only for keys and values that can be read back
-# correctly after being converted to a string.)
-
-
-class Dbm:
-
-	def __init__(self, filename, mode, perm):
-		import dbm
-		self.db = dbm.open(filename, mode, perm)
-
-	def __repr__(self):
-		s = ''
-		for key in self.keys():
-			t = `key` + ': ' + `self[key]`
-			if s: t = ', ' + t
-			s = s + t
-		return '{' + s + '}'
-
-	def __len__(self):
-		return len(self.db)
-
-	def __getitem__(self, key):
-		return eval(self.db[`key`])
-
-	def __setitem__(self, key, value):
-		self.db[`key`] = `value`
-
-	def __delitem__(self, key):
-		del self.db[`key`]
-
-	def keys(self):
-		res = []
-		for key in self.db.keys():
-			res.append(eval(key))
-		return res
-
-	def has_key(self, key):
-		return self.db.has_key(`key`)
-
-
-def test():
-	d = Dbm('@dbm', 'rw', 0600)
-	print d
-	while 1:
-		try:
-			key = input('key: ')
-			if d.has_key(key):
-				value = d[key]
-				print 'currently:', value
-			value = input('value: ')
-			if value == None:
-				del d[key]
-			else:
-				d[key] = value
-		except KeyboardInterrupt:
-			print ''
-			print d
-		except EOFError:
-			print '[eof]'
-			break
-	print d
-
-
-test()

File Demo/classes/README

  • Ignore whitespace
-Examples of classes that implement special operators (see reference manual):
-
-Complex.py	Complex numbers
-Dates.py	Date manipulation package by Tim Peters
-Dbm.py		Wrapper around built-in dbm, supporting	arbitrary values
-Range.py	Example of a generator: re-implement built-in range()
-Rat.py		Rational numbers
-Rev.py		Yield the reverse of a sequence
-Vec.py		A simple vector class
-bitvec.py	A bit-vector class by Jan-Hein B\"uhrman
-
-(For straightforward examples of basic class features, such as use of
-methods and inheritance, see the library code -- especially the window
-modules are full of them.)

File Demo/classes/Range.py

  • Ignore whitespace
-# Example of a generator: re-implement the built-in range function
-# without actually constructing the list of values.  (It turns out
-# that the built-in function is about 20 times faster -- that's why
-# it's built-in. :-)
-
-
-# Wrapper function to emulate the complicated range() arguments
-
-def range(*a):
-	if len(a) == 1:
-		start, stop, step = 0, a[0], 1
-	elif len(a) == 2:
-		start, stop = a
-		step = 1
-	elif len(a) == 3:
-		start, stop, step = a
-	else:
-		raise TypeError, 'range() needs 1-3 arguments'
-	return Range(start, stop, step)
-	
-
-# Class implementing a range object.
-# To the user the instances feel like immutable sequences
-# (and you can't concatenate or slice them)
-
-class Range:
-
-	# initialization -- should be called only by range() above
-	def __init__(self, start, stop, step):
-		if step == 0:
-			raise ValueError, 'range() called with zero step'
-		self.start = start
-		self.stop = stop
-		self.step = step
-		self.len = max(0, int((self.stop - self.start) / self.step))
-
-	# implement `x` and is also used by print x
-	def __repr__(self):
-		return 'range' + `self.start, self.stop, self.step`
-
-	# implement len(x)
-	def __len__(self):
-		return self.len
-
-	# implement x[i]
-	def __getitem__(self, i):
-		if 0 <= i < self.len:
-			return self.start + self.step * i
-		else:
-			raise IndexError, 'range[i] index out of range'
-
-
-# Small test program
-
-def test():
-	import time, __builtin__
-	print range(10), range(-10, 10), range(0, 10, 2)
-	for i in range(100, -100, -10): print i,
-	print
-	t1 = time.millitimer()
-	for i in range(1000):
-		pass
-	t2 = time.millitimer()
-	for i in __builtin__.range(1000):
-		pass
-	t3 = time.millitimer()
-	print t2-t1, 'msec (class)'
-	print t3-t2, 'msec (built-in)'
-
-
-test()

File Demo/classes/Rat.py

  • Ignore whitespace
-# Rational numbers
-
-
-def rat(num, den):
-	return Rat(num, den)
-
-
-def gcd(a, b):
-	while b:
-		a, b = b, a%b
-	return a
-
-
-class Rat:
-
-	def __init__(self, num, den):
-		if den == 0:
-			raise ZeroDivisionError, 'rat(x, 0)'
-		g = gcd(num, den)
-		self.num = num/g
-		self.den = den/g
-
-	def __repr__(self):
-		return 'rat' + `self.num, self.den`
-
-	def __cmp__(a, b):
-		c = a-b
-		if c.num < 0:
-			return -1
-		if c.num > 0:
-			return 1
-		return 0
-
-	def __float__(self):
-		return float(self.num) / float(self.den)
-
-	def __long__(self):
-		return long(self.num) / long(self.den)
-
-	def __int__(self):
-		return int(self.num / self.den)
-
-	def __coerce__(a, b):
-		t = type(b)
-		if t == type(0):
-			return a, rat(b, 1)
-		if t == type(0L):
-			return a, rat(b, 1L)
-		if t == type(0.0):
-			return a.__float__(), b
-		if t == type(a) and a.__class__ == b.__class__:
-			return a, b
-		raise TypeError, 'Rat.__coerce__: bad other arg'
-
-	def __add__(a, b):
-		if type(b) <> type(a):
-			a, b = a.__coerce__(b)
-			return a + b
-		return rat(a.num*b.den + b.num*a.den, a.den*b.den)
-
-	def __sub__(a, b):
-		return rat(a.num*b.den - b.num*a.den, a.den*b.den)
-
-	def __mul__(a, b):
-		if type(b) <> type(a):
-			a, b = a.__coerce__(b)
-			return a * b
-		return rat(a.num*b.num, a.den*b.den)
-
-	def __div__(a, b):
-		return rat(a.num*b.den, a.den*b.num)
-
-	def __neg__(self):
-		return rat(-self.num, self.den)
-
-
-def test():
-	print rat(-1L, 1)
-	print rat(1, -1)
-	a = rat(1, 10)
-	print int(a), long(a), float(a)
-	b = rat(2, 5)
-	l = [a+b, a-b, a*b, a/b]
-	print l
-	l.sort()
-	print l
-	print rat(0, 1)
-	print a+1
-	print a+1L
-	print a+1.0
-	try:
-		print rat(1, 0)
-		raise SystemError, 'should have been ZeroDivisionError'
-	except ZeroDivisionError:
-		print 'OK'
-
-test()

File Demo/classes/Rev.py

  • Ignore whitespace
-# A class which presents the reverse of a sequence without duplicating it.
-# From: "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu>
-
-# It works on mutable or inmutable sequences.
-#
-# >>> for c in Rev( 'Hello World!' ) : sys.stdout.write( c )
-# ... else: sys.stdout.write( '\n' )
-# ... 
-# !dlroW olleH
-#
-# The .forw is so you can use anonymous sequences in __init__, and still
-# keep a reference the forward sequence. ) 
-# If you give it a non-anonymous mutable sequence, the reverse sequence
-# will track the updated values. ( but not reassignment! - another 
-# good reason to use anonymous values in creating the sequence to avoid
-# confusion. Maybe it should be change to copy input sequence to break
-# the connection completely ? )
-#
-# >>> nnn = range( 0, 3 )
-# >>> rnn = Rev( nnn )
-# >>> for n in rnn: print n
-# ... 
-# 2
-# 1
-# 0
-# >>> for n in range( 4, 6 ): nnn.append( n )	# update nnn
-# ... 
-# >>> for n in rnn: print n	# prints reversed updated values
-# ... 
-# 5
-# 4
-# 2
-# 1
-# 0
-# >>> nnn = nnn[1:-1]
-# >>> nnn
-# [1, 2, 4]
-# >>> for n in rnn: print n	# prints reversed values of old nnn
-# ... 
-# 5
-# 4
-# 2
-# 1
-# 0
-# >>> 
-#
-# WH = Rev( 'Hello World!' )
-# print WH.forw, WH.back
-# nnn = Rev( range( 1, 10 ) )
-# print nnn.forw
-# print nnn
-# 
-# produces output:
-# 
-# Hello World! !dlroW olleH
-# [1, 2, 3, 4, 5, 6, 7, 8, 9]
-# [9, 8, 7, 6, 5, 4, 3, 2, 1]
-# 
-# >>>rrr = Rev( nnn ) 
-# >>>rrr
-# <1, 2, 3, 4, 5, 6, 7, 8, 9>	
-
-from string import joinfields
-class Rev:
-	def __init__( self, seq ):
-		self.forw = seq
-		self.back = self
-	def __len__( self ):
-		return len( self.forw )
-	def __getitem__( self, j ):
-		return self.forw[ -( j + 1 ) ]
-	def __repr__( self ):
-		seq = self.forw
-		if type(seq) == type( [] ) : 
-			wrap = '[]'
-			sep = ', '
-		elif type(seq) == type( () ) : 
-			wrap = '()'
-			sep = ', '
-		elif type(seq) == type( '' ) : 
-			wrap = ''
-			sep = ''
-		else: 
-			wrap = '<>'
-			sep = ', ' 
-		outstrs = []
-		for item in self.back :
-			outstrs.append( str( item ) )
-		return wrap[:1] + joinfields( outstrs, sep ) + wrap[-1:]

File Demo/classes/Vec.py

  • Ignore whitespace
-# A simple vector class
-
-
-def vec(*v):
-	return apply(Vec, v)
-
-
-class Vec:
-
-	def __init__(self, *v):
-		self.v = []
-		for x in v:
-			self.v.append(x)
-
-
-	def fromlist(self, v):
-		self.v = []
-		if type(v) <> type([]):
-			raise TypeError
-		self.v = v[:]
-		return self
-
-
-	def __repr__(self):
-		return 'vec(' + `self.v`[1:-1] + ')'
-
-	def __len__(self):
-		return len(self.v)
-
-	def __getitem__(self, i):
-		return self.v[i]
-
-	def __add__(a, b):
-		# Element-wise addition
-		v = []
-		for i in range(len(a)):
-			v.append(a[i] + b[i])
-		return Vec().fromlist(v)
-
-	def __sub__(a, b):
-		# Element-wise subtraction
-		v = []
-		for i in range(len(a)):
-			v.append(a[i] - b[i])
-		return Vec().fromlist(v)
-
-	def __mul__(self, scalar):
-		# Multiply by scalar
-		v = []
-		for i in range(len(self.v)):
-			v.append(self.v[i]*scalar)
-		return Vec().fromlist(v)
-
-
-
-def test():
-	a = vec(1, 2, 3)
-	b = vec(3, 2, 1)
-	print a
-	print b
-	print a+b
-	print a*3.0
-
-test()

File Demo/classes/bitvec.py

  • Ignore whitespace
-#
-# this is a rather strict implementation of a bit vector class
-# it is accessed the same way as an array of python-ints, except
-# the value must be 0 or 1
-#
-
-import sys; rprt = sys.stderr.write #for debugging
-
-error = 'bitvec.error'
-
-
-def _check_value(value):
-	if type(value) != type(0) or not 0 <= value < 2:
-		raise error, 'bitvec() items must have int value 0 or 1'
-
-
-import math
-
-def _compute_len(param):
-	mant, l = math.frexp(float(param))
-	bitmask = 1L << l
-	if bitmask <= param:
-		raise 'FATAL', '(param, l) = ' + `param, l`
-	while l:
-		bitmask = bitmask >> 1
-		if param & bitmask:
-			break
-		l = l - 1
-	return l
-
-
-def _check_key(len, key):
-	if type(key) != type(0):
-		raise TypeError, 'sequence subscript not int'
-	if key < 0:
-		key = key + len
-	if not 0 <= key < len:
-		raise IndexError, 'list index out of range'
-	return key
-
-def _check_slice(len, i, j):
-	#the type is ok, Python already checked that
-	i, j = max(i, 0), min(len, j)
-	if i > j:
-		i = j
-	return i, j
-	
-
-class BitVec:
-
-	def __init__(self, *params):
-		self._data = 0L
-		self._len = 0
-		if not len(params):
-			pass
-		elif len(params) == 1:
-			param, = params
-			if type(param) == type([]):
-				value = 0L
-				bit_mask = 1L
-				for item in param:
-					# strict check
-					#_check_value(item)
-					if item:
-						value = value | bit_mask
-					bit_mask = bit_mask << 1
-				self._data = value
-				self._len = len(param)
-			elif type(param) == type(0L):
-				if param < 0:
-					raise error, 'bitvec() can\'t handle negative longs'
-				self._data = param
-				self._len = _compute_len(param)
-			else:
-				raise error, 'bitvec() requires array or long parameter'
-		elif len(params) == 2:
-			param, length = params
-			if type(param) == type(0L):
-				if param < 0:
-					raise error, \
-					  'can\'t handle negative longs'
-				self._data = param
-				if type(length) != type(0):
-					raise error, 'bitvec()\'s 2nd parameter must be int'
-				computed_length = _compute_len(param)
-				if computed_length > length:
-					print 'warning: bitvec() value is longer than the lenght indicates, truncating value'
-					self._data = self._data & \
-						  ((1L << length) - 1)
-				self._len = length
-			else:
-				raise error, 'bitvec() requires array or long parameter'
-		else:
-			raise error, 'bitvec() requires 0 -- 2 parameter(s)'
-
-		
-	def append(self, item):
-		#_check_value(item)
-		#self[self._len:self._len] = [item]
-		self[self._len:self._len] = \
-			  BitVec(long(not not item), 1)
-
-		
-	def count(self, value):
-		#_check_value(value)
-		if value:
-			data = self._data
-		else:
-			data = (~self)._data
-		count = 0
-		while data:
-			data, count = data >> 1, count + (data & 1 != 0)
-		return count
-
-
-	def index(self, value):
-		#_check_value(value):
-		if value:
-			data = self._data
-		else:
-			data = (~self)._data
-		index = 0
-		if not data:
-			raise ValueError, 'list.index(x): x not in list'
-		while not (data & 1):
-			data, index = data >> 1, index + 1
-		return index
-
-
-	def insert(self, index, item):
-		#_check_value(item)
-		#self[index:index] = [item]
-		self[index:index] = BitVec(long(not not item), 1)
-
-
-	def remove(self, value):
-		del self[self.index(value)]
-
-
-	def reverse(self):
-		#ouch, this one is expensive!
-		#for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i]
-		data, result = self._data, 0L
-		for i in range(self._len):
-			if not data:
-				result = result << (self._len - i)
-				break
-			result, data = (result << 1) | (data & 1), data >> 1
-		self._data = result
-
-		
-	def sort(self):
-		c = self.count(1)
-		self._data = ((1L << c) - 1) << (self._len - c)
-
-
-	def copy(self):
-		return BitVec(self._data, self._len)
-
-
-	def seq(self):
-		result = []
-		for i in self:
-			result.append(i)
-		return result
-		
-
-	def __repr__(self):
-		##rprt('<bitvec class instance object>.' + '__repr__()\n')
-		return 'bitvec' + `self._data, self._len`
-
-	def __cmp__(self, other, *rest):
-		#rprt(`self`+'.__cmp__'+`(other, ) + rest`+'\n')
-		if type(other) != type(self):
-			other = apply(bitvec, (other, ) + rest)
-		#expensive solution... recursive binary, with slicing
-		length = self._len
-		if length == 0 or other._len == 0:
-			return cmp(length, other._len)
-		if length != other._len:
-			min_lenght = min(length, other._len)
-			return cmp(self[:min_length], other[:min_length]) or \
-				  cmp(self[min_length:], other[min_length:])
-		#the lengths are the same now...
-		if self._data == other._data:
-			return 0
-		if length == 1:
-			return cmp(self[0], other[0])
-		else:
-			length = length >> 1
-			return cmp(self[:length], other[:length]) or \
-				  cmp(self[length:], other[length:])
-		
-
-	def __len__(self):
-		#rprt(`self`+'.__len__()\n')
-		return self._len
-
-	def __getitem__(self, key):
-		#rprt(`self`+'.__getitem__('+`key`+')\n')
-		key = _check_key(self._len, key)
-		return self._data & (1L << key) != 0
-
-	def __setitem__(self, key, value):
-		#rprt(`self`+'.__setitem__'+`key, value`+'\n')
-		key = _check_key(self._len, key)
-		#_check_value(value)
-		if value:
-			self._data = self._data | (1L << key)
-		else:
-			self._data = self._data & ~(1L << key)
-
-	def __delitem__(self, key):
-		#rprt(`self`+'.__delitem__('+`key`+')\n')
-		key = _check_key(self._len, key)
-		#el cheapo solution...
-		self._data = self[:key]._data | self[key+1:]._data >> key
-		self._len = self._len - 1
-
-	def __getslice__(self, i, j):
-		#rprt(`self`+'.__getslice__'+`i, j`+'\n')
-		i, j = _check_slice(self._len, i, j)
-		if i >= j:
-			return BitVec(0L, 0)
-		if i:
-			ndata = self._data >> i
-		else:
-			ndata = self._data
-		nlength = j - i
-		if j != self._len:
-			#we'll have to invent faster variants here
-			#e.g. mod_2exp
-			ndata = ndata & ((1L << nlength) - 1)
-		return BitVec(ndata, nlength)
-
-	def __setslice__(self, i, j, sequence, *rest):
-		#rprt(`self`+'.__setslice__'+`(i, j, sequence) + rest`+'\n')
-		i, j = _check_slice(self._len, i, j)
-		if type(sequence) != type(self):
-			sequence = apply(bitvec, (sequence, ) + rest)
-		#sequence is now of our own type
-		ls_part = self[:i]
-		ms_part = self[j:]
-		self._data = ls_part._data | \
-			  ((sequence._data | \
-			  (ms_part._data << sequence._len)) << ls_part._len)
-		self._len = self._len - j + i + sequence._len
-
-	def __delslice__(self, i, j):
-		#rprt(`self`+'.__delslice__'+`i, j`+'\n')
-		i, j = _check_slice(self._len, i, j)
-		if i == 0 and j == self._len:
-			self._data, self._len = 0L, 0
-		elif i < j:
-			self._data = self[:i]._data | (self[j:]._data >> i)
-			self._len = self._len - j + i
-
-	def __add__(self, other):
-		#rprt(`self`+'.__add__('+`other`+')\n')
-		retval = self.copy()
-		retval[self._len:self._len] = other
-		return retval
-
-	def __mul__(self, multiplier):
-		#rprt(`self`+'.__mul__('+`multiplier`+')\n')
-		if type(multiplier) != type(0):
-			raise TypeError, 'sequence subscript not int'
-		if multiplier <= 0:
-			return BitVec(0L, 0)
-		elif multiplier == 1:
-			return self.copy()
-		#handle special cases all 0 or all 1...
-		if self._data == 0L:
-			return BitVec(0L, self._len * multiplier)
-		elif (~self)._data == 0L:
-			return ~BitVec(0L, self._len * multiplier)
-		#otherwise el cheapo again...
-		retval = BitVec(0L, 0)
-		while multiplier:
-			retval, multiplier = retval + self, multiplier - 1
-		return retval
-
-	def __and__(self, otherseq, *rest):
-		#rprt(`self`+'.__and__'+`(otherseq, ) + rest`+'\n')
-		if type(otherseq) != type(self):
-			otherseq = apply(bitvec, (otherseq, ) + rest)
-		#sequence is now of our own type
-		return BitVec(self._data & otherseq._data, \
-			  min(self._len, otherseq._len))
-
-
-	def __xor__(self, otherseq, *rest):
-		#rprt(`self`+'.__xor__'+`(otherseq, ) + rest`+'\n')
-		if type(otherseq) != type(self):
-			otherseq = apply(bitvec, (otherseq, ) + rest)
-		#sequence is now of our own type
-		return BitVec(self._data ^ otherseq._data, \
-			  max(self._len, otherseq._len))
-
-
-	def __or__(self, otherseq, *rest):
-		#rprt(`self`+'.__or__'+`(otherseq, ) + rest`+'\n')
-		if type(otherseq) != type(self):
-			otherseq = apply(bitvec, (otherseq, ) + rest)
-		#sequence is now of our own type
-		return BitVec(self._data | otherseq._data, \
-			  max(self._len, otherseq._len))
-
-
-	def __invert__(self):
-		#rprt(`self`+'.__invert__()\n')
-		return BitVec(~self._data & ((1L << self._len) - 1), \
-			  self._len)
-
-	def __coerce__(self, otherseq, *rest):
-		#needed for *some* of the arithmetic operations
-		#rprt(`self`+'.__coerce__'+`(otherseq, ) + rest`+'\n')
-		if type(otherseq) != type(self):
-			otherseq = apply(bitvec, (otherseq, ) + rest)
-		return self, otherseq
-
-	def __int__(self):
-		return int(self._data)
-
-	def __long__(self):
-		return long(self._data)
-
-	def __float__(self):
-		return float(self._data)
-
-
-bitvec = BitVec

File Demo/classes/class.doc

  • Ignore whitespace
-New features of classes
-=======================
-
-A class can implement certain operations that are invoked by special
-syntax (such as subscription or arithmetic operations) by defining
-methods with special names.
-
-
-Special methods for any type
-----------------------------
-
-__repr__(self) --> string
-
-Used by the print statement and conversions (reverse quotes) to
-compute the string representation of an object.
-
-__cmp__(self, other) --> int
-
-Used by all comparison operations.  Should return -1 if self<other, 0
-if self==other, +1 if self>other.  Due to limitations in the
-interpreter, exceptions raised by comparisons are ignored, and the
-objects will be considered equal in this case.
-
-
-Special methods for sequence and mapping types
-----------------------------------------------
-
-__len__(self) --> int
-
-Used by the built-in function len().  Should return the length of the
-object, which should be >= 0.  Also, an object whose __len__() method
-returns 0 
-
-__getitem__(self, key) --> value
-
-Used to implement value = self[key].  Note that the special
-interpretation of negative keys (if the class wishes to emulate a
-sequence type) is up to the __getitem__ method.
-
-__setitem__(self, key, value)
-
-Used to implement self[key] = value.  Same note as for __getitem__.
-
-__delitem__(self, key)
-
-Used to implement del self[key].  Same note as for __getitem__.
-
-
-Special methods for sequence types
-----------------------------------
-
-__getslice__(self, i, j) --> sequence
-
-Used to implement self[i:j].  Note that missing i or j are replaced by
-0 or len(self), respectively, and len(self) has been added to negative
-i or j.
-
-__setslice__(self, i, j, sequence)
-
-Used to implement self[i:j] = value.  Same note as for __getslice__.
-
-__delslice__(self, i, j)
-
-Used to implement del self[i:j].  Same note as for __getslice__.
-
-
-Special methods for numeric types
----------------------------------
-
-__add__, __sub__, __mul__, __div__, __mod__, __divmod__, __pow__,
-__lshift__, __rshift__, __and__, __xor__, __or__
-
-Used to implement the binary arithmetic operations (divmod and pow are
-called by built-in functions).  All have the call pattern
-func(self, other) --> number.
-
-__neg__, __pos__, __abs__, __invert__
-
-Used to implement the unary arithmetic operations (-, +, abs and ~).
-All have the call pattern func(self) --> number.
-
-__nonzero__(self) --> int
-
-Used to implement boolean testing.  An alternative name for this
-method is __len__.
-
-__coerce__(self, other) --> (self1, other1) or None
-
-Used to implement "mixed-mode" numeric arithmetic.  Either return a
-tuple containing self and other converted to some common type, or None
-if no way of conversion is known.  When the common type would be the
-type of other, it is sufficient to return None, since the interpreter
-will also ask the other object to attempt a coercion (but sometimes,
-if the implementation of the other type cannot be changed, it is
-useful to do the conversion to the other type here).
-
-__int__(self) --> int
-__long__(self) --> long
-__float__(self) --> float
-
-Used to implement the built-in functions int(), long() and float().
-
-
-Notes
------
-
-Except for __repr__ and __cmp__, when no appropriate method is
-defined, attempts to execute the operation raise an exception.  For
-__repr__ and __cmp__, the traditional interpretations are used
-in this case.

File Demo/cwilib/cwilib.py

  • Ignore whitespace
-# Interface to the interactive CWI library catalog.
-
-import sys
-import stdwin
-from stdwinevents import *
-import select
-import telnetlib
-import vt100win
-from form import Form
-
-
-# Main program
-
-def main():
-    vt = vt100win.VT100win()
-    #
-    host = 'biefstuk.cwi.nl'
-    tn = telnetlib.Telnet(host, 0)
-    #
-    try:
-	vt.send(tn.read_until('login: ', 10))
-	tn.write('cwilib\r')
-	#
-	vt.send(tn.read_until('Hit <RETURN> to continue...', 10))
-	tn.write('\r')
-	#
-	vt.send(tn.read_until('QUIT', 20))
-    except EOFError:
-	sys.stderr.write('Connection closed prematurely\n')
-	sys.exit(1)
-    #
-    define_screens(vt)
-    matches = vt.which_screens()
-    if 'menu' not in matches:
-	sys.stderr.write('Main menu does not appear\n')
-	sys.exit(1)
-    #
-    tn.write('\r\r')
-    vt.open('Progress -- CWI Library')
-    vt.set_debuglevel(0)
-    ui = UserInterface()
-    #
-    while 1:
-	try:
-	    data = tn.read_very_eager()
-	except EOFError:
-	    stdwin.message('Connection closed--goodbye')
-	    break
-	if data:
-	    print 'send...'
-	    vt.send(data)
-	    print 'send...done'
-	    continue
-	event = stdwin.pollevent()
-	if event:
-	    type, window, detail = event
-	    if window == None and type == WE_LOST_SEL:
-		window = ui.queryform.window
-		event = type, window, detail
-	    if type == WE_CLOSE:
-		break
-	    if window in ui.windows:
-		ui.dispatch(type, window, detail)
-	    elif window == vt.window:
-		if type == WE_NULL:
-		    pass
-		elif type == WE_COMMAND:
-		    if detail == WC_RETURN:
-			tn.write('\r')
-		    elif detail == WC_BACKSPACE:
-			tn.write('\b')
-		    elif detail == WC_TAB:
-			tn.write('\t')
-		    elif detail == WC_UP:
-			tn.write('\033[A')
-		    elif detail == WC_DOWN:
-			tn.write('\033[B')
-		    elif detail == WC_RIGHT:
-			tn.write('\033[C')
-		    elif detail == WC_LEFT:
-			tn.write('\033[D')
-		    else:
-			print '*** Command:', detail
-		elif type == WE_CHAR:
-		    tn.write(detail)
-		elif type == WE_DRAW:
-		    vt.draw(detail)
-		elif type in (WE_ACTIVATE, WE_DEACTIVATE):
-		    pass
-		else:
-		    print '*** VT100 event:', type, detail
-	    else:
-		print '*** Alien event:', type, window, detail
-	    continue
-	rfd, wfd, xfd = select.select([tn, stdwin], [], [])
-
-
-# Subroutine to define our screen recognition patterns
-
-def define_screens(vt):
-    vt.define_screen('menu', {
-	      'title': ('search', 0, 0, 80,
-			' SEARCH FUNCTIONS  +OTHER FUNCTIONS '),
-	      })
-    vt.define_screen('search', {
-	      'title': ('search', 0, 0, 80, ' Search '),
-	      })
-    vt.define_screen('shortlist', {'title': ('search', 0, 0, 80,
-	      ' Short-list')})
-    vt.define_screen('showrecord', {
-	      'title': ('search', 0, 0, 80, ' Show record '),
-	      })
-    vt.define_screen('timelimit', {
-	      'limit': ('search', 12, 0, 80, ' TIME LIMIT '),
-	      })
-    vt.define_screen('attention', {
-	      'BASE': ('copy', 0, 0, 0, 'search'),
-	      'title': ('search', 10, 0, 80, ' ATTENTION ')})
-    vt.define_screen('syntaxerror', {
-	      'BASE': ('copy', 0, 0, 0, 'attention'),
-	      'message': ('search', 12, 0, 80, ' Syntax error'),
-	      })
-    vt.define_screen('emptyerror', {
-	      'BASE': ('copy', 0, 0, 0, 'attention'),
-	      'message': ('search', 12, 0, 80,
-			  ' Check your input. Search at least one term'),
-	      })
-    vt.define_screen('unsortedwarning', {
-	      'BASE': ('copy', 0, 0, 0, 'attention'),
-	      'message': ('search', 12, 0, 80,
-			  ' Number of records exceeds sort limit'),
-	      })
-    vt.define_screen('thereismore', {
-	      'BASE': ('copy', 0, 0, 0, 'showrecord'),
-	      'message': ('search', 15, 0, 80,
-		 'There is more within this record. Use the arrow keys'),
-	      })
-    vt.define_screen('nofurther', {
-	      'BASE': ('copy', 0, 0, 0, 'showrecord'),
-	      'message': ('search', 17, 0, 80, 'You cannot go further\.'),
-	      })
-    vt.define_screen('nofurtherback', {
-	      'BASE': ('copy', 0, 0, 0, 'showrecord'),
-	      'message': ('search', 17, 0, 80,
-			  'You cannot go further back'),
-	      })
-
-
-# Class to implement our user interface.
-
-class UserInterface:
-
-    def __init__(self):
-	stdwin.setfont('7x14')
-	self.queryform = QueryForm()
-	self.listform = ListForm()
-	self.recordform = RecordForm()
-	self.forms = [self.queryform, self.listform, self.recordform]
-	define_query_fields(self.queryform)
-	self.windows = []
-	for form in self.forms:
-	    if form.formheight > 0:
-		form.open()
-		self.windows.append(form.window)
-
-    def __del__(self):
-	self.close()
-
-    def close(self):
-	for form in self.forms:
-	    form.close()
-
-    def dispatch(self, type, window, detail):
-	for form in self.forms:
-	    if window == form.window:
-		form.dispatch(type, detail)
-
-
-def define_query_fields(f):
-    f.define_field('name', 'Name auth./ed.', 1, 60)
-    f.define_field('title',  'Title', 4, 60)
-    f.define_field('shelfmark', 'Shelf mark', 1, 60)
-    f.define_field('class', 'Prim. classif.', 1, 60)
-    f.define_field('series', 'Series', 1, 60)
-    f.define_field('congress', 'Congr. pl./year', 1, 60)
-    f.define_field('type', 'Type', 1, 60)
-
-
-class QueryForm(Form):
-
-    def __init__(self):
-	Form.__init__(self, 'Query form -- CWI Library')
-
-    def dispatch(self, type, detail):
-	if type == WE_COMMAND and detail == WC_RETURN:
-	    print '*** SUBMIT ***'
-	else:
-	    Form.dispatch(self, type, detail)
-
-
-class ListForm(Form):
-
-    def __init__(self):
-	Form.__init__(self, 'Short list -- CWI Library')
-
-
-class RecordForm(Form):
-
-    def __init__(self):
-	Form.__init__(self, 'Record detail -- CWI Library')
-
-
-main()

File Demo/cwilib/form.py

  • Ignore whitespace
-# Fill-out form window
-
-import stdwin
-from stdwinevents import *
-
-
-class Form:
-
-	def __init__(self, title):
-		self.title = title
-		self.window = None
-		self.fields = {}
-		self.fieldnames = []
-		self.formwidth = self.formheight = 0
-		self.focusname = None
-		self.tefocus = None
-
-	def define_field(self, name, label, lines, chars):
-		self.fieldnames.append(name)
-		lh = stdwin.lineheight()
-		cw = stdwin.textwidth('m')
-		left = 20*cw
-		top = self.formheight + 4
-		right = left + chars*cw
-		bottom = top + lines*lh
-		te = None
-		self.fields[name] = (label, left, top, right, bottom, te)
-		self.formheight = bottom + 2
-		self.formwidth = max(self.formwidth, right + 4)
-
-	def open(self):
-		if self.window: return
-		self.formwidth = max(100, self.formwidth)
-		self.formheight = max(50, self.formheight)
-		stdwin.setdefwinsize(self.formwidth, self.formheight)
-		stdwin.setdefscrollbars(0, 0)
-		self.window = stdwin.open(self.title)
-		self.window.setdocsize(self.formwidth, self.formheight)
-		for name in self.fieldnames:
-			label, left, top, right, bottom, te = \
-				  self.fields[name]
-			rect = (left, top), (right, bottom)
-			te = self.window.textcreate(rect)
-			te.setactive(0)
-			te.setview(rect)
-			self.fields[name] = \
-				  label, left, top, right, bottom, te
-		if self.fieldnames:
-			self.setfocus(self.fieldnames[0])
-
-	def setfocus(self, name):
-		if name <> self.focusname and self.tefocus:
-			self.tefocus.setactive(0)
-		self.focusname = name
-		if self.focusname:
-			self.tefocus = self.fields[self.focusname][-1]
-			self.tefocus.setactive(1)
-		else:
-			self.tefocus = None
-
-	def dispatch(self, type, detail):
-		event = type, self.window, detail
-		if type == WE_NULL:
-			pass
-		elif type == WE_DRAW:
-			self.draw(detail)
-		elif type == WE_MOUSE_DOWN:
-			x, y = detail[0]
-			for name in self.fieldnames:
-				label, left, top, right, bottom, te = \
-					  self.fields[name]
-				if left <= x < right and \
-					  top <= y < bottom: