Commit 4117e542 authored by Guido van Rossum's avatar Guido van Rossum

nannified

parent f9a6d7d4
...@@ -18,22 +18,22 @@ def main(): ...@@ -18,22 +18,22 @@ def main():
tn = telnetlib.Telnet(host, 0) tn = telnetlib.Telnet(host, 0)
# #
try: try:
vt.send(tn.read_until('login: ', 10)) vt.send(tn.read_until('login: ', 10))
tn.write('cwilib\r') tn.write('cwilib\r')
# #
vt.send(tn.read_until('Hit <RETURN> to continue...', 10)) vt.send(tn.read_until('Hit <RETURN> to continue...', 10))
tn.write('\r') tn.write('\r')
# #
vt.send(tn.read_until('QUIT', 20)) vt.send(tn.read_until('QUIT', 20))
except EOFError: except EOFError:
sys.stderr.write('Connection closed prematurely\n') sys.stderr.write('Connection closed prematurely\n')
sys.exit(1) sys.exit(1)
# #
define_screens(vt) define_screens(vt)
matches = vt.which_screens() matches = vt.which_screens()
if 'menu' not in matches: if 'menu' not in matches:
sys.stderr.write('Main menu does not appear\n') sys.stderr.write('Main menu does not appear\n')
sys.exit(1) sys.exit(1)
# #
tn.write('\r\r') tn.write('\r\r')
vt.open('Progress -- CWI Library') vt.open('Progress -- CWI Library')
...@@ -41,109 +41,109 @@ def main(): ...@@ -41,109 +41,109 @@ def main():
ui = UserInterface() ui = UserInterface()
# #
while 1: while 1:
try: try:
data = tn.read_very_eager() data = tn.read_very_eager()
except EOFError: except EOFError:
stdwin.message('Connection closed--goodbye') stdwin.message('Connection closed--goodbye')
break break
if data: if data:
print 'send...' print 'send...'
vt.send(data) vt.send(data)
print 'send...done' print 'send...done'
continue continue
event = stdwin.pollevent() event = stdwin.pollevent()
if event: if event:
type, window, detail = event type, window, detail = event
if window == None and type == WE_LOST_SEL: if window == None and type == WE_LOST_SEL:
window = ui.queryform.window window = ui.queryform.window
event = type, window, detail event = type, window, detail
if type == WE_CLOSE: if type == WE_CLOSE:
break break
if window in ui.windows: if window in ui.windows:
ui.dispatch(type, window, detail) ui.dispatch(type, window, detail)
elif window == vt.window: elif window == vt.window:
if type == WE_NULL: if type == WE_NULL:
pass pass
elif type == WE_COMMAND: elif type == WE_COMMAND:
if detail == WC_RETURN: if detail == WC_RETURN:
tn.write('\r') tn.write('\r')
elif detail == WC_BACKSPACE: elif detail == WC_BACKSPACE:
tn.write('\b') tn.write('\b')
elif detail == WC_TAB: elif detail == WC_TAB:
tn.write('\t') tn.write('\t')
elif detail == WC_UP: elif detail == WC_UP:
tn.write('\033[A') tn.write('\033[A')
elif detail == WC_DOWN: elif detail == WC_DOWN:
tn.write('\033[B') tn.write('\033[B')
elif detail == WC_RIGHT: elif detail == WC_RIGHT:
tn.write('\033[C') tn.write('\033[C')
elif detail == WC_LEFT: elif detail == WC_LEFT:
tn.write('\033[D') tn.write('\033[D')
else: else:
print '*** Command:', detail print '*** Command:', detail
elif type == WE_CHAR: elif type == WE_CHAR:
tn.write(detail) tn.write(detail)
elif type == WE_DRAW: elif type == WE_DRAW:
vt.draw(detail) vt.draw(detail)
elif type in (WE_ACTIVATE, WE_DEACTIVATE): elif type in (WE_ACTIVATE, WE_DEACTIVATE):
pass pass
else: else:
print '*** VT100 event:', type, detail print '*** VT100 event:', type, detail
else: else:
print '*** Alien event:', type, window, detail print '*** Alien event:', type, window, detail
continue continue
rfd, wfd, xfd = select.select([tn, stdwin], [], []) rfd, wfd, xfd = select.select([tn, stdwin], [], [])
# Subroutine to define our screen recognition patterns # Subroutine to define our screen recognition patterns
def define_screens(vt): def define_screens(vt):
vt.define_screen('menu', { vt.define_screen('menu', {
'title': ('search', 0, 0, 80, 'title': ('search', 0, 0, 80,
' SEARCH FUNCTIONS +OTHER FUNCTIONS '), ' SEARCH FUNCTIONS +OTHER FUNCTIONS '),
}) })
vt.define_screen('search', { vt.define_screen('search', {
'title': ('search', 0, 0, 80, ' Search '), 'title': ('search', 0, 0, 80, ' Search '),
}) })
vt.define_screen('shortlist', {'title': ('search', 0, 0, 80, vt.define_screen('shortlist', {'title': ('search', 0, 0, 80,
' Short-list')}) ' Short-list')})
vt.define_screen('showrecord', { vt.define_screen('showrecord', {
'title': ('search', 0, 0, 80, ' Show record '), 'title': ('search', 0, 0, 80, ' Show record '),
}) })
vt.define_screen('timelimit', { vt.define_screen('timelimit', {
'limit': ('search', 12, 0, 80, ' TIME LIMIT '), 'limit': ('search', 12, 0, 80, ' TIME LIMIT '),
}) })
vt.define_screen('attention', { vt.define_screen('attention', {
'BASE': ('copy', 0, 0, 0, 'search'), 'BASE': ('copy', 0, 0, 0, 'search'),
'title': ('search', 10, 0, 80, ' ATTENTION ')}) 'title': ('search', 10, 0, 80, ' ATTENTION ')})
vt.define_screen('syntaxerror', { vt.define_screen('syntaxerror', {
'BASE': ('copy', 0, 0, 0, 'attention'), 'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, ' Syntax error'), 'message': ('search', 12, 0, 80, ' Syntax error'),
}) })
vt.define_screen('emptyerror', { vt.define_screen('emptyerror', {
'BASE': ('copy', 0, 0, 0, 'attention'), 'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, 'message': ('search', 12, 0, 80,
' Check your input. Search at least one term'), ' Check your input. Search at least one term'),
}) })
vt.define_screen('unsortedwarning', { vt.define_screen('unsortedwarning', {
'BASE': ('copy', 0, 0, 0, 'attention'), 'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, 'message': ('search', 12, 0, 80,
' Number of records exceeds sort limit'), ' Number of records exceeds sort limit'),
}) })
vt.define_screen('thereismore', { vt.define_screen('thereismore', {
'BASE': ('copy', 0, 0, 0, 'showrecord'), 'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 15, 0, 80, 'message': ('search', 15, 0, 80,
'There is more within this record. Use the arrow keys'), 'There is more within this record. Use the arrow keys'),
}) })
vt.define_screen('nofurther', { vt.define_screen('nofurther', {
'BASE': ('copy', 0, 0, 0, 'showrecord'), 'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80, 'You cannot go further\.'), 'message': ('search', 17, 0, 80, 'You cannot go further\.'),
}) })
vt.define_screen('nofurtherback', { vt.define_screen('nofurtherback', {
'BASE': ('copy', 0, 0, 0, 'showrecord'), 'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80, 'message': ('search', 17, 0, 80,
'You cannot go further back'), 'You cannot go further back'),
}) })
# Class to implement our user interface. # Class to implement our user interface.
...@@ -151,29 +151,29 @@ def define_screens(vt): ...@@ -151,29 +151,29 @@ def define_screens(vt):
class UserInterface: class UserInterface:
def __init__(self): def __init__(self):
stdwin.setfont('7x14') stdwin.setfont('7x14')
self.queryform = QueryForm() self.queryform = QueryForm()
self.listform = ListForm() self.listform = ListForm()
self.recordform = RecordForm() self.recordform = RecordForm()
self.forms = [self.queryform, self.listform, self.recordform] self.forms = [self.queryform, self.listform, self.recordform]
define_query_fields(self.queryform) define_query_fields(self.queryform)
self.windows = [] self.windows = []
for form in self.forms: for form in self.forms:
if form.formheight > 0: if form.formheight > 0:
form.open() form.open()
self.windows.append(form.window) self.windows.append(form.window)
def __del__(self): def __del__(self):
self.close() self.close()
def close(self): def close(self):
for form in self.forms: for form in self.forms:
form.close() form.close()
def dispatch(self, type, window, detail): def dispatch(self, type, window, detail):
for form in self.forms: for form in self.forms:
if window == form.window: if window == form.window:
form.dispatch(type, detail) form.dispatch(type, detail)
def define_query_fields(f): def define_query_fields(f):
...@@ -189,25 +189,25 @@ def define_query_fields(f): ...@@ -189,25 +189,25 @@ def define_query_fields(f):
class QueryForm(Form): class QueryForm(Form):
def __init__(self): def __init__(self):
Form.__init__(self, 'Query form -- CWI Library') Form.__init__(self, 'Query form -- CWI Library')
def dispatch(self, type, detail): def dispatch(self, type, detail):
if type == WE_COMMAND and detail == WC_RETURN: if type == WE_COMMAND and detail == WC_RETURN:
print '*** SUBMIT ***' print '*** SUBMIT ***'
else: else:
Form.dispatch(self, type, detail) Form.dispatch(self, type, detail)
class ListForm(Form): class ListForm(Form):
def __init__(self): def __init__(self):
Form.__init__(self, 'Short list -- CWI Library') Form.__init__(self, 'Short list -- CWI Library')
class RecordForm(Form): class RecordForm(Form):
def __init__(self): def __init__(self):
Form.__init__(self, 'Record detail -- CWI Library') Form.__init__(self, 'Record detail -- CWI Library')
main() main()
...@@ -7,7 +7,7 @@ import socket ...@@ -7,7 +7,7 @@ import socket
import select import select
def main(): def main():
server = 'cnri.reston.va.us' # How? server = 'cnri.reston.va.us' # How?
port = 53 port = 53
opcode = dnsopcode.QUERY opcode = dnsopcode.QUERY
rd = 0 rd = 0
...@@ -15,21 +15,21 @@ def main(): ...@@ -15,21 +15,21 @@ def main():
qname = sys.argv[1:] and sys.argv[1] or 'www.python.org' qname = sys.argv[1:] and sys.argv[1] or 'www.python.org'
m = dnslib.Mpacker() m = dnslib.Mpacker()
m.addHeader(0, m.addHeader(0,
0, opcode, 0, 0, rd, 0, 0, 0, 0, opcode, 0, 0, rd, 0, 0, 0,
1, 0, 0, 0) 1, 0, 0, 0)
m.addQuestion(qname, qtype, dnsclass.IN) m.addQuestion(qname, qtype, dnsclass.IN)
request = m.getbuf() request = m.getbuf()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((server, port)) s.connect((server, port))
s.send(request) s.send(request)
while 1: while 1:
r, w, x = [s], [], [] r, w, x = [s], [], []
r, w, x = select.select(r, w, x, 0.333) r, w, x = select.select(r, w, x, 0.333)
print r, w, x print r, w, x
if r: if r:
reply = s.recv(1024) reply = s.recv(1024)
u = dnslib.Munpacker(reply) u = dnslib.Munpacker(reply)
dnslib.dumpM(u) dnslib.dumpM(u)
break break
main() main()
...@@ -4,19 +4,19 @@ For example, ...@@ -4,19 +4,19 @@ For example,
class C: class C:
def m1(self, arg): def m1(self, arg):
require arg > 0 require arg > 0
return whatever return whatever
ensure Result > arg ensure Result > arg
can be written (clumsily, I agree) as: can be written (clumsily, I agree) as:
class C(Eiffel): class C(Eiffel):
def m1(self, arg): def m1(self, arg):
return whatever return whatever
def m1_pre(self, arg): def m1_pre(self, arg):
assert arg > 0 assert arg > 0
def m1_post(self, Result, arg): def m1_post(self, Result, arg):
assert Result > arg assert Result > arg
Pre- and post-conditions for a method, being implemented as methods Pre- and post-conditions for a method, being implemented as methods
themselves, are inherited independently from the method. This gives themselves, are inherited independently from the method. This gives
...@@ -28,10 +28,10 @@ post-condition with that defined in the derived class', for example: ...@@ -28,10 +28,10 @@ post-condition with that defined in the derived class', for example:
class D(C): class D(C):
def m1(self, arg): def m1(self, arg):
return whatever**2 return whatever**2
def m1_post(self, Result, arg): def m1_post(self, Result, arg):
C.m1_post(self, Result, arg) C.m1_post(self, Result, arg)
assert Result < 100 assert Result < 100
This gives derived classes more freedom but also more responsibility This gives derived classes more freedom but also more responsibility
than in Eiffel, where the compiler automatically takes care of this. than in Eiffel, where the compiler automatically takes care of this.
...@@ -42,13 +42,13 @@ up to the derived class. For example, a derived class that takes away ...@@ -42,13 +42,13 @@ up to the derived class. For example, a derived class that takes away
the requirement that arg > 0 could write: the requirement that arg > 0 could write:
def m1_pre(self, arg): def m1_pre(self, arg):
pass pass
but one could equally write a derived class that makes a stronger but one could equally write a derived class that makes a stronger
requirement: requirement:
def m1_pre(self, arg): def m1_pre(self, arg):
require arg > 50 require arg > 50
It would be easy to modify the classes shown here so that pre- and It would be easy to modify the classes shown here so that pre- and
post-conditions can be disabled (separately, on a per-class basis). post-conditions can be disabled (separately, on a per-class basis).
...@@ -66,27 +66,27 @@ from Meta import MetaClass, MetaHelper, MetaMethodWrapper ...@@ -66,27 +66,27 @@ from Meta import MetaClass, MetaHelper, MetaMethodWrapper
class EiffelMethodWrapper(MetaMethodWrapper): class EiffelMethodWrapper(MetaMethodWrapper):
def __init__(self, func, inst): def __init__(self, func, inst):
MetaMethodWrapper.__init__(self, func, inst) MetaMethodWrapper.__init__(self, func, inst)
# Note that the following causes recursive wrappers around # Note that the following causes recursive wrappers around
# the pre-/post-condition testing methods. These are harmless # the pre-/post-condition testing methods. These are harmless
# but inefficient; to avoid them, the lookup must be done # but inefficient; to avoid them, the lookup must be done
# using the class. # using the class.
try: try:
self.pre = getattr(inst, self.__name__ + "_pre") self.pre = getattr(inst, self.__name__ + "_pre")
except AttributeError: except AttributeError:
self.pre = None self.pre = None
try: try:
self.post = getattr(inst, self.__name__ + "_post") self.post = getattr(inst, self.__name__ + "_post")
except AttributeError: except AttributeError:
self.post = None self.post = None
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
if self.pre: if self.pre:
apply(self.pre, args, kw) apply(self.pre, args, kw)
Result = apply(self.func, (self.inst,) + args, kw) Result = apply(self.func, (self.inst,) + args, kw)
if self.post: if self.post:
apply(self.post, (Result,) + args, kw) apply(self.post, (Result,) + args, kw)
return Result return Result
class EiffelHelper(MetaHelper): class EiffelHelper(MetaHelper):
__methodwrapper__ = EiffelMethodWrapper __methodwrapper__ = EiffelMethodWrapper
...@@ -99,12 +99,12 @@ Eiffel = EiffelMetaClass('Eiffel', (), {}) ...@@ -99,12 +99,12 @@ Eiffel = EiffelMetaClass('Eiffel', (), {})
def _test(): def _test():
class C(Eiffel): class C(Eiffel):
def m1(self, arg): def m1(self, arg):
return arg+1 return arg+1
def m1_pre(self, arg): def m1_pre(self, arg):
assert arg > 0, "precondition for m1 failed" assert arg > 0, "precondition for m1 failed"
def m1_post(self, Result, arg): def m1_post(self, Result, arg):
assert Result > arg assert Result > arg
x = C() x = C()
x.m1(12) x.m1(12)
## x.m1(-1) ## x.m1(-1)
......
...@@ -12,9 +12,9 @@ class EnumMetaClass: ...@@ -12,9 +12,9 @@ class EnumMetaClass:
To define your own enumeration, do something like To define your own enumeration, do something like
class Color(Enum): class Color(Enum):
red = 1 red = 1
green = 2 green = 2
blue = 3 blue = 3
Now, Color.red, Color.green and Color.blue behave totally Now, Color.red, Color.green and Color.blue behave totally
different: they are enumerated values, not integers. different: they are enumerated values, not integers.
...@@ -25,66 +25,66 @@ class EnumMetaClass: ...@@ -25,66 +25,66 @@ class EnumMetaClass:
""" """
def __init__(self, name, bases, dict): def __init__(self, name, bases, dict):
"""Constructor -- create an enumeration. """Constructor -- create an enumeration.
Called at the end of the class statement. The arguments are Called at the end of the class statement. The arguments are
the name of the new class, a tuple containing the base the name of the new class, a tuple containing the base
classes, and a dictionary containing everything that was classes, and a dictionary containing everything that was
entered in the class' namespace during execution of the class entered in the class' namespace during execution of the class
statement. In the above example, it would be {'red': 1, statement. In the above example, it would be {'red': 1,
'green': 2, 'blue': 3}. 'green': 2, 'blue': 3}.
""" """
for base in bases: for base in bases:
if base.__class__ is not EnumMetaClass: if base.__class__ is not EnumMetaClass:
raise TypeError, "Enumeration base class must be enumeration" raise TypeError, "Enumeration base class must be enumeration"
bases = filter(lambda x: x is not Enum, bases) bases = filter(lambda x: x is not Enum, bases)
self.__name__ = name self.__name__ = name
self.__bases__ = bases self.__bases__ = bases
self.__dict = {} self.__dict = {}
for key, value in dict.items(): for key, value in dict.items():
self.__dict[key] = EnumInstance(name, key, value) self.__dict[key] = EnumInstance(name, key, value)
def __getattr__(self, name): def __getattr__(self, name):
"""Return an enumeration value. """Return an enumeration value.
For example, Color.red returns the value corresponding to red. For example, Color.red returns the value corresponding to red.
XXX Perhaps the values should be created in the constructor? XXX Perhaps the values should be created in the constructor?
This looks in the class dictionary and if it is not found This looks in the class dictionary and if it is not found
there asks the base classes. there asks the base classes.
The special attribute __members__ returns the list of names The special attribute __members__ returns the list of names
defined in this class (it does not merge in the names defined defined in this class (it does not merge in the names defined
in base classes). in base classes).
""" """
if name == '__members__': if name == '__members__':
return self.__dict.keys() return self.__dict.keys()
try: try:
return self.__dict[name] return self.__dict[name]
except KeyError: except KeyError:
for base in self.__bases__: for base in self.__bases__:
try: try:
return getattr(base, name) return getattr(base, name)
except AttributeError: except AttributeError:
continue continue
raise AttributeError, name raise AttributeError, name
def __repr__(self): def __repr__(self):
s = self.__name__ s = self.__name__
if self.__bases__: if self.__bases__:
s = s + '(' + string.join(map(lambda x: x.__name__, s = s + '(' + string.join(map(lambda x: x.__name__,
self.__bases__), ", ") + ')' self.__bases__), ", ") + ')'
if self.__dict: if self.__dict:
list = [] list = []
for key, value in self.__dict.items(): for key, value in self.__dict.items():
list.append("%s: %s" % (key, int(value))) list.append("%s: %s" % (key, int(value)))
s = "%s: {%s}" % (s, string.join(list, ", ")) s = "%s: {%s}" % (s, string.join(list, ", "))
return s return s
class EnumInstance: class EnumInstance:
...@@ -99,23 +99,23 @@ class EnumInstance: ...@@ -99,23 +99,23 @@ class EnumInstance:
""" """
def __init__(self, classname, enumname, value): def __init__(self, classname, enumname, value):
self.__classname = classname self.__classname = classname
self.__enumname = enumname self.__enumname = enumname
self.__value = value self.__value = value
def __int__(self): def __int__(self):
return self.__value return self.__value
def __repr__(self): def __repr__(self):
return "EnumInstance(%s, %s, %s)" % (`self.__classname`, return "EnumInstance(%s, %s, %s)" % (`self.__classname`,
`self.__enumname`, `self.__enumname`,
`self.__value`) `self.__value`)
def __str__(self): def __str__(self):
return "%s.%s" % (self.__classname, self.__enumname) return "%s.%s" % (self.__classname, self.__enumname)
def __cmp__(self, other): def __cmp__(self, other):
return cmp(self.__value, int(other)) return cmp(self.__value, int(other))
# Create the base class for enumerations. # Create the base class for enumerations.
...@@ -126,9 +126,9 @@ Enum = EnumMetaClass("Enum", (), {}) ...@@ -126,9 +126,9 @@ Enum = EnumMetaClass("Enum", (), {})
def _test(): def _test():
class Color(Enum): class Color(Enum):
red = 1 red = 1
green = 2 green = 2
blue = 3 blue = 3
print Color.red print Color.red
print dir(Color) print dir(Color)
...@@ -139,11 +139,11 @@ def _test(): ...@@ -139,11 +139,11 @@ def _test():
print Color.red == 2 print Color.red == 2
class ExtendedColor(Color): class ExtendedColor(Color):
white = 0 white = 0
orange = 4 orange = 4
yellow = 5 yellow = 5
purple = 6 purple = 6
black = 7 black = 7
print ExtendedColor.orange print ExtendedColor.orange
print ExtendedColor.red print ExtendedColor.red
...@@ -151,11 +151,11 @@ def _test(): ...@@ -151,11 +151,11 @@ def _test():
print Color.red == ExtendedColor.red print Color.red == ExtendedColor.red
class OtherColor(Enum): class OtherColor(Enum):
white = 4 white = 4
blue = 5 blue = 5
class MergedColor(Color, OtherColor): class MergedColor(Color, OtherColor):
pass pass
print MergedColor.red print MergedColor.red
print MergedColor.white print MergedColor.white
......
...@@ -9,33 +9,33 @@ import types ...@@ -9,33 +9,33 @@ import types
class MetaMethodWrapper: class MetaMethodWrapper:
def __init__(self, func, inst): def __init__(self, func, inst):
self.func = func self.func = func
self.inst = inst self.inst = inst
self.__name__ = self.func.__name__ self.__name__ = self.func.__name__
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
return apply(self.func, (self.inst,) + args, kw) return apply(self.func, (self.inst,) + args, kw)
class MetaHelper: class MetaHelper:
__methodwrapper__ = MetaMethodWrapper # For derived helpers to override __methodwrapper__ = MetaMethodWrapper # For derived helpers to override
def __helperinit__(self, formalclass): def __helperinit__(self, formalclass):
self.__formalclass__ = formalclass self.__formalclass__ = formalclass
def __getattr__(self, name): def __getattr__(self, name):
# Invoked for any attr not in the instance's __dict__ # Invoked for any attr not in the instance's __dict__
try: try:
raw = self.__formalclass__.__getattr__(name) raw = self.__formalclass__.__getattr__(name)
except AttributeError: except AttributeError:
try: try:
ga = self.__formalclass__.__getattr__('__usergetattr__') ga = self.__formalclass__.__getattr__('__usergetattr__')
except KeyError: except KeyError:
raise AttributeError, name raise AttributeError, name
return ga(self, name) return ga(self, name)
if type(raw) != types.FunctionType: if type(raw) != types.FunctionType:
return raw return raw
return self.__methodwrapper__(raw, self) return self.__methodwrapper__(raw, self)
class MetaClass: class MetaClass:
...@@ -45,49 +45,49 @@ class MetaClass: ...@@ -45,49 +45,49 @@ class MetaClass:
""" """
__helper__ = MetaHelper # For derived metaclasses to override __helper__ = MetaHelper # For derived metaclasses to override
__inited = 0 __inited = 0
def __init__(self, name, bases, dict): def __init__(self, name, bases, dict):
try: try:
ga = dict['__getattr__'] ga = dict['__getattr__']
except KeyError: except KeyError:
pass pass
else: else:
dict['__usergetattr__'] = ga dict['__usergetattr__'] = ga
del dict['__getattr__'] del dict['__getattr__']
self.__name__ = name self.__name__ = name
self.__bases__ = bases self.__bases__ = bases
self.__realdict__ = dict self.__realdict__ = dict
self.__inited = 1 self.__inited = 1
def __getattr__(self, name): def __getattr__(self, name):
try: try:
return self.__realdict__[name] return self.__realdict__[name]
except KeyError: except KeyError:
for base in self.__bases__: for base in self.__bases__:
try: try:
return base.__getattr__(name) return base.__getattr__(name)
except AttributeError: except AttributeError:
pass pass
raise AttributeError, name raise AttributeError, name
def __setattr__(self, name, value): def __setattr__(self, name, value):
if not self.__inited: if not self.__inited:
self.__dict__[name] = value self.__dict__[name] = value
else: else:
self.__realdict__[name] = value self.__realdict__[name] = value
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
inst = self.__helper__() inst = self.__helper__()
inst.__helperinit__(self) inst.__helperinit__(self)
try: try:
init = inst.__getattr__('__init__') init = inst.__getattr__('__init__')
except AttributeError: except AttributeError:
init = lambda: None init = lambda: None
apply(init, args, kw) apply(init, args, kw)
return inst return inst
Meta = MetaClass('Meta', (), {}) Meta = MetaClass('Meta', (), {})
...@@ -95,18 +95,18 @@ Meta = MetaClass('Meta', (), {}) ...@@ -95,18 +95,18 @@ Meta = MetaClass('Meta', (), {})
def _test(): def _test():
class C(Meta): class C(Meta):
def __init__(self, *args): def __init__(self, *args):
print "__init__, args =", args print "__init__, args =", args
def m1(self, x): def m1(self, x):
print "m1(x=%s)" %`x` print "m1(x=%s)" %`x`
print C print C
x = C() x = C()
print x print x
x.m1(12) x.m1(12)
class D(C): class D(C):
def __getattr__(self, name): def __getattr__(self, name):
if name[:2] == '__': raise AttributeError, name if name[:2] == '__': raise AttributeError, name
return "getattr:%s" % name return "getattr:%s" % name
x = D() x = D()
print x.foo print x.foo
print x._foo print x._foo
......
This diff is collapsed.
...@@ -20,38 +20,38 @@ class TraceMetaClass: ...@@ -20,38 +20,38 @@ class TraceMetaClass:
__inited = 0 __inited = 0
def __init__(self, name, bases, dict): def __init__(self, name, bases, dict):
self.__name__ = name self.__name__ = name
self.__bases__ = bases self.__bases__ = bases
self.__dict = dict self.__dict = dict
# XXX Can't define __dict__, alas # XXX Can't define __dict__, alas
self.__inited = 1 self.__inited = 1
def __getattr__(self, name): def __getattr__(self, name):
try: try:
return self.__dict[name] return self.__dict[name]
except KeyError: except KeyError:
for base in self.__bases__: for base in self.__bases__:
try: try:
return base.__getattr__(name) return base.__getattr__(name)
except AttributeError: except AttributeError:
pass pass
raise AttributeError, name raise AttributeError, name
def __setattr__(self, name, value): def __setattr__(self, name, value):
if not self.__inited: if not self.__inited:
self.__dict__[name] = value self.__dict__[name] = value
else: else:
self.__dict[name] = value self.__dict[name] = value
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
inst = TracingInstance() inst = TracingInstance()
inst.__meta_init__(self) inst.__meta_init__(self)
try: try:
init = inst.__getattr__('__init__') init = inst.__getattr__('__init__')
except AttributeError: except AttributeError:
init = lambda: None init = lambda: None
apply(init, args, kw) apply(init, args, kw)
return inst return inst
__trace_output__ = None __trace_output__ = None
...@@ -59,52 +59,52 @@ class TracingInstance: ...@@ -59,52 +59,52 @@ class TracingInstance:
"""Helper class to represent an instance of a tracing class.""" """Helper class to represent an instance of a tracing class."""
def __trace_call__(self, fp, fmt, *args): def __trace_call__(self, fp, fmt, *args):
fp.write((fmt+'\n') % args) fp.write((fmt+'\n') % args)
def __meta_init__(self, klass): def __meta_init__(self, klass):
self.__class = klass self.__class = klass
def __getattr__(self, name): def __getattr__(self, name):
# Invoked for any attr not in the instance's __dict__ # Invoked for any attr not in the instance's __dict__
try: try:
raw = self.__class.__getattr__(name) raw = self.__class.__getattr__(name)
except AttributeError: except AttributeError:
raise AttributeError, name raise AttributeError, name
if type(raw) != types.FunctionType: if type(raw) != types.FunctionType:
return raw return raw
# It's a function # It's a function
fullname = self.__class.__name__ + "." + name fullname = self.__class.__name__ + "." + name
if not self.__trace_output__ or name == '__trace_call__': if not self.__trace_output__ or name == '__trace_call__':
return NotTracingWrapper(fullname, raw, self) return NotTracingWrapper(fullname, raw, self)
else: else:
return TracingWrapper(fullname, raw, self) return TracingWrapper(fullname, raw, self)
class NotTracingWrapper: class NotTracingWrapper:
def __init__(self, name, func, inst): def __init__(self, name, func, inst):
self.__name__ = name self.__name__ = name
self.func = func self.func = func
self.inst = inst self.inst = inst
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
return apply(self.func, (self.inst,) + args, kw) return apply(self.func, (self.inst,) + args, kw)
class TracingWrapper(NotTracingWrapper): class TracingWrapper(NotTracingWrapper):
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
self.inst.__trace_call__(self.inst.__trace_output__, self.inst.__trace_call__(self.inst.__trace_output__,
"calling %s, inst=%s, args=%s, kw=%s", "calling %s, inst=%s, args=%s, kw=%s",
self.__name__, self.inst, args, kw) self.__name__, self.inst, args, kw)
try: try:
rv = apply(self.func, (self.inst,) + args, kw) rv = apply(self.func, (self.inst,) + args, kw)
except: except:
t, v, tb = sys.exc_info() t, v, tb = sys.exc_info()
self.inst.__trace_call__(self.inst.__trace_output__, self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with exception %s: %s", "returning from %s with exception %s: %s",
self.__name__, t, v) self.__name__, t, v)
raise t, v, tb raise t, v, tb
else: else:
self.inst.__trace_call__(self.inst.__trace_output__, self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with value %s", "returning from %s with value %s",
self.__name__, rv) self.__name__, rv)
return rv return rv
Traced = TraceMetaClass('Traced', (), {'__trace_output__': None}) Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
...@@ -112,13 +112,13 @@ Traced = TraceMetaClass('Traced', (), {'__trace_output__': None}) ...@@ -112,13 +112,13 @@ Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
def _test(): def _test():
global C, D global C, D
class C(Traced): class C(Traced):
def __init__(self, x=0): self.x = x def __init__(self, x=0): self.x = x
def m1(self, x): self.x = x def m1(self, x): self.x = x
def m2(self, y): return self.x + y def m2(self, y): return self.x + y
__trace_output__ = sys.stdout __trace_output__ = sys.stdout
class D(C): class D(C):
def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y) def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y)
__trace_output__ = None __trace_output__ = None
x = C(4321) x = C(4321)
print x print x
print x.x print x.x
......
...@@ -14,7 +14,7 @@ def get_docs(fileName): ...@@ -14,7 +14,7 @@ def get_docs(fileName):
"""Retrieve information from the parse tree of a source file. """Retrieve information from the parse tree of a source file.
fileName fileName
Name of the file to read Python source code from. Name of the file to read Python source code from.
""" """
source = open(fileName).read() source = open(fileName).read()
import os import os
...@@ -30,86 +30,86 @@ class SuiteInfoBase: ...@@ -30,86 +30,86 @@ class SuiteInfoBase:
_name = '' _name = ''
def __init__(self, tree = None): def __init__(self, tree = None):
self._class_info = {} self._class_info = {}
self._function_info = {} self._function_info = {}
if tree: if tree:
self._extract_info(tree) self._extract_info(tree)
def _extract_info(self, tree): def _extract_info(self, tree):
# extract docstring # extract docstring
if len(tree) == 2: if len(tree) == 2:
found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1]) found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
else: else:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[3]) found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
if found: if found:
self._docstring = eval(vars['docstring']) self._docstring = eval(vars['docstring'])
# discover inner definitions # discover inner definitions
for node in tree[1:]: for node in tree[1:]:
found, vars = match(COMPOUND_STMT_PATTERN, node) found, vars = match(COMPOUND_STMT_PATTERN, node)
if found: if found:
cstmt = vars['compound'] cstmt = vars['compound']
if cstmt[0] == symbol.funcdef: if cstmt[0] == symbol.funcdef:
name = cstmt[2][1] name = cstmt[2][1]
self._function_info[name] = FunctionInfo(cstmt) self._function_info[name] = FunctionInfo(cstmt)
elif cstmt[0] == symbol.classdef: elif cstmt[0] == symbol.classdef:
name = cstmt[2][1] name = cstmt[2][1]
self._class_info[name] = ClassInfo(cstmt) self._class_info[name] = ClassInfo(cstmt)
def get_docstring(self): def get_docstring(self):
return self._docstring return self._docstring
def get_name(self): def get_name(self):
return self._name return self._name
def get_class_names(self): def get_class_names(self):
return self._class_info.keys() return self._class_info.keys()
def get_class_info(self, name): def get_class_info(self, name):
return self._class_info[name] return self._class_info[name]
def __getitem__(self, name): def __getitem__(self, name):
try: try:
return self._class_info[name] return self._class_info[name]
except KeyError: except KeyError:
return self._function_info[name] return self._function_info[name]
class SuiteFuncInfo: class SuiteFuncInfo:
# Mixin class providing access to function names and info. # Mixin class providing access to function names and info.
def get_function_names(self): def get_function_names(self):
return self._function_info.keys() return self._function_info.keys()
def get_function_info(self, name): def get_function_info(self, name):
return self._function_info[name] return self._function_info[name]
class FunctionInfo(SuiteInfoBase, SuiteFuncInfo): class FunctionInfo(SuiteInfoBase, SuiteFuncInfo):
def __init__(self, tree = None): def __init__(self, tree = None):
self._name = tree[2][1] self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None) SuiteInfoBase.__init__(self, tree and tree[-1] or None)
class ClassInfo(SuiteInfoBase): class ClassInfo(SuiteInfoBase):
def __init__(self, tree = None): def __init__(self, tree = None):
self._name = tree[2][1] self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None) SuiteInfoBase.__init__(self, tree and tree[-1] or None)
def get_method_names(self): def get_method_names(self):
return self._function_info.keys() return self._function_info.keys()
def get_method_info(self, name): def get_method_info(self, name):
return self._function_info[name] return self._function_info[name]
class ModuleInfo(SuiteInfoBase, SuiteFuncInfo): class ModuleInfo(SuiteInfoBase, SuiteFuncInfo):
def __init__(self, tree = None, name = "<string>"): def __init__(self, tree = None, name = "<string>"):
self._name = name self._name = name
SuiteInfoBase.__init__(self, tree) SuiteInfoBase.__init__(self, tree)
if tree: if tree:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[1]) found, vars = match(DOCSTRING_STMT_PATTERN, tree[1])
if found: if found:
self._docstring = vars["docstring"] self._docstring = vars["docstring"]
from types import ListType, TupleType from types import ListType, TupleType
...@@ -118,14 +118,14 @@ def match(pattern, data, vars=None): ...@@ -118,14 +118,14 @@ def match(pattern, data, vars=None):
"""Match `data' to `pattern', with variable extraction. """Match `data' to `pattern', with variable extraction.
pattern pattern
Pattern to match against, possibly containing variables. Pattern to match against, possibly containing variables.
data data
Data to be checked and against which variables are extracted. Data to be checked and against which variables are extracted.
vars vars
Dictionary of variables which have already been found. If not Dictionary of variables which have already been found. If not
provided, an empty dictionary is created. provided, an empty dictionary is created.
The `pattern' value may contain variables of the form ['varname'] which The `pattern' value may contain variables of the form ['varname'] which
are allowed to match anything. The value that is matched is returned as are allowed to match anything. The value that is matched is returned as
...@@ -138,18 +138,18 @@ def match(pattern, data, vars=None): ...@@ -138,18 +138,18 @@ def match(pattern, data, vars=None):
values. values.
""" """
if vars is None: if vars is None:
vars = {} vars = {}
if type(pattern) is ListType: # 'variables' are ['varname'] if type(pattern) is ListType: # 'variables' are ['varname']
vars[pattern[0]] = data vars[pattern[0]] = data
return 1, vars return 1, vars
if type(pattern) is not TupleType: if type(pattern) is not TupleType:
return (pattern == data), vars return (pattern == data), vars
if len(data) != len(pattern): if len(data) != len(pattern):
return 0, vars return 0, vars
for pattern, data in map(None, pattern, data): for pattern, data in map(None, pattern, data):
same, vars = match(pattern, data, vars) same, vars = match(pattern, data, vars)
if not same: if not same:
break break
return same, vars return same, vars
...@@ -172,21 +172,21 @@ DOCSTRING_STMT_PATTERN = ( ...@@ -172,21 +172,21 @@ DOCSTRING_STMT_PATTERN = (
(symbol.small_stmt, (symbol.small_stmt,
(symbol.expr_stmt, (symbol.expr_stmt,
(symbol.testlist, (symbol.testlist,
(symbol.test, (symbol.test,
(symbol.and_test, (symbol.and_test,
(symbol.not_test, (symbol.not_test,
(symbol.comparison, (symbol.comparison,
(symbol.expr, (symbol.expr,
(symbol.xor_expr, (symbol.xor_expr,
(symbol.and_expr, (symbol.and_expr,
(symbol.shift_expr, (symbol.shift_expr,
(symbol.arith_expr, (symbol.arith_expr,
(symbol.term, (symbol.term,
(symbol.factor, (symbol.factor,
(symbol.power, (symbol.power,
(symbol.atom, (symbol.atom,
(token.STRING, ['docstring']) (token.STRING, ['docstring'])
)))))))))))))))), )))))))))))))))),
(token.NEWLINE, '') (token.NEWLINE, '')
)) ))
......
...@@ -9,18 +9,18 @@ class Simple: ...@@ -9,18 +9,18 @@ class Simple:
"This class does very little." "This class does very little."
def method(self): def method(self):
"This method does almost nothing." "This method does almost nothing."
return 1 return 1
class Nested: class Nested:
"This is a nested class." "This is a nested class."
def nested_method(self): def nested_method(self):
"Method of Nested class." "Method of Nested class."
def nested_function(): def nested_function():
"Function in method of Nested class." "Function in method of Nested class."
pass pass
return nested_function return nested_function
def function(): def function():
"This function lives at the module level." "This function lives at the module level."
......
...@@ -11,24 +11,24 @@ def testChunk(t, fileName): ...@@ -11,24 +11,24 @@ def testChunk(t, fileName):
global _numFailed global _numFailed
print '----', fileName, print '----', fileName,
try: try:
ast = parser.suite(t) ast = parser.suite(t)
tup = parser.ast2tuple(ast) tup = parser.ast2tuple(ast)
# this discards the first AST; a huge memory savings when running # this discards the first AST; a huge memory savings when running
# against a large source file like Tkinter.py. # against a large source file like Tkinter.py.
ast = None ast = None
new = parser.tuple2ast(tup) new = parser.tuple2ast(tup)
except parser.ParserError, err: except parser.ParserError, err:
print print
print 'parser module raised exception on input file', fileName + ':' print 'parser module raised exception on input file', fileName + ':'
traceback.print_exc() traceback.print_exc()
_numFailed = _numFailed + 1 _numFailed = _numFailed + 1
else: else:
if tup != parser.ast2tuple(new): if tup != parser.ast2tuple(new):
print print
print 'parser module failed on input file', fileName print 'parser module failed on input file', fileName
_numFailed = _numFailed + 1 _numFailed = _numFailed + 1
else: else:
print 'o.k.' print 'o.k.'
def testFile(fileName): def testFile(fileName):
t = open(fileName).read() t = open(fileName).read()
...@@ -38,8 +38,8 @@ def test(): ...@@ -38,8 +38,8 @@ def test():
import sys import sys
args = sys.argv[1:] args = sys.argv[1:]
if not args: if not args:
import glob import glob
args = glob.glob("*.py") args = glob.glob("*.py")
map(testFile, args) map(testFile, args)
sys.exit(_numFailed != 0) sys.exit(_numFailed != 0)
......
...@@ -31,147 +31,147 @@ import rcslib ...@@ -31,147 +31,147 @@ import rcslib
class DirSupport: class DirSupport:
def __init__(self): def __init__(self):
self._dirstack = [] self._dirstack = []
def __del__(self): def __del__(self):
self._close() self._close()
def _close(self): def _close(self):
while self._dirstack: while self._dirstack:
self.back() self.back()
def pwd(self): def pwd(self):
return os.getcwd() return os.getcwd()
def cd(self, name): def cd(self, name):
save = os.getcwd() save = os.getcwd()
os.chdir(name) os.chdir(name)
self._dirstack.append(save) self._dirstack.append(save)
def back(self): def back(self):
if not self._dirstack: if not self._dirstack:
raise os.error, "empty directory stack" raise os.error, "empty directory stack"
dir = self._dirstack[-1] dir = self._dirstack[-1]
os.chdir(dir) os.chdir(dir)
del self._dirstack[-1] del self._dirstack[-1]
def listsubdirs(self, pat = None): def listsubdirs(self, pat = None):
files = os.listdir(os.curdir) files = os.listdir(os.curdir)
files = filter(os.path.isdir, files) files = filter(os.path.isdir, files)
return self._filter(files, pat) return self._filter(files, pat)
def isdir(self, name): def isdir(self, name):
return os.path.isdir(name) return os.path.isdir(name)
def mkdir(self, name): def mkdir(self, name):
os.mkdir(name, 0777) os.mkdir(name, 0777)
def rmdir(self, name): def rmdir(self, name):
os.rmdir(name) os.rmdir(name)
class RCSProxyLocal(rcslib.RCS, DirSupport): class RCSProxyLocal(rcslib.RCS, DirSupport):
def __init__(self): def __init__(self):
rcslib.RCS.__init__(self) rcslib.RCS.__init__(self)
DirSupport.__init__(self) DirSupport.__init__(self)
def __del__(self): def __del__(self):
DirSupport.__del__(self) DirSupport.__del__(self)
rcslib.RCS.__del__(self) rcslib.RCS.__del__(self)
def sumlist(self, list = None): def sumlist(self, list = None):
return self._list(self.sum, list) return self._list(self.sum, list)
def sumdict(self, list = None): def sumdict(self, list = None):
return self._dict(self.sum, list) return self._dict(self.sum, list)
def sum(self, name_rev): def sum(self, name_rev):
f = self._open(name_rev) f = self._open(name_rev)
BUFFERSIZE = 1024*8 BUFFERSIZE = 1024*8
sum = md5.new() sum = md5.new()
while 1: while 1:
buffer = f.read(BUFFERSIZE) buffer = f.read(BUFFERSIZE)
if not buffer: if not buffer:
break break
sum.update(buffer) sum.update(buffer)
self._closepipe(f) self._closepipe(f)
return sum.digest() return sum.digest()
def get(self, name_rev): def get(self, name_rev):
f = self._open(name_rev) f = self._open(name_rev)
data = f.read() data = f.read()
self._closepipe(f) self._closepipe(f)
return data return data
def put(self, name_rev, data, message=None): def put(self, name_rev, data, message=None):
name, rev = self._unmangle(name_rev) name, rev = self._unmangle(name_rev)
f = open(name, 'w') f = open(name, 'w')
f.write(data) f.write(data)
f.close() f.close()
self.checkin(name_rev, message) self.checkin(name_rev, message)
self._remove(name) self._remove(name)
def _list(self, function, list = None): def _list(self, function, list = None):
"""INTERNAL: apply FUNCTION to all files in LIST. """INTERNAL: apply FUNCTION to all files in LIST.
Return a list of the results. Return a list of the results.
The list defaults to all files in the directory if None. The list defaults to all files in the directory if None.
""" """
if list is None: if list is None:
list = self.listfiles() list = self.listfiles()
res = [] res = []
for name in list: for name in list:
try: try:
res.append((name, function(name))) res.append((name, function(name)))
except (os.error, IOError): except (os.error, IOError):
res.append((name, None)) res.append((name, None))
return res return res
def _dict(self, function, list = None): def _dict(self, function, list = None):
"""INTERNAL: apply FUNCTION to all files in LIST. """INTERNAL: apply FUNCTION to all files in LIST.
Return a dictionary mapping files to results. Return a dictionary mapping files to results.
The list defaults to all files in the directory if None. The list defaults to all files in the directory if None.
""" """
if list is None: if list is None:
list = self.listfiles() list = self.listfiles()
dict = {} dict = {}
for name in list: for name in list:
try: try:
dict[name] = function(name) dict[name] = function(name)
except (os.error, IOError): except (os.error, IOError):
pass pass
return dict return dict
class RCSProxyServer(RCSProxyLocal, server.SecureServer): class RCSProxyServer(RCSProxyLocal, server.SecureServer):
def __init__(self, address, verbose = server.VERBOSE): def __init__(self, address, verbose = server.VERBOSE):
RCSProxyLocal.__init__(self) RCSProxyLocal.__init__(self)
server.SecureServer.__init__(self, address, verbose) server.SecureServer.__init__(self, address, verbose)
def _close(self): def _close(self):
server.SecureServer._close(self) server.SecureServer._close(self)
RCSProxyLocal._close(self) RCSProxyLocal._close(self)
def _serve(self): def _serve(self):
server.SecureServer._serve(self) server.SecureServer._serve(self)
# Retreat into start directory # Retreat into start directory
while self._dirstack: self.back() while self._dirstack: self.back()
def test_server(): def test_server():
import string import string
import sys import sys
if sys.argv[1:]: if sys.argv[1:]:
port = string.atoi(sys.argv[1]) port = string.atoi(sys.argv[1])
else: else:
port = 4127 port = 4127
proxy = RCSProxyServer(('', port)) proxy = RCSProxyServer(('', port))
proxy._serverloop() proxy._serverloop()
...@@ -179,19 +179,19 @@ def test_server(): ...@@ -179,19 +179,19 @@ def test_server():
def test(): def test():
import sys import sys
if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789': if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789':
test_server() test_server()
sys.exit(0) sys.exit(0)
proxy = RCSProxyLocal() proxy = RCSProxyLocal()
what = sys.argv[1] what = sys.argv[1]
if hasattr(proxy, what): if hasattr(proxy, what):
attr = getattr(proxy, what) attr = getattr(proxy, what)
if callable(attr): if callable(attr):
print apply(attr, tuple(sys.argv[2:])) print apply(attr, tuple(sys.argv[2:]))
else: else:
print `attr` print `attr`
else: else:
print "%s: no such attribute" % what print "%s: no such attribute" % what
sys.exit(2) sys.exit(2)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -15,25 +15,25 @@ def main(): ...@@ -15,25 +15,25 @@ def main():
opts, args = getopt.getopt(args, 'p:') opts, args = getopt.getopt(args, 'p:')
prefix = '' prefix = ''
for o, a in opts: for o, a in opts:
if p == '-p': prefix = a if p == '-p': prefix = a
f = sys.stdin f = sys.stdin
allrevs = [] allrevs = []
while 1: while 1:
file = getnextfile(f) file = getnextfile(f)
if not file: break if not file: break
revs = [] revs = []
while 1: while 1:
rev = getnextrev(f, file) rev = getnextrev(f, file)
if not rev: if not rev:
break break
revs.append(rev) revs.append(rev)
if revs: if revs:
allrevs[len(allrevs):] = revs allrevs[len(allrevs):] = revs
allrevs.sort() allrevs.sort()
allrevs.reverse() allrevs.reverse()
for rev in allrevs: for rev in allrevs:
formatrev(rev, prefix) formatrev(rev, prefix)
parsedateprog = regex.compile( parsedateprog = regex.compile(
'^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' + '^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' +
...@@ -48,46 +48,46 @@ authormap = { ...@@ -48,46 +48,46 @@ authormap = {
def formatrev(rev, prefix): def formatrev(rev, prefix):
dateline, file, revline, log = rev dateline, file, revline, log = rev
if parsedateprog.match(dateline) >= 0: if parsedateprog.match(dateline) >= 0:
fields = parsedateprog.group(1, 2, 3, 4, 5, 6) fields = parsedateprog.group(1, 2, 3, 4, 5, 6)
author = parsedateprog.group(7) author = parsedateprog.group(7)
if authormap.has_key(author): author = authormap[author] if authormap.has_key(author): author = authormap[author]
tfields = map(string.atoi, fields) + [0, 0, 0] tfields = map(string.atoi, fields) + [0, 0, 0]
tfields[5] = tfields[5] - time.timezone tfields[5] = tfields[5] - time.timezone
t = time.mktime(tuple(tfields)) t = time.mktime(tuple(tfields))
print time.ctime(t), '', author print time.ctime(t), '', author
words = string.split(log) words = string.split(log)
words[:0] = ['*', prefix + file + ':'] words[:0] = ['*', prefix + file + ':']
maxcol = 72-8 maxcol = 72-8
col = maxcol col = maxcol
for word in words: for word in words:
if col > 0 and col + len(word) >= maxcol: if col > 0 and col + len(word) >= maxcol:
print print
print '\t' + word, print '\t' + word,
col = -1 col = -1
else: else:
print word, print word,
col = col + 1 + len(word) col = col + 1 + len(word)
print print
print print
startprog = regex.compile("^Working file: \(.*\)$") startprog = regex.compile("^Working file: \(.*\)$")
def getnextfile(f): def getnextfile(f):
while 1: while 1:
line = f.readline() line = f.readline()
if not line: return None if not line: return None
if startprog.match(line) >= 0: if startprog.match(line) >= 0:
file = startprog.group(1) file = startprog.group(1)
# Skip until first revision # Skip until first revision
while 1: while 1:
line = f.readline() line = f.readline()
if not line: return None if not line: return None
if line[:10] == '='*10: return None if line[:10] == '='*10: return None
if line[:10] == '-'*10: break if line[:10] == '-'*10: break
## print "Skipped", line, ## print "Skipped", line,
return file return file
## else: ## else:
## print "Ignored", line, ## print "Ignored", line,
def getnextrev(f, file): def getnextrev(f, file):
# This is called when we are positioned just after a '---' separator # This is called when we are positioned just after a '---' separator
...@@ -95,14 +95,14 @@ def getnextrev(f, file): ...@@ -95,14 +95,14 @@ def getnextrev(f, file):
dateline = f.readline() dateline = f.readline()
log = '' log = ''
while 1: while 1:
line = f.readline() line = f.readline()
if not line: break if not line: break
if line[:10] == '='*10: if line[:10] == '='*10:
# Ignore the *last* log entry for each file since it # Ignore the *last* log entry for each file since it
# is the revision since which we are logging. # is the revision since which we are logging.
return None return None
if line[:10] == '-'*10: break if line[:10] == '-'*10: break
log = log + line log = log + line
return dateline, file, revline, log return dateline, file, revline, log
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -22,8 +22,8 @@ import client ...@@ -22,8 +22,8 @@ import client
class RCSProxyClient(client.SecureClient): class RCSProxyClient(client.SecureClient):
def __init__(self, address, verbose = client.VERBOSE): def __init__(self, address, verbose = client.VERBOSE):
client.SecureClient.__init__(self, address, verbose) client.SecureClient.__init__(self, address, verbose)
def openrcsclient(opts = []): def openrcsclient(opts = []):
......
This diff is collapsed.
...@@ -14,30 +14,30 @@ can log in on your machine. Use with caution! ...@@ -14,30 +14,30 @@ can log in on your machine. Use with caution!
import sys, os, string, getopt, thread, socket, traceback import sys, os, string, getopt, thread, socket, traceback
PORT = 4000 # Default port PORT = 4000 # Default port
def main(): def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "") opts, args = getopt.getopt(sys.argv[1:], "")
if len(args) > 1: if len(args) > 1:
raise getopt.error, "Too many arguments." raise getopt.error, "Too many arguments."
except getopt.error, msg: except getopt.error, msg:
usage(msg) usage(msg)
for o, a in opts: for o, a in opts:
pass pass
if args: if args:
try: try:
port = string.atoi(args[0]) port = string.atoi(args[0])
except ValueError, msg: except ValueError, msg:
usage(msg) usage(msg)
else: else:
port = PORT port = PORT
main_thread(port) main_thread(port)
def usage(msg=None): def usage(msg=None):
sys.stdout = sys.stderr sys.stdout = sys.stderr
if msg: if msg:
print msg print msg
print "\n", __doc__, print "\n", __doc__,
sys.exit(2) sys.exit(2)
...@@ -47,18 +47,18 @@ def main_thread(port): ...@@ -47,18 +47,18 @@ def main_thread(port):
sock.listen(5) sock.listen(5)
print "Listening on port", port, "..." print "Listening on port", port, "..."
while 1: while 1:
(conn, addr) = sock.accept() (conn, addr) = sock.accept()
if addr[0] != conn.getsockname()[0]: if addr[0] != conn.getsockname()[0]:
conn.close() conn.close()
print "Refusing connection from non-local host", addr[0], "." print "Refusing connection from non-local host", addr[0], "."
continue continue
thread.start_new_thread(service_thread, (conn, addr)) thread.start_new_thread(service_thread, (conn, addr))
del conn, addr del conn, addr
def service_thread(conn, addr): def service_thread(conn, addr):
(caddr, cport) = addr (caddr, cport) = addr
print "Thread %s has connection from %s.\n" % (str(thread.get_ident()), print "Thread %s has connection from %s.\n" % (str(thread.get_ident()),
caddr), caddr),
stdin = conn.makefile("r") stdin = conn.makefile("r")
stdout = conn.makefile("w", 0) stdout = conn.makefile("w", 0)
run_interpreter(stdin, stdout) run_interpreter(stdin, stdout)
...@@ -67,57 +67,57 @@ def service_thread(conn, addr): ...@@ -67,57 +67,57 @@ def service_thread(conn, addr):
def run_interpreter(stdin, stdout): def run_interpreter(stdin, stdout):
globals = {} globals = {}
try: try:
str(sys.ps1) str(sys.ps1)
except: except:
sys.ps1 = ">>> " sys.ps1 = ">>> "
source = "" source = ""
while 1: while 1:
stdout.write(sys.ps1) stdout.write(sys.ps1)
line = stdin.readline() line = stdin.readline()
if line[:2] == '\377\354': if line[:2] == '\377\354':
line = "" line = ""
if not line and not source: if not line and not source:
break break
if line[-2:] == '\r\n': if line[-2:] == '\r\n':
line = line[:-2] + '\n' line = line[:-2] + '\n'
source = source + line source = source + line
try: try:
code = compile_command(source) code = compile_command(source)
except SyntaxError, err: except SyntaxError, err:
source = "" source = ""
traceback.print_exception(SyntaxError, err, None, file=stdout) traceback.print_exception(SyntaxError, err, None, file=stdout)
continue continue
if not code: if not code:
continue continue
source = "" source = ""
try: try:
run_command(code, stdin, stdout, globals) run_command(code, stdin, stdout, globals)
except SystemExit, how: except SystemExit, how:
if how: if how:
try: try:
how = str(how) how = str(how)
except: except:
how = "" how = ""
stdout.write("Exit %s\n" % how) stdout.write("Exit %s\n" % how)
break break
stdout.write("\nGoodbye.\n") stdout.write("\nGoodbye.\n")
def run_command(code, stdin, stdout, globals): def run_command(code, stdin, stdout, globals):
save = sys.stdin, sys.stdout, sys.stderr save = sys.stdin, sys.stdout, sys.stderr
try: try:
sys.stdout = sys.stderr = stdout sys.stdout = sys.stderr = stdout
sys.stdin = stdin sys.stdin = stdin
try: try:
exec code in globals exec code in globals
except SystemExit, how: except SystemExit, how:
raise SystemExit, how, sys.exc_info()[2] raise SystemExit, how, sys.exc_info()[2]
except: except:
type, value, tb = sys.exc_info() type, value, tb = sys.exc_info()
if tb: tb = tb.tb_next if tb: tb = tb.tb_next
traceback.print_exception(type, value, tb) traceback.print_exception(type, value, tb)
del tb del tb
finally: finally:
sys.stdin, sys.stdout, sys.stderr = save sys.stdin, sys.stdout, sys.stderr = save
from code import compile_command from code import compile_command
......
...@@ -96,22 +96,22 @@ class NFSUnpacker(MountUnpacker): ...@@ -96,22 +96,22 @@ class NFSUnpacker(MountUnpacker):
return status, attributes return status, attributes
def unpack_fattr(self): def unpack_fattr(self):
type = self.unpack_enum() type = self.unpack_enum()
mode = self.unpack_uint() mode = self.unpack_uint()
nlink = self.unpack_uint() nlink = self.unpack_uint()
uid = self.unpack_uint() uid = self.unpack_uint()
gid = self.unpack_uint() gid = self.unpack_uint()
size = self.unpack_uint() size = self.unpack_uint()
blocksize = self.unpack_uint() blocksize = self.unpack_uint()
rdev = self.unpack_uint() rdev = self.unpack_uint()
blocks = self.unpack_uint() blocks = self.unpack_uint()
fsid = self.unpack_uint() fsid = self.unpack_uint()
fileid = self.unpack_uint() fileid = self.unpack_uint()
atime = self.unpack_timeval() atime = self.unpack_timeval()
mtime = self.unpack_timeval() mtime = self.unpack_timeval()
ctime = self.unpack_timeval() ctime = self.unpack_timeval()
return (type, mode, nlink, uid, gid, size, blocksize, \ return (type, mode, nlink, uid, gid, size, blocksize, \
rdev, blocks, fsid, fileid, atime, mtime, ctime) rdev, blocks, fsid, fileid, atime, mtime, ctime)
def unpack_timeval(self): def unpack_timeval(self):
secs = self.unpack_uint() secs = self.unpack_uint()
......
...@@ -53,44 +53,45 @@ def main(): ...@@ -53,44 +53,45 @@ def main():
bytype = {} bytype = {}
lineno = 0 lineno = 0
try: try:
while 1:
line = f.readline()
if not line: break
lineno = lineno + 1
if search and string.find(line, search) < 0:
continue
if prog.match(line) < 0:
print 'Bad line', lineno, ':', `line`
continue
items = prog.group(1, 2, 3, 4, 5, 6)
logtime, loguser, loghost, logfile, logbytes, logxxx2 = items
## print logtime
## print '-->', loguser
## print '--> -->', loghost
## print '--> --> -->', logfile
## print '--> --> --> -->', logbytes
## print '--> --> --> --> -->', logxxx2
## for i in logtime, loghost, logbytes, logxxx2:
## if '!' in i: print '???', i
add(bydate, logtime[-4:] + ' ' + logtime[:6], items)
add(bytime, logtime[7:9] + ':00-59', items)
direction, logfile = logfile[0], logfile[1:]
# The real path probably starts at the last //...
while 1: while 1:
i = string.find(logfile, '//') line = f.readline()
if i < 0: break if not line: break
logfile = logfile[i+1:] lineno = lineno + 1
add(byfile, logfile + ' ' + direction, items) if search and string.find(line, search) < 0:
logdir = os.path.dirname(logfile) continue
if prog.match(line) < 0:
print 'Bad line', lineno, ':', `line`
continue
items = prog.group(1, 2, 3, 4, 5, 6)
(logtime, loguser, loghost, logfile, logbytes,
logxxx2) = items
## print logtime
## print '-->', loguser
## print '--> -->', loghost
## print '--> --> -->', logfile
## print '--> --> --> -->', logbytes
## print '--> --> --> --> -->', logxxx2
## for i in logtime, loghost, logbytes, logxxx2:
## if '!' in i: print '???', i
add(bydate, logtime[-4:] + ' ' + logtime[:6], items)
add(bytime, logtime[7:9] + ':00-59', items)
direction, logfile = logfile[0], logfile[1:]
# The real path probably starts at the last //...
while 1:
i = string.find(logfile, '//')
if i < 0: break
logfile = logfile[i+1:]
add(byfile, logfile + ' ' + direction, items)
logdir = os.path.dirname(logfile)
## logdir = os.path.normpath(logdir) + '/.' ## logdir = os.path.normpath(logdir) + '/.'
while 1: while 1:
add(bydir, logdir + ' ' + direction, items) add(bydir, logdir + ' ' + direction, items)
dirhead = os.path.dirname(logdir) dirhead = os.path.dirname(logdir)
if dirhead == logdir: break if dirhead == logdir: break
logdir = dirhead logdir = dirhead
add(byhost, loghost, items) add(byhost, loghost, items)
add(byuser, loguser, items) add(byuser, loguser, items)
add(bytype, direction, items) add(bytype, direction, items)
except KeyboardInterrupt: except KeyboardInterrupt:
print 'Interrupted at line', lineno print 'Interrupted at line', lineno
show(bytype, 'by transfer direction', maxitems) show(bytype, 'by transfer direction', maxitems)
......
...@@ -96,11 +96,11 @@ sublistsize = 4 ...@@ -96,11 +96,11 @@ sublistsize = 4
####################################################################### #######################################################################
for dir in os.curdir, os.environ['HOME']: for dir in os.curdir, os.environ['HOME']:
rcfile = os.path.join(dir, '.newslistrc.py') rcfile = os.path.join(dir, '.newslistrc.py')
if os.path.exists(rcfile): if os.path.exists(rcfile):
print rcfile print rcfile
execfile(rcfile) execfile(rcfile)
break break
from nntplib import NNTP from nntplib import NNTP
from stat import * from stat import *
...@@ -120,8 +120,8 @@ page = os.path.join(topdir,pagedir) ...@@ -120,8 +120,8 @@ page = os.path.join(topdir,pagedir)
def addtotree(tree, groups): def addtotree(tree, groups):
print 'Updating tree...' print 'Updating tree...'
for i in groups: for i in groups:
parts = string.splitfields(i,'.') parts = string.splitfields(i,'.')
makeleaf(tree, parts) makeleaf(tree, parts)
# Makeleaf makes a leaf and the branch leading to it if necessary # Makeleaf makes a leaf and the branch leading to it if necessary
def makeleaf(tree,path): def makeleaf(tree,path):
...@@ -135,7 +135,7 @@ def makeleaf(tree,path): ...@@ -135,7 +135,7 @@ def makeleaf(tree,path):
if l > 1: if l > 1:
makeleaf(tree[j],path[1:]) makeleaf(tree[j],path[1:])
# Then the bits for outputting trees as pages ---------------- # Then the bits for outputting trees as pages ----------------
# Createpage creates an HTML file named <root>.html containing links # Createpage creates an HTML file named <root>.html containing links
# to those groups beginning with <root>. # to those groups beginning with <root>.
...@@ -177,24 +177,24 @@ def printtree(f, tree, indent, p): ...@@ -177,24 +177,24 @@ def printtree(f, tree, indent, p):
if l > 1: if l > 1:
kl.sort() kl.sort()
if indent > 0: if indent > 0:
# Create a sub-list # Create a sub-list
f.write('<LI>'+p[1:]+'\n<UL>') f.write('<LI>'+p[1:]+'\n<UL>')
else: else:
# Create a main list # Create a main list
f.write('<UL>') f.write('<UL>')
indent = indent + 1 indent = indent + 1
for i in kl: for i in kl:
if i == '.': if i == '.':
# Output a newsgroup # Output a newsgroup
f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ') f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ')
if desc.has_key(p[1:]): if desc.has_key(p[1:]):
f.write(' <I>'+desc[p[1:]]+'</I>\n') f.write(' <I>'+desc[p[1:]]+'</I>\n')
else: else:
f.write('\n') f.write('\n')
else: else:
# Output a hierarchy # Output a hierarchy
printtree(f,tree[i], indent, p+'.'+i) printtree(f,tree[i], indent, p+'.'+i)
if l > 1: if l > 1:
f.write('\n</UL>') f.write('\n</UL>')
...@@ -209,7 +209,7 @@ def readdesc(descfile): ...@@ -209,7 +209,7 @@ def readdesc(descfile):
desc = {} desc = {}
if descfile == '': if descfile == '':
return return
try: try:
d = open(descfile, 'r') d = open(descfile, 'r')
...@@ -221,12 +221,12 @@ def readdesc(descfile): ...@@ -221,12 +221,12 @@ def readdesc(descfile):
while l != '': while l != '':
bits = string.split(l) bits = string.split(l)
try: try:
grp = bits[0] grp = bits[0]
dsc = string.join(bits[1:]) dsc = string.join(bits[1:])
if len(dsc)>1: if len(dsc)>1:
desc[grp] = dsc desc[grp] = dsc
except (IndexError): except (IndexError):
pass pass
l = d.readline() l = d.readline()
# Check that ouput directory exists, ------------------------------ # Check that ouput directory exists, ------------------------------
...@@ -237,14 +237,14 @@ def checkopdir(pagedir): ...@@ -237,14 +237,14 @@ def checkopdir(pagedir):
print 'Directory '+pagedir+' does not exist.' print 'Directory '+pagedir+' does not exist.'
print 'Shall I create it for you? (y/n)' print 'Shall I create it for you? (y/n)'
if sys.stdin.readline()[0] == 'y': if sys.stdin.readline()[0] == 'y':
try: try:
os.mkdir(pagedir,0777) os.mkdir(pagedir,0777)
except: except:
print 'Sorry - failed!' print 'Sorry - failed!'
sys.exit(1) sys.exit(1)
else: else:
print 'OK. Exiting.' print 'OK. Exiting.'
sys.exit(1) sys.exit(1)
# Read and write current local tree ---------------------------------- # Read and write current local tree ----------------------------------
...@@ -252,19 +252,19 @@ def readlocallist(treefile): ...@@ -252,19 +252,19 @@ def readlocallist(treefile):
print 'Reading current local group list...' print 'Reading current local group list...'
tree = {} tree = {}
try: try:
treetime = time.localtime(os.stat(treefile)[ST_MTIME]) treetime = time.localtime(os.stat(treefile)[ST_MTIME])
except: except:
print '\n*** Failed to open local group cache '+treefile print '\n*** Failed to open local group cache '+treefile
print 'If this is the first time you have run newslist, then' print 'If this is the first time you have run newslist, then'
print 'use the -a option to create it.' print 'use the -a option to create it.'
sys.exit(1) sys.exit(1)
treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2]) treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2])
try: try:
dump = open(treefile,'r') dump = open(treefile,'r')
tree = marshal.load(dump) tree = marshal.load(dump)
dump.close() dump.close()
except (IOError): except (IOError):
print 'Cannot open local group list ' + treefile print 'Cannot open local group list ' + treefile
return (tree, treedate) return (tree, treedate)
def writelocallist(treefile, tree): def writelocallist(treefile, tree):
...@@ -291,9 +291,9 @@ def getallgroups(server): ...@@ -291,9 +291,9 @@ def getallgroups(server):
for i in info: for i in info:
grpname = string.split(i[0])[0] grpname = string.split(i[0])[0]
if skipempty and string.atoi(i[1]) < string.atoi(i[2]): if skipempty and string.atoi(i[1]) < string.atoi(i[2]):
print grpname+' ', print grpname+' ',
else: else:
groups.append(grpname) groups.append(grpname)
print '\n' print '\n'
if skipempty: if skipempty:
print '(End of empty groups)' print '(End of empty groups)'
...@@ -326,9 +326,9 @@ def main(): ...@@ -326,9 +326,9 @@ def main():
try: try:
print 'Connecting to '+newshost+'...' print 'Connecting to '+newshost+'...'
if sys.version[0] == '0': if sys.version[0] == '0':
s = NNTP.init(newshost) s = NNTP.init(newshost)
else: else:
s = NNTP(newshost) s = NNTP(newshost)
connected = 1 connected = 1
except (nntplib.error_temp, nntplib.error_perm), x: except (nntplib.error_temp, nntplib.error_perm), x:
print 'Error connecting to host:', x print 'Error connecting to host:', x
...@@ -346,7 +346,7 @@ def main(): ...@@ -346,7 +346,7 @@ def main():
(tree, treedate) = readlocallist(treefile) (tree, treedate) = readlocallist(treefile)
if connected: if connected:
groups = getnewgroups(s, treedate) groups = getnewgroups(s, treedate)
if connected: if connected:
addtotree(tree, groups) addtotree(tree, groups)
......
...@@ -217,108 +217,108 @@ commands['\b'] = WC_BACKSPACE ...@@ -217,108 +217,108 @@ commands['\b'] = WC_BACKSPACE
commands['\t'] = WC_TAB commands['\t'] = WC_TAB
# #
def getevent(): def getevent():
while 1: while 1:
# #
# Get next event from the processed queue, if any # Get next event from the processed queue, if any
# #
if G.queue: if G.queue:
event = G.queue[0] event = G.queue[0]
del G.queue[0] del G.queue[0]
#print 'getevent from queue -->', event #print 'getevent from queue -->', event
return event return event
# #
# Get next event from the draw queue, if any, # Get next event from the draw queue, if any,
# but only if there is nothing in the system queue. # but only if there is nothing in the system queue.
# #
if G.drawqueue and not gl.qtest(): if G.drawqueue and not gl.qtest():
win = G.drawqueue[0] win = G.drawqueue[0]
del G.drawqueue[0] del G.drawqueue[0]
gl.winset(win._gid) gl.winset(win._gid)
gl.color(win._bg) gl.color(win._bg)
gl.clear() gl.clear()
event = WE_DRAW, win, win._area event = WE_DRAW, win, win._area
#print 'getevent from drawqueue -->', event #print 'getevent from drawqueue -->', event
return event return event
# #
# Get next event from system queue, blocking if necessary # Get next event from system queue, blocking if necessary
# until one is available. # until one is available.
# Some cases immediately return the event, others do nothing # Some cases immediately return the event, others do nothing
# or append one or more events to the processed queue. # or append one or more events to the processed queue.
# #
dev, val = gl.qread() dev, val = gl.qread()
# #
if dev == REDRAW: if dev == REDRAW:
win = G.windowmap[`val`] win = G.windowmap[`val`]
old_area = win._area old_area = win._area
win._fixviewport() win._fixviewport()
win._needredraw() win._needredraw()
if old_area <> win._area: if old_area <> win._area:
#print 'getevent --> WE_SIZE' #print 'getevent --> WE_SIZE'
return WE_SIZE, win, None return WE_SIZE, win, None
elif dev == KEYBD: elif dev == KEYBD:
if val == 3: if val == 3:
raise KeyboardInterrupt # Control-C in window raise KeyboardInterrupt # Control-C in window
character = chr(val) character = chr(val)
if commands.has_key(character): if commands.has_key(character):
return WE_COMMAND, G.focus, commands[character] return WE_COMMAND, G.focus, commands[character]
return WE_CHAR, G.focus, character return WE_CHAR, G.focus, character
elif dev == LEFTARROWKEY: elif dev == LEFTARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_LEFT return WE_COMMAND, G.focus, WC_LEFT
elif dev == RIGHTARROWKEY: elif dev == RIGHTARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_RIGHT return WE_COMMAND, G.focus, WC_RIGHT
elif dev == UPARROWKEY: elif dev == UPARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_UP return WE_COMMAND, G.focus, WC_UP
elif dev == DOWNARROWKEY: elif dev == DOWNARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_DOWN return WE_COMMAND, G.focus, WC_DOWN
elif dev in (LEFTALTKEY, RIGHTALTKEY): elif dev in (LEFTALTKEY, RIGHTALTKEY):
if val: if val:
for code in codelist: for code in codelist:
gl.qdevice(code) gl.qdevice(code)
else:
for code in codelist:
gl.unqdevice(code)
elif dev in codelist:
if val:
event = G.focus._doshortcut(code2key[`dev`])
if event:
return event
elif dev == LEFTMOUSE:
G.mousex = gl.getvaluator(MOUSEX)
G.mousey = gl.getvaluator(MOUSEY)
if val:
type = WE_MOUSE_DOWN
gl.qdevice(MOUSEX)
gl.qdevice(MOUSEY)
else:
type = WE_MOUSE_UP
gl.unqdevice(MOUSEX)
gl.unqdevice(MOUSEY)
return _mouseevent(type)
elif dev == MOUSEX:
G.mousex = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == MOUSEY:
G.mousey = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == RIGHTMOUSE: # Menu button press/release
if val: # Press
event = G.focus._domenu()
if event:
return event
elif dev == INPUTCHANGE:
if G.focus:
G.queue.append(WE_DEACTIVATE, G.focus, None)
G.focus = G.windowmap[`val`]
if G.focus:
G.queue.append(WE_ACTIVATE, G.focus, None)
elif dev in (WINSHUT, WINQUIT):
return WE_CLOSE, G.windowmap[`val`], None
else: else:
for code in codelist: print '*** qread() --> dev:', dev, 'val:', val
gl.unqdevice(code)
elif dev in codelist:
if val:
event = G.focus._doshortcut(code2key[`dev`])
if event:
return event
elif dev == LEFTMOUSE:
G.mousex = gl.getvaluator(MOUSEX)
G.mousey = gl.getvaluator(MOUSEY)
if val:
type = WE_MOUSE_DOWN
gl.qdevice(MOUSEX)
gl.qdevice(MOUSEY)
else:
type = WE_MOUSE_UP
gl.unqdevice(MOUSEX)
gl.unqdevice(MOUSEY)
return _mouseevent(type)
elif dev == MOUSEX:
G.mousex = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == MOUSEY:
G.mousey = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == RIGHTMOUSE: # Menu button press/release
if val: # Press
event = G.focus._domenu()
if event:
return event
elif dev == INPUTCHANGE:
if G.focus:
G.queue.append(WE_DEACTIVATE, G.focus, None)
G.focus = G.windowmap[`val`]
if G.focus:
G.queue.append(WE_ACTIVATE, G.focus, None)
elif dev in (WINSHUT, WINQUIT):
return WE_CLOSE, G.windowmap[`val`], None
else:
print '*** qread() --> dev:', dev, 'val:', val
# Helper routine to construct a mouse (up, move or down) event # Helper routine to construct a mouse (up, move or down) event
# #
......
This diff is collapsed.
...@@ -474,16 +474,16 @@ class mrsw: ...@@ -474,16 +474,16 @@ class mrsw:
self.rwOK.release() self.rwOK.release()
def write_to_read(self): def write_to_read(self):
self.rwOK.acquire() self.rwOK.acquire()
if not self.writing: if not self.writing:
raise ValueError, \ raise ValueError, \
'.write_to_read() invoked without an active writer' '.write_to_read() invoked without an active writer'
self.writing = 0 self.writing = 0
self.nw = self.nw - 1 self.nw = self.nw - 1
self.nr = self.nr + 1 self.nr = self.nr + 1
if not self.nw: if not self.nw:
self.readOK.broadcast() self.readOK.broadcast()
self.rwOK.release() self.rwOK.release()
# The rest of the file is a test case, that runs a number of parallelized # The rest of the file is a test case, that runs a number of parallelized
# quicksorts in parallel. If it works, you'll get about 600 lines of # quicksorts in parallel. If it works, you'll get about 600 lines of
......
...@@ -31,64 +31,64 @@ input=open(filename) ; output=open(outputname, 'w') ...@@ -31,64 +31,64 @@ input=open(filename) ; output=open(outputname, 'w')
if compressing: if compressing:
output.write('\037\213\010') # Write the header, ... output.write('\037\213\010') # Write the header, ...
output.write(chr(FNAME)) # ... flag byte ... output.write(chr(FNAME)) # ... flag byte ...
import os # ... modification time ... import os # ... modification time ...
statval=os.stat(filename) statval=os.stat(filename)
mtime=statval[8] mtime=statval[8]
write32(output, mtime) write32(output, mtime)
output.write('\002') # ... slowest compression alg. ... output.write('\002') # ... slowest compression alg. ...
output.write('\377') # ... OS (=unknown) ... output.write('\377') # ... OS (=unknown) ...
output.write(filename+'\000') # ... original filename ... output.write(filename+'\000') # ... original filename ...
crcval=zlib.crc32("") crcval=zlib.crc32("")
compobj=zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, compobj=zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL, 0) zlib.DEF_MEM_LEVEL, 0)
while (1): while (1):
data=input.read(1024) data=input.read(1024)
if data=="": break if data=="": break
crcval=zlib.crc32(data, crcval) crcval=zlib.crc32(data, crcval)
output.write(compobj.compress(data)) output.write(compobj.compress(data))
output.write(compobj.flush()) output.write(compobj.flush())
write32(output, crcval) # ... the CRC ... write32(output, crcval) # ... the CRC ...
write32(output, statval[6]) # and the file size. write32(output, statval[6]) # and the file size.
else: else:
magic=input.read(2) magic=input.read(2)
if magic!='\037\213': if magic!='\037\213':
print 'Not a gzipped file' ; sys.exit(0) print 'Not a gzipped file' ; sys.exit(0)
if ord(input.read(1))!=8: if ord(input.read(1))!=8:
print 'Unknown compression method' ; sys.exit(0) print 'Unknown compression method' ; sys.exit(0)
flag=ord(input.read(1)) flag=ord(input.read(1))
input.read(4+1+1) # Discard modification time, input.read(4+1+1) # Discard modification time,
# extra flags, and OS byte. # extra flags, and OS byte.
if flag & FEXTRA: if flag & FEXTRA:
# Read & discard the extra field, if present # Read & discard the extra field, if present
xlen=ord(input.read(1)) xlen=ord(input.read(1))
xlen=xlen+256*ord(input.read(1)) xlen=xlen+256*ord(input.read(1))
input.read(xlen) input.read(xlen)
if flag & FNAME: if flag & FNAME:
# Read and discard a null-terminated string containing the filename # Read and discard a null-terminated string containing the filename
while (1): while (1):
s=input.read(1) s=input.read(1)
if s=='\000': break if s=='\000': break
if flag & FCOMMENT: if flag & FCOMMENT:
# Read and discard a null-terminated string containing a comment # Read and discard a null-terminated string containing a comment
while (1): while (1):
s=input.read(1) s=input.read(1)
if s=='\000': break if s=='\000': break
if flag & FHCRC: if flag & FHCRC:
input.read(2) # Read & discard the 16-bit header CRC input.read(2) # Read & discard the 16-bit header CRC
decompobj=zlib.decompressobj(-zlib.MAX_WBITS) decompobj=zlib.decompressobj(-zlib.MAX_WBITS)
crcval=zlib.crc32("") crcval=zlib.crc32("")
length=0 length=0
while (1): while (1):
data=input.read(1024) data=input.read(1024)
if data=="": break if data=="": break
decompdata=decompobj.decompress(data) decompdata=decompobj.decompress(data)
print len(decompdata) print len(decompdata)
output.write(decompdata) ; length=length+len(decompdata) output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval) crcval=zlib.crc32(decompdata, crcval)
decompdata=decompobj.flush() decompdata=decompobj.flush()
output.write(decompdata) ; length=length+len(decompdata) output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval) crcval=zlib.crc32(decompdata, crcval)
......
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