[Pydev-cvs] org.python.pydev.test bdb.py,NONE,1.1 testthread.py,NONE,1.1 .project,NONE,1.1 dumpobj.p
Brought to you by:
fabioz
From: Aleksandar T. <at...@us...> - 2004-05-11 06:21:28
|
Update of /cvsroot/pydev/org.python.pydev.test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv8012 Added Files: bdb.py testthread.py .project dumpobj.py error.py README.txt simple.py palmFile.py Log Message: --- NEW FILE: .project --- <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>org.python.pydev.test</name> <comment></comment> <projects> </projects> <buildSpec> </buildSpec> <natures> </natures> </projectDescription> --- NEW FILE: simple.py --- import threading import time import inspect print "I am very simple" #s = raw_input("type something now: ") #print "you've typed", s from types import * def getType(o): if isinstance(o, NoneType): return (NoneType, False) if isinstance(o, ObjectType): return (ObjectType, False) if isinstance(o, IntType): return (IntType, False) if isinstance(o, LongType): return (LongType, False) if isinstance(o, FloatType): return (FloatType, False) if isinstance(o, BooleanType): return (BooleanType, False) if isinstance(o, ComplexType): return (ComplexType, False) if isinstance(o, StringType): return (StringType, False) if isinstance(o, UnicodeType): return (UnicodeType, False) if isinstance(o, BufferType): return (BufferType, False) if isinstance(o, TupleType): return (TupleType, True) if isinstance(o, ListType): return (ListType, True) if isinstance(o, DictType): return (DictType, True) if isinstance(o, FunctionType): return (FunctionType, True) if isinstance(o, LambdaType): return (LambdaType, True) if isinstance(o, GeneratorType): return (GeneratorType, True) if isinstance(o, ClassType): return (ClassType, True) if isinstance(o, UnboundMethodType): return (UnboundMethodType, True) if isinstance(o, InstanceType): return (InstanceType, True) if isinstance(o, BuiltinFunctionType): return (BuiltinFunctionType, False) if isinstance(o, BuiltinMethodType): return (BuiltinMethodType, False) if isinstance(o, ModuleType): return (ModuleType, True) if isinstance(o, FileType): return (FileType, True) if isinstance(o, XRangeType): return (XRangeType, True) if isinstance(o, TracebackType): return (TracebackType, True) if isinstance(o, FrameType): return (FrameType, True) if isinstance(o, SliceType): return (SliceType, True) if isinstance(o, EllipsisType): return (EllipsisType, False) if isinstance(o, DictProxyType): return (DictProxyType, True) if isinstance(o, NotImplementedType): return (NotImplementedType, False) def infinite_fun(): i = 1 while True: i = 1 time.sleep(i) print "I've been asleep for " + str(i) + " sec." # infinite_fun() class SimplestThread(threading.Thread): def run(self): print "just one statement" print "and now I exit thread" import mymodule.foo mymodule.foo.bar() --- NEW FILE: testthread.py --- import threading import thread import time import bdb import sys import inspect import types class DeepThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setName("Deep thread") def f1(self, first): print "entering f1 with argument ", first time.sleep(1) self.f2(first, "and one more") print "leaving f1" def f2(self, one, two): print "entering f2", one, two for i in range(100): self.f3(one, two, 3) print "leaving f2" def f3(self, ein, tzwei, drei): print "entering f3" print ein print tzwei print str(drei) print "one" print "two" print "three" print "four" print "five" print "six is sleep" time.sleep(1) print "seven" print "eight" print "leaving f3" def run(self): self.f1("hello") class First(threading.Thread): def __init__(self, delay, name): threading.Thread.__init__(self) self.delay = delay self.setName(name) self.setDaemon(True) self.__verbose = True def run(self): i=4 while (i > 0): i = i - 1 # print self.getName() + str(i) time.sleep(self.delay) print >>sys.stderr, "exiting", self.getName() class KillEm(threading.Thread): def __init__(self, delay): threading.Thread.__init__(self) self.delay = delay self.setName("KillerThread") def run(self): print "coming in for a kill in " + str(self.delay) + " seconds" time.sleep(self.delay) print "Killing!" + str(self.delay) + " seconds" Tdb.instance.do_quit() class Tdb: instance = None def __init__(self): Tdb.instance = self threading.settrace(self.trace_dispatch) # for all threads def trace_dispatch(self, frame, event, arg): print frame print id(frame) if event == 'line': return self.dispatch_line(frame) if event == 'call': return self.dispatch_call(frame, arg) if event == 'return': return self.dispatch_return(frame, arg) if event == 'exception': return self.dispatch_exception(frame, arg) return self.trace_dispatch def dispatch_line(self, frame): # print id(threading.currentThread()) # print inspect.getframeinfo(frame) return self.trace_dispatch def dispatch_call(self, frame, arg): print "C " + str(frame) + " " + str(arg) return self.trace_dispatch def dispatch_return(self, frame, arg): print "R " + str(frame) + " " + str(arg) return self.trace_dispatch def dispatch_exception(self, frame, arg): print "E " + str(frame) + " " + str(arg) return self.trace_dispatch def run(self, cmd, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals if not isinstance(cmd, types.CodeType): cmd = cmd+'\n' try: try: exec cmd in globals, locals except: # print sys.stderr, "Debugger exiting with exception" raise finally: print "Quitting now" self.quitting = 1 def infinite_fun(): i = 1 while True: i += 10 time.sleep(i) print "I've been asleep for " + str(i) + " sec." def infinite2(): infinite_fun() def infinite_1(): infinite2() def many_threads(): print "many threads" t = First(1, "1 seconder ") t2 = First(2, "2 cool 4 you ") t3 = First(3, "3 is a magic number ") dt = DeepThread() # t.start() # t2.start() # t3.start() dt.start() # infinite_1() def test(): t = Tdb() t.run('many_threads()') if __name__ == "__main__": many_threads() raw_input("ready to quit now? ") --- NEW FILE: dumpobj.py --- def printDict(di, format="%-25s %s"): for (key, val) in di.items(): print format % (str(key)+':', val) def dumpObj(obj, maxlen=77, lindent=24, maxspew=600): """Print a nicely formatted overview of an object. The output lines will be wrapped at maxlen, with lindent of space for names of attributes. A maximum of maxspew characters will be printed for each attribute value. You can hand dumpObj any data type -- a module, class, instance, new class. Note that in reformatting for compactness the routine trashes any formatting in the docstrings it prints. Example: >>> class Foo(object): a = 30 def bar(self, b): "A silly method" return a*b ... ... ... ... >>> foo = Foo() >>> dumpObj(foo) Instance of class 'Foo' as defined in module __main__ with id 136863308 Documentation string: None Built-in Methods: __delattr__, __getattribute__, __hash__, __init__ __new__, __reduce__, __repr__, __setattr__, __str__ Methods: bar "A silly method" Attributes: __dict__ {} __weakref__ None a 30 """ import types # Formatting parameters. ltab = 2 # initial tab in front of level 2 text # There seem to be a couple of other types; gather templates of them MethodWrapperType = type(object().__hash__) # # Gather all the attributes of the object # objclass = None objdoc = None objmodule = '<None defined>' methods = [] builtins = [] classes = [] attrs = [] for slot in dir(obj): attr = getattr(obj, slot) if slot == '__class__': objclass = attr.__name__ elif slot == '__doc__': objdoc = attr elif slot == '__module__': objmodule = attr elif (isinstance(attr, types.BuiltinMethodType) or isinstance(attr, MethodWrapperType)): builtins.append( slot ) elif (isinstance(attr, types.MethodType) or isinstance(attr, types.FunctionType)): methods.append( (slot, attr) ) elif isinstance(attr, types.TypeType): classes.append( (slot, attr) ) else: attrs.append( (slot, attr) ) # # Organize them # methods.sort() builtins.sort() classes.sort() attrs.sort() # # Print a readable summary of those attributes # normalwidths = [lindent, maxlen - lindent] tabbedwidths = [ltab, lindent-ltab, maxlen - lindent - ltab] def truncstring(s, maxlen): if len(s) > maxlen: return s[0:maxlen] + ' ...(%d more chars)...' % (len(s) - maxlen) else: return s # Summary of introspection attributes if objclass == '': objclass = type(obj).__name__ intro = "Instance of class '%s' as defined in module %s with id %d" % \ (objclass, objmodule, id(obj)) print '\n'.join(prettyPrint(intro, maxlen)) # Object's Docstring if objdoc is None: objdoc = str(objdoc) else: objdoc = ('"""' + objdoc.strip() + '"""') print print prettyPrintCols( ('Documentation string:', truncstring(objdoc, maxspew)), normalwidths, ' ') # Built-in methods if builtins: bi_str = delchars(str(builtins), "[']") or str(None) print print prettyPrintCols( ('Built-in Methods:', truncstring(bi_str, maxspew)), normalwidths, ', ') # Classes if classes: print print 'Classes:' for (classname, classtype) in classes: classdoc = getattr(classtype, '__doc__', None) or '<No documentation>' print prettyPrintCols( ('', classname, truncstring(classdoc, maxspew)), tabbedwidths, ' ') # User methods if methods: print print 'Methods:' for (methodname, method) in methods: methoddoc = getattr(method, '__doc__', None) or '<No documentation>' print prettyPrintCols( ('', methodname, truncstring(methoddoc, maxspew)), tabbedwidths, ' ') # Attributes if attrs: print print 'Attributes:' for (attr, val) in attrs: print prettyPrintCols( ('', attr, truncstring(str(val), maxspew)), tabbedwidths, ' ') def prettyPrintCols(strings, widths, split=' '): """Pretty prints text in colums, with each string breaking at split according to prettyPrint. margins gives the corresponding right breaking point.""" assert len(strings) == len(widths) strings = map(nukenewlines, strings) # pretty print each column cols = [''] * len(strings) for i in range(len(strings)): cols[i] = prettyPrint(strings[i], widths[i], split) # prepare a format line format = ''.join(["%%-%ds" % width for width in widths[0:-1]]) + "%s" def formatline(*cols): return format % tuple(map(lambda s: (s or ''), cols)) # generate the formatted text return '\n'.join(map(formatline, *cols)) def prettyPrint(string, maxlen=75, split=' '): """Pretty prints the given string to break at an occurrence of split where necessary to avoid lines longer than maxlen. This will overflow the line if no convenient occurrence of split is found""" # Tack on the splitting character to guarantee a final match string += split lines = [] oldeol = 0 eol = 0 while not (eol == -1 or eol == len(string)-1): eol = string.rfind(split, oldeol, oldeol+maxlen+len(split)) lines.append(string[oldeol:eol]) oldeol = eol + len(split) return lines def nukenewlines(string): """Strip newlines and any trailing/following whitespace; rejoin with a single space where the newlines were. Bug: This routine will completely butcher any whitespace-formatted text.""" if not string: return '' lines = string.splitlines() return ' '.join( [line.strip() for line in lines] ) def delchars(str, chars): """Returns a string for which all occurrences of characters in chars have been removed.""" # Translate demands a mapping string of 256 characters; # whip up a string that will leave all characters unmolested. identity = ''.join([chr(x) for x in range(256)]) return str.translate(identity, chars) --- NEW FILE: error.py --- import sys; def mo(): print "mo crashes" a = 1/0 def minnie(): print "minnie" mo() def meenie(): print "mennie" minnie() def eenie(): print "eenie" meenie() if __name__ == "__main__": eenie() --- NEW FILE: palmFile.py --- """ Python module that parses palm files The files are parsed into list/dictionary data structure that mirrors the structure of the palm file. Thanks to Scott Leighton who provided the Palm File format at http://www.geocities.com/Heartland/Acres/3216/palmrecs.htm Usage import palmFile.py fileStruct = readPalmFile(<fileName>) the structure you get back mirrors the file structure. I use import pprint pprint.pprint(fileStruct) to make sense of the data I get back see printAWeekWorthOfCalendar and printAllNames for examples """ """ Author: at...@ya... Version 0.4 Date: 3/22/04 Accepted a patch for reading repeating events from Jeff Mikels Version 0.3 Date: 12/12/03 Patch for readRepeatEvent, from John Lim (Rainlendar guy) Date: Apr 24, 2003 Version: 0.2: fixed dateExceptionCount parsing Date: 11/21/2002 Version: 0.1, my first Python code It works on my machine, Python 2.2, I have not tried it on any others Terminology used in coding: record - a list of items in a known predefined format, not composed of fields each record read has a HEADERDEF defined in this file that describes it frecord - a special record, where each item is a *field* field - fields have type & data. The labels are implicit in their position and are defined in this file as a list items - basic units we know how to read: byte/short/long/, etc """ ### # Generic reading routines ### import struct def readCString(f): """Read in a Palm-format string.""" """ String docs off the net: Strings less than 255 bytes are stored with the length specified in the first byte followed by the actual string. Zero length strings are stored with a 0x00 byte. Strings 255 bytes or longer are stored with a flag byte set to 0xFF followed by a short (2*Byte) that specifies the length of the string, followed by the actual string. """ retVal = None (firstByte, ) = struct.unpack("B", f.read(1)) if firstByte == 0 : retVal = ""; elif firstByte == 0xFF: (length, ) = struct.unpack("H", f.read(2)) retVal = f.read(length) else: # length was in first byte retVal = f.read(firstByte) return retVal def readShort(f): """Read unsigned 2 byte value from a file f.""" (retVal,) = struct.unpack("H", f.read(2)) return retVal def readLong(f): """Read unsigned 4 byte value from a file f.""" (retVal,) = struct.unpack("L", f.read(4)) return retVal def readFloat(f): """Read float (4 byte?) from a file f.""" (retVal,) = struct.unpack("f", f.read(4)) return retVal def readRepeatEvent(f): """Read RepeatEvent, a hacky palm data structure must be read programatically due to randomness of the data structure """ event = {}; event['dateExceptionCount'] = readShort(f) dateExceptions = []; for i in range(event['dateExceptionCount']): dateExceptions.append(readLong(f)) if len(dateExceptions) > 0: event['dateExceptions'] = dateExceptions event['repeatEventFlag']= readShort(f) if event['repeatEventFlag'] == 0: return event if event['repeatEventFlag'] == 0xFFFF: classRecord = {} classRecord['constant'] = readShort(f) classRecord['nameLength'] = readShort(f) classRecord['name'] = f.read(classRecord['nameLength']) if event['repeatEventFlag'] == 0: return event event['brand'] = readLong(f) event['interval'] = readLong(f) event['endDate'] = readLong(f) event['firstDayOfWeek'] = readLong(f) if event['brand'] in (1L,2L,3L): event['brandDayIndex'] = readLong(f) if event['brand'] == 2L: event['brandDaysMask'] = f.read(1) if event['brand'] == 3L: event['brandWeekIndex'] = readLong(f) if event['brand'] in (4L, 5L): event['brandDayNumber'] = readLong(f) if event['brand'] == 5L: event['brandMonthIndex'] = readLong(f) return event def readField(f, fieldType): """Read palm record from a file f. fieldType -- integer specifying the palm field type """ retVal = None if fieldType ==0: # none retVal = None elif fieldType == 1: # integer retVal = readLong(f) elif fieldType == 2: # float retVal = readFloat(f) elif fieldType == 3: # date retVal = readLong(f) elif fieldType == 4: # alpha raise NotImplementedError elif fieldType == 5: # cstring readLong(f) # padding retVal = readCString(f) elif fieldType == 6: # boolean retVal = readLong(f) != 0 elif fieldType == 7: # bit flag retVal = readLong(f) elif fieldType == 8: # repeat event, bad hack, bad retVal = readRepeatEvent(f) else: raise ValueError return retVal def readFRecords(f, fileSoFar, labels): """reads a list of frecords from file f returns -- a list of records fileSoFar -- dictionary of data read so far, used to get the number of records to read labels -- a list of labels for the fields """ fieldsPerRecord = fileSoFar['fieldCount'] # make sure that declared if fieldsPerRecord != len(labels): raise ValueError numberOfRecords = fileSoFar['numEntries'] / fieldsPerRecord; # print "reading", str(numberOfRecords), "records" entries = [] for i in range(numberOfRecords): # print "reading record", str(i) newEntry = {} for j in labels: fieldType = readLong(f) newEntry[j] = readField(f, fieldType) entries.append(newEntry) # print "done with", str(numberOfRecords), "records" return entries def readRecords(f, fileFormat, howMany=1): """reads a list of objects from a file f fileFormat -- HEADERDEF of what format looks like howMany -- how many records to read returns a list of howMany dictionaries: [ {d1}, .... {dN}] """ retVal = [] # print "entering", str(fileFormat[0]); for i in range(howMany): entry = {} for fieldDef in fileFormat: if fieldDef[1] is "long": entry[fieldDef[0]] = readLong(f) elif fieldDef[1] is "short": entry[fieldDef[0]] = readShort(f) elif fieldDef[1] is "cstring": entry[fieldDef[0]] = readCString(f) elif fieldDef[1] is "record": entry[fieldDef[0]] = readRecords(f, eval(fieldDef[2]), entry[fieldDef[3]]) elif fieldDef[1] is "frecord": entry[fieldDef[0]] = readFRecords(f, entry, eval(fieldDef[2])) else: raise AssertionError retVal.append(entry); # print "returning", str(fileFormat[0]) return retVal # Address book defines """ HEADERDEF lists format HEADERDEF are data that represent the file format. I've tried to make all parsing data driven, and HEADERDEF structs describe the grammar. When data to be read go beyound what HEADERDEF defines, 3rd column provides the name Python to be executed. headerDef tuple columns format col 1 property name col 2 type short, long, palm cstring, record, frecord 3 additional argument: if type in col 2 is record, the name of the entry that defines the struct count if type in col 2 is frecord, the python code to execute """ """See HEADERDEF lists format above""" addressHeaderDef = ( ("versionTag", "long"), ("fileName", "cstring"), ("tableString", "cstring"), ("nextFree", "long"), ("categoryCount","long"), ("categoryList", "record", "addressCategoryEntryDef", "categoryCount"), ("resourceID", "long"), ("fieldsPerRow", "long"), ("recIDPos", "long"), ("recStatus", "long"), ("placementPos", "long"), ("fieldCount", "short"), ("fieldEntryList", "record", "addressSchemaFieldDef", "fieldCount"), ("numEntries", "long"), ("addresses", "frecord","addressEntryFields") ) """See HEADERDEF lists format above""" addressCategoryEntryDef = ( ("index", "long"), ("id", "long"), ("dirtyFlag", "long"), ("longName", "cstring"), ("shortName", "cstring") ) """See HEADERDEF lists format above""" addressSchemaFieldDef = ( ("fieldEntryType", "short"), ) """See HEADERDEF lists format above""" addressEntryFields = ( "recordID", "status", "position", "lastName", "firstName", "title", "companyName", "phone1LabelID", "phone1Text", "phone2LabelID", "phone2Text", "phone3LabelID", "phone3Text", "phone4LabelID", "phone4Text", "phone5LabelID", "phone5Text", "address", "city", "state", "zip", "country", "note", "private", "category", "custom1Text", "custom2Text", "custom3Text", "custom4Text", "displayPhone" ) """ # Calendar defines """ """See HEADERDEF lists format above""" calendarHeaderDef = ( ("versionTag", "long"), ("fileName", "cstring"), ("tableString", "cstring"), ("nextFree", "long"), ("categoryCount","long"), ("categoryList", "record", "addressCategoryEntryDef", "categoryCount"), ("resourceID", "long"), ("fieldsPerRow", "long"), ("recIDPos", "long"), ("recStatus", "long"), ("placementPos", "long"), ("fieldCount", "short"), ("fieldEntry", "record", "addressSchemaFieldDef", "fieldCount"), ("numEntries", "long"), ("datebookList", "frecord","calendarEntryFields") ) calendarEntryFields = ( "recordID", "status", "position", "startTime", "endTime", "text", "duration", "note", "untimed", "private", "category", "alarmSet", "alarmAdvUnits", "alarmAdvType", "repeatEvent" ) def getUpcomingEvents(calendar, daysAhead, traceRepeats=0): #returns a list of event dictionaries from now until daysAhead days from now import time calendarDict = calendar[0] dateList = calendarDict['datebookList'] #we don't want to change the original calendar so we create a copy startTime = time.time(); endTime = startTime + (daysAhead * 60 * 60 * 24) # converts daysAhead to seconds retVal = [] #print 'Checking for events between',time.localtime(startTime),'and',time.localtime(endTime) for event in dateList: newEvent = event.copy() if newEvent['startTime'] > startTime and newEvent['startTime'] < endTime: #print 'Adding [', newEvent['text'], '] [', time.localtime(newEvent['startTime']), ']' #pprint.pprint(event) #print '\n\n' retVal.append(newEvent.copy()) if traceRepeats and newEvent['repeatEvent']['repeatEventFlag'] and newEvent['repeatEvent']['endDate'] > startTime: newEvent = getNextRepeatedEvent(newEvent) #print 'Looking [',newEvent['text'],'] [',time.localtime(newEvent['startTime']),']' while newEvent['startTime'] < startTime: newEvent = getNextRepeatedEvent(newEvent) #print 'Looking [',newEvent['text'],'] [',time.localtime(newEvent['startTime']),']' while newEvent['startTime'] <= endTime: #print 'Adding [', newEvent['text'], '] [', time.localtime(newEvent['startTime']), ']' retVal.append(newEvent.copy()) newEvent = getNextRepeatedEvent(newEvent) return retVal def getNextRepeatedEvent(event): import time '''A sample from datebookList: 'repeatEvent': {'brand': 5L, Daily, Weekly, Monthly Date, Monthly Day, YEARLY 'brandDayNumber': 4L, 4th 'brandMonthIndex': 7L, August 'dateExceptionCount': 0, 'endDate': 1028437200L, 'firstDayOfWeek': 0L, 'interval': 1L, 'repeatEventFlag': 65535}, ''' repeatDetails = event['repeatEvent'] repeatStartDST = time.localtime(event['startTime'])[8] if repeatDetails['brand'] == 1: #daily repeat event['startTime'] = event['startTime'] + 60*60*24*repeatDetails['interval'] elif repeatDetails['brand'] == 2: # repeat weekly on specific days targetDaysMask = ord(repeatDetails['brandDaysMask']) #convert character read from file to ascii code #print 'targetDaysMask:',targetDaysMask repeatStartLocal=time.localtime(event['startTime']) if repeatStartLocal[6] == 5: # event's current start time is a Saturday '''add one day to get to Sunday, then add whole weeks according to the specified interval minus one, because we just went from Saturday to Sunday with the first addition. ''' event['startTime'] = event['startTime'] + (60*60*24) + (60*60*24*7) * (repeatDetails['interval'] - 1) repeatStartLocal=time.localtime(event['startTime']) else: event['startTime'] = event['startTime'] + (60*60*24) repeatStartLocal=time.localtime(event['startTime']) '''Python stores Wdays in element 6 of a time_struct, but stores them with Monday as 0 and Sun as 6. This line converts from the python time_struct to a WDay value with Sunday as 0 ''' rsWDay = (repeatStartLocal[6] + 1) % 7 #print time.localtime(event['startTime']),'\n\trsWDay:',rsWDay,'\n\t',2**rsWDay,'\n\t',not ((2**rsWDay) & targetDaysMask) while not ((2**rsWDay) & targetDaysMask): # targetDaysMask is sum of the following: 1 = Sunday, 2 = Monday, 4 = Tues, . . . , 64 = Saturday event['startTime'] = event['startTime'] + (60*60*24) repeatStartLocal=time.localtime(event['startTime']) rsWDay = (repeatStartLocal[6] + 1) % 7 elif repeatDetails['brand'] == 3: #repeat monthly based on day from calendar import monthrange targetDay = repeatDetails['brandDayIndex'] #returns wday according to Python standards with Monday = 0 targetWeek = repeatDetails['brandWeekIndex'] #returns week with first week = 0, fourth week = 3, and last week = 4 for interval in range(1,repeatDetails['interval'] + 1): if targetWeek == 4: #event repeats on last ?day of the month. #event['startTime'] = event['startTime'] + (60*60*24*7) #add one week to current event newTime = event['startTime'] + (60*60*24*7*4) #add four weeks to current event newLocalTime = time.localtime(newTime) monthBegins, monthLength = monthrange(newLocalTime[0],newLocalTime[1]) if (monthLength - newLocalTime[3]) >= 7: newTime = newTime + (60*60*24*7) event['startTime'] = newTime else: #repeats on 1st - 4th ?day of month newTime = event['startTime'] newLocalTime = time.localtime(newTime) oldStartTimeMonth = newLocalTime[1] #advance event until it's the first occurrence of that weekday in the next month while newLocalTime[1] == oldStartTimeMonth: newTime = newTime + (60*60*24*7) #add one week to current event newLocalTime = time.localtime(newTime) event['startTime'] = newTime + (60*60*24*7*(targetWeek)) elif repeatDetails['brand'] == 4: #repeat monthly based on date repeatStartLocal = time.localtime(event['startTime']) event['startTime'] = time.mktime((repeatStartLocal[0],repeatStartLocal[1]+repeatDetails['interval'],repeatStartLocal[2],repeatStartLocal[3],repeatStartLocal[4],repeatStartLocal[5],0,0,0)) elif repeatDetails['brand'] == 5: #repeat yearly based on date repeatStartLocal = time.localtime(event['startTime']) event['startTime'] = time.mktime((repeatStartLocal[0]+repeatDetails['interval'],repeatStartLocal[1],repeatStartLocal[2],repeatStartLocal[3],repeatStartLocal[4],repeatStartLocal[5],0,0,0)) newEventDST = time.localtime(event['startTime'])[8] correctDST = repeatStartDST - newEventDST event['startTime'] = event['startTime'] + (60*60*correctDST) return event def readPalmFile(fileName): """ Read in a Palm fileName with a specified format The type of the file is determined automatically by reading the first four bytes fileFormat -- different files have different formats (address book, calendar...) [abHeaderDef | calHeaderDef] """ retVal = None try: palmFile = open(fileName, "rb") except IOError: print "Palm file", fileName, "cannot be opened\n\n" raise IOError try: sig = palmFile.read(4) palmFile.seek(0) if sig == "\x00\x01BA": # address book fileFormat = addressHeaderDef elif sig == "\x00\x01BD": # datebook (calendar) fileFormat = calendarHeaderDef else: print "Unknown file format ", sig raise ValueError retVal = readRecords(palmFile, fileFormat, 1) except IOError: print "Unexpected error while reading Palm file" raise IOError if palmFile : palmFile.close() return retVal def printAllNames(adBook): """print all names in the address book demo of walking the address book structure """ addressDict = adBook[0] addresses = addressDict["addresses"] for address in addresses: print address["firstName"],address["lastName"] # this is a simple version that does not take repeating events # into account. See newer printAWeekWorthOfCalendar(calendar,traceRepeats=0) # for repeated events implementation def printAWeekWorthOfCalendar(calendar): """demo of walking the calendar data structure prints all events a week from now """ import time calendarDict = calendar[0] dateList = calendarDict['datebookList'] startTime = time.time(); endTime = startTime + 60*60*24*7 # a week worth of seconds print "Your schedule next week:" for event in dateList: if event['startTime'] > startTime and event['startTime'] < endTime: if event['untimed']: print time.strftime("%x ***", time.localtime(event['startTime'])), event['text'] else : print time.strftime("%c-", time.localtime(event['startTime'])), time.strftime("%X", time.localtime(event['endTime'])),event['text'] if event['note']: print event['note'] def printAWeekWorthOfCalendar(calendar,traceRepeats=0): """demo of walking the calendar data structure prints all events a week from now """ import time print "Your schedule next week:" events = getUpcomingEvents(calendar,7,traceRepeats) for event in events: if event['untimed']: print time.strftime("%x ***", time.localtime(event['startTime'])), event['text'] else : print time.strftime("%c-", time.localtime(event['startTime'])), time.strftime("%X", time.localtime(event['endTime'])),event['text'] if event['note']: print event['note'] if __name__ == "__main__": import sys import getopt try: options, args = getopt.getopt(sys.argv[1:], 'v') verbose = len(options) > 0 and options[0][0] == "-v" if (len(args) != 1): raise RuntimeError, "Missing filename" except: print "Usage: python palmFile.py [-v] <fileName>" print "-v for verbose, print all the data in the file" print "\nPrint out sample data from a palm file" sys.exit() palmData = readPalmFile(args[0]) if verbose: import pprint pprint.pprint(palmData) if palmData[0]["versionTag"] == 1094844672L: # addresses printAllNames(palmData) elif palmData[0]["versionTag"] == 1145176320L: # datebook printAWeekWorthOfCalendar(palmData, 1) --- NEW FILE: bdb.py --- """Debugger basics""" import sys import os import types __all__ = ["BdbQuit","Bdb","Breakpoint"] BdbQuit = 'bdb.BdbQuit' # Exception to give up completely class Bdb: """Generic Python debugger base class. This class takes care of details of the trace facility; a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example. """ def __init__(self): self.breaks = {} self.fncache = {} # comment """ this line does not get indented""" def canonic(self, filename): if filename == "<" + filename[1:-1] + ">": return filename canonic = self.fncache.get(filename) if not canonic: canonic = os.path.abspath(filename) canonic = os.path.normcase(canonic) self.fncache[filename] = canonic return canonic def reset(self): import linecache linecache.checkcache() self.botframe = None self.stopframe = None self.returnframe = None self.quitting = 0 def trace_dispatch(self, frame, event, arg): if self.quitting: return # None if event == 'line': return self.dispatch_line(frame) if event == 'call': return self.dispatch_call(frame, arg) if event == 'return': return self.dispatch_return(frame, arg) if event == 'exception': return self.dispatch_exception(frame, arg) print 'bdb.Bdb.dispatch: unknown debugging event:', `event` return self.trace_dispatch def dispatch_line(self, frame): if self.stop_here(frame) or self.break_here(frame): self.user_line(frame) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_call(self, frame, arg): # XXX 'arg' is no longer used if self.botframe is None: # First call of dispatch since reset() self.botframe = frame.f_back # (CT) Note that this may also be None! return self.trace_dispatch if not (self.stop_here(frame) or self.break_anywhere(frame)): # No need to trace this function return # None self.user_call(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_return(self, frame, arg): if self.stop_here(frame) or frame == self.returnframe: self.user_return(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_exception(self, frame, arg): if self.stop_here(frame): self.user_exception(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch # Normally derived classes don't override the following # methods, but they may if they want to redefine the # definition of stopping and breakpoints. def stop_here(self, frame): # (CT) stopframe may now also be None, see dispatch_call. # (CT) the former test for None is therefore removed from here. if frame is self.stopframe: return 1 while frame is not None and frame is not self.stopframe: if frame is self.botframe: return 1 frame = frame.f_back return 0 def break_here(self, frame): filename = self.canonic(frame.f_code.co_filename) if not self.breaks.has_key(filename): return 0 lineno = frame.f_lineno if not lineno in self.breaks[filename]: return 0 # flag says ok to delete temp. bp (bp, flag) = effective(filename, lineno, frame) if bp: self.currentbp = bp.number if (flag and bp.temporary): self.do_clear(str(bp.number)) return 1 else: return 0 def do_clear(self, arg): raise NotImplementedError, "subclass of bdb must implement do_clear()" def break_anywhere(self, frame): return self.breaks.has_key( self.canonic(frame.f_code.co_filename)) # Derived classes should override the user_* methods # to gain control. def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" pass def user_line(self, frame): """This method is called when we stop or break at this line.""" pass def user_return(self, frame, return_value): """This method is called when a return trap is set here.""" pass def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): """This method is called if an exception occurs, but only if we are to stop at or just below this level.""" pass # Derived classes and clients can call the following methods # to affect the stepping state. def set_step(self): """Stop after one line of code.""" self.stopframe = None self.returnframe = None self.quitting = 0 def set_next(self, frame): """Stop on the next line in or below the given frame.""" self.stopframe = frame self.returnframe = None self.quitting = 0 def set_return(self, frame): """Stop when returning from the given frame.""" self.stopframe = frame.f_back self.returnframe = frame self.quitting = 0 def set_trace(self): """Start debugging from here.""" frame = sys._getframe().f_back self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step() sys.settrace(self.trace_dispatch) def set_continue(self): # Don't stop except at breakpoints or when finished self.stopframe = self.botframe self.returnframe = None self.quitting = 0 if not self.breaks: # no breakpoints; run without debugger overhead sys.settrace(None) frame = sys._getframe().f_back while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back def set_quit(self): self.stopframe = self.botframe self.returnframe = None self.quitting = 1 sys.settrace(None) # Derived classes and clients can call the following methods # to manipulate breakpoints. These methods return an # error message is something went wrong, None if all is well. # Set_break prints out the breakpoint line and file:lineno. # Call self.get_*break*() to see the breakpoints or better # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint(). def set_break(self, filename, lineno, temporary=0, cond = None): filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) if not self.breaks.has_key(filename): self.breaks[filename] = [] list = self.breaks[filename] if not lineno in list: list.append(lineno) bp = Breakpoint(filename, lineno, temporary, cond) def clear_break(self, filename, lineno): filename = self.canonic(filename) if not self.breaks.has_key(filename): return 'There are no breakpoints in %s' % filename if lineno not in self.breaks[filename]: return 'There is no breakpoint at %s:%d' % (filename, lineno) # If there's only one bp in the list for that file,line # pair, then remove the breaks entry for bp in Breakpoint.bplist[filename, lineno][:]: bp.deleteMe() if not Breakpoint.bplist.has_key((filename, lineno)): self.breaks[filename].remove(lineno) if not self.breaks[filename]: del self.breaks[filename] def clear_bpbynumber(self, arg): try: number = int(arg) except: return 'Non-numeric breakpoint number (%s)' % arg try: bp = Breakpoint.bpbynumber[number] except IndexError: return 'Breakpoint number (%d) out of range' % number if not bp: return 'Breakpoint (%d) already deleted' % number self.clear_break(bp.file, bp.line) def clear_all_file_breaks(self, filename): filename = self.canonic(filename) if not self.breaks.has_key(filename): return 'There are no breakpoints in %s' % filename for line in self.breaks[filename]: blist = Breakpoint.bplist[filename, line] for bp in blist: bp.deleteMe() del self.breaks[filename] def clear_all_breaks(self): if not self.breaks: return 'There are no breakpoints' for bp in Breakpoint.bpbynumber: if bp: bp.deleteMe() self.breaks = {} def get_break(self, filename, lineno): filename = self.canonic(filename) return self.breaks.has_key(filename) and \ lineno in self.breaks[filename] def get_breaks(self, filename, lineno): filename = self.canonic(filename) return self.breaks.has_key(filename) and \ lineno in self.breaks[filename] and \ Breakpoint.bplist[filename, lineno] or [] def get_file_breaks(self, filename): filename = self.canonic(filename) if self.breaks.has_key(filename): return self.breaks[filename] else: return [] def get_all_breaks(self): return self.breaks # Derived classes and clients can call the following method # to get a data structure representing a stack trace. def get_stack(self, f, t): stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next return stack, i # def format_stack_entry(self, frame_lineno, lprefix=': '): import linecache, repr frame, lineno = frame_lineno filename = self.canonic(frame.f_code.co_filename) s = filename + '(' + `lineno` + ')' if frame.f_code.co_name: s = s + frame.f_code.co_name else: s = s + "<lambda>" if frame.f_locals.has_key('__args__'): args = frame.f_locals['__args__'] else: args = None if args: s = s + repr.repr(args) else: s = s + '()' if frame.f_locals.has_key('__return__'): rv = frame.f_locals['__return__'] s = s + '->' s = s + repr.repr(rv) line = linecache.getline(filename, lineno) if line: s = s + lprefix + line.strip() return s # The following two methods can be called by clients to use # a debugger to debug a statement, given as a string. def run(self, cmd, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) if not isinstance(cmd, types.CodeType): cmd = cmd+'\n' try: try: exec cmd in globals, locals except BdbQuit: pass finally: self.quitting = 1 sys.settrace(None) def runeval(self, expr, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) if not isinstance(expr, types.CodeType): expr = expr+'\n' try: try: return eval(expr, globals, locals) except BdbQuit: pass finally: self.quitting = 1 sys.settrace(None) def runctx(self, cmd, globals, locals): # B/W compatibility self.run(cmd, globals, locals) # This method is more useful to debug a single function call. def runcall(self, func, *args): self.reset() sys.settrace(self.trace_dispatch) res = None try: try: res = apply(func, args) except BdbQuit: pass finally: self.quitting = 1 sys.settrace(None) return res def set_trace(): Bdb().set_trace() class Breakpoint: """Breakpoint class Implements temporary breakpoints, ignore counts, disabling and (re)-enabling, and conditionals. Breakpoints are indexed by number through bpbynumber and by the file,line tuple using bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line. """ # XXX Keeping state in the class is a mistake -- this means # you cannot have more than one active Bdb instance. next = 1 # Next bp to be assigned bplist = {} # indexed by (file, lineno) tuple bpbynumber = [None] # Each entry is None or an instance of Bpt # index 0 is unused, except for marking an # effective break .... see effective() def __init__(self, file, line, temporary=0, cond = None): self.file = file # This better be in canonical form! self.line = line self.temporary = temporary self.cond = cond self.enabled = 1 self.ignore = 0 self.hits = 0 self.number = Breakpoint.next Breakpoint.next = Breakpoint.next + 1 # Build the two lists self.bpbynumber.append(self) if self.bplist.has_key((file, line)): self.bplist[file, line].append(self) else: self.bplist[file, line] = [self] def deleteMe(self): index = (self.file, self.line) self.bpbynumber[self.number] = None # No longer in list self.bplist[index].remove(self) if not self.bplist[index]: # No more bp for this f:l combo del self.bplist[index] def enable(self): self.enabled = 1 def disable(self): self.enabled = 0 def bpprint(self): if self.temporary: disp = 'del ' else: disp = 'keep ' if self.enabled: disp = disp + 'yes' else: disp = disp + 'no ' print '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) if self.cond: print '\tstop only if %s' % (self.cond,) if self.ignore: print '\tignore next %d hits' % (self.ignore) if (self.hits): if (self.hits > 1): ss = 's' else: ss = '' print ('\tbreakpoint already hit %d time%s' % (self.hits, ss)) # -----------end of Breakpoint class---------- # Determines if there is an effective (active) breakpoint at this # line of code. Returns breakpoint number or 0 if none def effective(file, line, frame): """Determine which breakpoint for this file:line is to be acted upon. Called only if we know there is a bpt at this location. Returns breakpoint that was triggered and a flag that indicates if it is ok to delete a temporary bp. """ possibles = Breakpoint.bplist[file,line] for i in range(0, len(possibles)): b = possibles[i] if b.enabled == 0: continue # Count every hit when bp is enabled b.hits = b.hits + 1 if not b.cond: # If unconditional, and ignoring, # go on to next, else break if b.ignore > 0: b.ignore = b.ignore -1 continue else: # breakpoint and marker that's ok # to delete if temporary return (b,1) else: # Conditional bp. # Ignore count applies only to those bpt hits where the # condition evaluates to true. try: val = eval(b.cond, frame.f_globals, frame.f_locals) if val: if b.ignore > 0: b.ignore = b.ignore -1 # continue else: return (b,1) # else: # continue except: # if eval fails, most conservative # thing is to stop on breakpoint # regardless of ignore count. # Don't delete temporary, # as another hint to user. return (b,0) return (None, None) # -------------------- testing -------------------- class Tdb(Bdb): def user_call(self, frame, args): name = frame.f_code.co_name if not name: name = '???' print '+++ call', name, args def user_line(self, frame): import linecache name = frame.f_code.co_name if not name: name = '???' fn = self.canonic(frame.f_code.co_filename) line = linecache.getline(fn, frame.f_lineno) print '+++', fn, frame.f_lineno, name, ':', line.strip() def user_return(self, frame, retval): print '+++ return', retval def user_exception(self, frame, exc_stuff): print '+++ exception', exc_stuff self.set_continue() def foo(n): print 'foo(', n, ')' x = bar(n*10) print 'bar returned', x def bar(a): print 'bar(', a, ')' return a/2 def test(): t = Tdb() t.run('import bdb; bdb.foo(10)') # end --- NEW FILE: README.txt --- Directory for pydev tests. Right now it is just a collection of random tests. A good project for volunteers. |