diff options
author | Tim Peters <tim.peters@gmail.com> | 2004-07-18 06:16:08 (GMT) |
---|---|---|
committer | Tim Peters <tim.peters@gmail.com> | 2004-07-18 06:16:08 (GMT) |
commit | 182b5aca27d376b08a2904bed42b751496f932f3 (patch) | |
tree | df13115820dbc879c0fe2eae488c9f8c0215a7da /Lib/lib-old | |
parent | e6ddc8b20b493fef2e7cffb2e1351fe1d238857e (diff) | |
download | cpython-182b5aca27d376b08a2904bed42b751496f932f3.zip cpython-182b5aca27d376b08a2904bed42b751496f932f3.tar.gz cpython-182b5aca27d376b08a2904bed42b751496f932f3.tar.bz2 |
Whitespace normalization, via reindent.py.
Diffstat (limited to 'Lib/lib-old')
-rw-r--r-- | Lib/lib-old/Para.py | 656 | ||||
-rw-r--r-- | Lib/lib-old/addpack.py | 56 | ||||
-rw-r--r-- | Lib/lib-old/codehack.py | 70 | ||||
-rw-r--r-- | Lib/lib-old/dump.py | 60 | ||||
-rw-r--r-- | Lib/lib-old/find.py | 36 | ||||
-rw-r--r-- | Lib/lib-old/fmt.py | 1038 | ||||
-rw-r--r-- | Lib/lib-old/grep.py | 118 | ||||
-rw-r--r-- | Lib/lib-old/lockfile.py | 12 | ||||
-rw-r--r-- | Lib/lib-old/newdir.py | 110 | ||||
-rw-r--r-- | Lib/lib-old/packmail.py | 168 | ||||
-rw-r--r-- | Lib/lib-old/poly.py | 60 | ||||
-rw-r--r-- | Lib/lib-old/rand.py | 6 | ||||
-rw-r--r-- | Lib/lib-old/tb.py | 286 | ||||
-rw-r--r-- | Lib/lib-old/util.py | 6 | ||||
-rw-r--r-- | Lib/lib-old/zmod.py | 86 |
15 files changed, 1384 insertions, 1384 deletions
diff --git a/Lib/lib-old/Para.py b/Lib/lib-old/Para.py index 2e6aa4c..2fd8dc6 100644 --- a/Lib/lib-old/Para.py +++ b/Lib/lib-old/Para.py @@ -1,4 +1,4 @@ -# Text formatting abstractions +# Text formatting abstractions # Note -- this module is obsolete, it's too slow anyway @@ -14,330 +14,330 @@ Int = type(0) # different screen locations. Once rendered, it can be queried # for mouse hits, and parts of the text can be highlighted class Para: - # - def __init__(self): - self.words = [] # The words - self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c' - self.indent_left = self.indent_right = self.indent_hang = 0 - # Final lay-out parameters, may change - self.left = self.top = self.right = self.bottom = \ - self.width = self.height = self.lines = None - # - # Add a word, computing size information for it. - # Words may also be added manually by appending to self.words - # Each word should be a 7-tuple: - # (font, text, width, space, stretch, ascent, descent) - def addword(self, d, font, text, space, stretch): - if font is not None: - d.setfont(font) - width = d.textwidth(text) - ascent = d.baseline() - descent = d.lineheight() - ascent - spw = d.textwidth(' ') - space = space * spw - stretch = stretch * spw - tuple = (font, text, width, space, stretch, ascent, descent) - self.words.append(tuple) - # - # Hooks to begin and end anchors -- insert numbers in the word list! - def bgn_anchor(self, id): - self.words.append(id) - # - def end_anchor(self, id): - self.words.append(0) - # - # Return the total length (width) of the text added so far, in pixels - def getlength(self): - total = 0 - for word in self.words: - if type(word) is not Int: - total = total + word[2] + word[3] - return total - # - # Tab to a given position (relative to the current left indent): - # remove all stretch, add fixed space up to the new indent. - # If the current position is already at the tab stop, - # don't add any new space (but still remove the stretch) - def tabto(self, tab): - total = 0 - as, de = 1, 0 - for i in range(len(self.words)): - word = self.words[i] - if type(word) is Int: continue - (fo, te, wi, sp, st, as, de) = word - self.words[i] = (fo, te, wi, sp, 0, as, de) - total = total + wi + sp - if total < tab: - self.words.append((None, '', 0, tab-total, 0, as, de)) - # - # Make a hanging tag: tab to hang, increment indent_left by hang, - # and reset indent_hang to -hang - def makehangingtag(self, hang): - self.tabto(hang) - self.indent_left = self.indent_left + hang - self.indent_hang = -hang - # - # Decide where the line breaks will be given some screen width - def layout(self, linewidth): - self.width = linewidth - height = 0 - self.lines = lines = [] - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - words = self.words - i = 0 - n = len(words) - lastfont = None - while i < n: - firstfont = lastfont - charcount = 0 - width = 0 - stretch = 0 - ascent = 0 - descent = 0 - lsp = 0 - j = i - while i < n: - word = words[i] - if type(word) is Int: - if word > 0 and width >= avail: - break - i = i+1 - continue - fo, te, wi, sp, st, as, de = word - if width + wi > avail and width > 0 and wi > 0: - break - if fo is not None: - lastfont = fo - if width == 0: - firstfont = fo - charcount = charcount + len(te) + (sp > 0) - width = width + wi + sp - lsp = sp - stretch = stretch + st - lst = st - ascent = max(ascent, as) - descent = max(descent, de) - i = i+1 - while i > j and type(words[i-1]) is Int and \ - words[i-1] > 0: i = i-1 - width = width - lsp - if i < n: - stretch = stretch - lst - else: - stretch = 0 - tuple = i-j, firstfont, charcount, width, stretch, \ - ascent, descent - lines.append(tuple) - height = height + ascent + descent - avail = avail1 - self.height = height - # - # Call a function for all words in a line - def visit(self, wordfunc, anchorfunc): - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - v = self.top - i = 0 - for tuple in self.lines: - wordcount, firstfont, charcount, width, stretch, \ - ascent, descent = tuple - h = self.left + self.indent_left - if i == 0: h = h + self.indent_hang - extra = 0 - if self.just == 'r': h = h + avail - width - elif self.just == 'c': h = h + (avail - width) / 2 - elif self.just == 'lr' and stretch > 0: - extra = avail - width - v2 = v + ascent + descent - for j in range(i, i+wordcount): - word = self.words[j] - if type(word) is Int: - ok = anchorfunc(self, tuple, word, \ - h, v) - if ok is not None: return ok - continue - fo, te, wi, sp, st, as, de = word - if extra > 0 and stretch > 0: - ex = extra * st / stretch - extra = extra - ex - stretch = stretch - st - else: - ex = 0 - h2 = h + wi + sp + ex - ok = wordfunc(self, tuple, word, h, v, \ - h2, v2, (j==i), (j==i+wordcount-1)) - if ok is not None: return ok - h = h2 - v = v2 - i = i + wordcount - avail = avail1 - # - # Render a paragraph in "drawing object" d, using the rectangle - # given by (left, top, right) with an unspecified bottom. - # Return the computed bottom of the text. - def render(self, d, left, top, right): - if self.width != right-left: - self.layout(right-left) - self.left = left - self.top = top - self.right = right - self.bottom = self.top + self.height - self.anchorid = 0 - try: - self.d = d - self.visit(self.__class__._renderword, \ - self.__class__._renderanchor) - finally: - self.d = None - return self.bottom - # - def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if word[0] is not None: self.d.setfont(word[0]) - baseline = v + tuple[5] - self.d.text((h, baseline - word[5]), word[1]) - if self.anchorid > 0: - self.d.line((h, baseline+2), (h2, baseline+2)) - # - def _renderanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return which anchor(s) was hit by the mouse - def hitcheck(self, mouseh, mousev): - self.mouseh = mouseh - self.mousev = mousev - self.anchorid = 0 - self.hits = [] - self.visit(self.__class__._hitcheckword, \ - self.__class__._hitcheckanchor) - return self.hits - # - def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if self.anchorid > 0 and h <= self.mouseh <= h2 and \ - v <= self.mousev <= v2: - self.hits.append(self.anchorid) - # - def _hitcheckanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return whether the given anchor id is present - def hasanchor(self, id): - return id in self.words or -id in self.words - # - # Extract the raw text from the word list, substituting one space - # for non-empty inter-word space, and terminating with '\n' - def extract(self): - text = '' - for w in self.words: - if type(w) is not Int: - word = w[1] - if w[3]: word = word + ' ' - text = text + word - return text + '\n' - # - # Return which character position was hit by the mouse, as - # an offset in the entire text as returned by extract(). - # Return None if the mouse was not in this paragraph - def whereis(self, d, mouseh, mousev): - if mousev < self.top or mousev > self.bottom: - return None - self.mouseh = mouseh - self.mousev = mousev - self.lastfont = None - self.charcount = 0 - try: - self.d = d - return self.visit(self.__class__._whereisword, \ - self.__class__._whereisanchor) - finally: - self.d = None - # - def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo is not None: self.lastfont = fo - h = h1 - if isfirst: h1 = 0 - if islast: h2 = 999999 - if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2): - self.charcount = self.charcount + len(te) + (sp > 0) - return - if self.lastfont is not None: - self.d.setfont(self.lastfont) - cc = 0 - for c in te: - cw = self.d.textwidth(c) - if self.mouseh <= h + cw/2: - return self.charcount + cc - cc = cc+1 - h = h+cw - self.charcount = self.charcount + cc - if self.mouseh <= (h+h2) / 2: - return self.charcount - else: - return self.charcount + 1 - # - def _whereisanchor(self, tuple, word, h, v): - pass - # - # Return screen position corresponding to position in paragraph. - # Return tuple (h, vtop, vbaseline, vbottom). - # This is more or less the inverse of whereis() - def screenpos(self, d, pos): - if pos < 0: - ascent, descent = self.lines[0][5:7] - return self.left, self.top, self.top + ascent, \ - self.top + ascent + descent - self.pos = pos - self.lastfont = None - try: - self.d = d - ok = self.visit(self.__class__._screenposword, \ - self.__class__._screenposanchor) - finally: - self.d = None - if ok is None: - ascent, descent = self.lines[-1][5:7] - ok = self.right, self.bottom - ascent - descent, \ - self.bottom - descent, self.bottom - return ok - # - def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo is not None: self.lastfont = fo - cc = len(te) + (sp > 0) - if self.pos > cc: - self.pos = self.pos - cc - return - if self.pos < cc: - self.d.setfont(self.lastfont) - h = h1 + self.d.textwidth(te[:self.pos]) - else: - h = h2 - ascent, descent = tuple[5:7] - return h, v1, v1+ascent, v2 - # - def _screenposanchor(self, tuple, word, h, v): - pass - # - # Invert the stretch of text between pos1 and pos2. - # If pos1 is None, the beginning is implied; - # if pos2 is None, the end is implied. - # Undoes its own effect when called again with the same arguments - def invert(self, d, pos1, pos2): - if pos1 is None: - pos1 = self.left, self.top, self.top, self.top - else: - pos1 = self.screenpos(d, pos1) - if pos2 is None: - pos2 = self.right, self.bottom,self.bottom,self.bottom - else: - pos2 = self.screenpos(d, pos2) - h1, top1, baseline1, bottom1 = pos1 - h2, top2, baseline2, bottom2 = pos2 - if bottom1 <= top2: - d.invert((h1, top1), (self.right, bottom1)) - h1 = self.left - if bottom1 < top2: - d.invert((h1, bottom1), (self.right, top2)) - top1, bottom1 = top2, bottom2 - d.invert((h1, top1), (h2, bottom2)) + # + def __init__(self): + self.words = [] # The words + self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c' + self.indent_left = self.indent_right = self.indent_hang = 0 + # Final lay-out parameters, may change + self.left = self.top = self.right = self.bottom = \ + self.width = self.height = self.lines = None + # + # Add a word, computing size information for it. + # Words may also be added manually by appending to self.words + # Each word should be a 7-tuple: + # (font, text, width, space, stretch, ascent, descent) + def addword(self, d, font, text, space, stretch): + if font is not None: + d.setfont(font) + width = d.textwidth(text) + ascent = d.baseline() + descent = d.lineheight() - ascent + spw = d.textwidth(' ') + space = space * spw + stretch = stretch * spw + tuple = (font, text, width, space, stretch, ascent, descent) + self.words.append(tuple) + # + # Hooks to begin and end anchors -- insert numbers in the word list! + def bgn_anchor(self, id): + self.words.append(id) + # + def end_anchor(self, id): + self.words.append(0) + # + # Return the total length (width) of the text added so far, in pixels + def getlength(self): + total = 0 + for word in self.words: + if type(word) is not Int: + total = total + word[2] + word[3] + return total + # + # Tab to a given position (relative to the current left indent): + # remove all stretch, add fixed space up to the new indent. + # If the current position is already at the tab stop, + # don't add any new space (but still remove the stretch) + def tabto(self, tab): + total = 0 + as, de = 1, 0 + for i in range(len(self.words)): + word = self.words[i] + if type(word) is Int: continue + (fo, te, wi, sp, st, as, de) = word + self.words[i] = (fo, te, wi, sp, 0, as, de) + total = total + wi + sp + if total < tab: + self.words.append((None, '', 0, tab-total, 0, as, de)) + # + # Make a hanging tag: tab to hang, increment indent_left by hang, + # and reset indent_hang to -hang + def makehangingtag(self, hang): + self.tabto(hang) + self.indent_left = self.indent_left + hang + self.indent_hang = -hang + # + # Decide where the line breaks will be given some screen width + def layout(self, linewidth): + self.width = linewidth + height = 0 + self.lines = lines = [] + avail1 = self.width - self.indent_left - self.indent_right + avail = avail1 - self.indent_hang + words = self.words + i = 0 + n = len(words) + lastfont = None + while i < n: + firstfont = lastfont + charcount = 0 + width = 0 + stretch = 0 + ascent = 0 + descent = 0 + lsp = 0 + j = i + while i < n: + word = words[i] + if type(word) is Int: + if word > 0 and width >= avail: + break + i = i+1 + continue + fo, te, wi, sp, st, as, de = word + if width + wi > avail and width > 0 and wi > 0: + break + if fo is not None: + lastfont = fo + if width == 0: + firstfont = fo + charcount = charcount + len(te) + (sp > 0) + width = width + wi + sp + lsp = sp + stretch = stretch + st + lst = st + ascent = max(ascent, as) + descent = max(descent, de) + i = i+1 + while i > j and type(words[i-1]) is Int and \ + words[i-1] > 0: i = i-1 + width = width - lsp + if i < n: + stretch = stretch - lst + else: + stretch = 0 + tuple = i-j, firstfont, charcount, width, stretch, \ + ascent, descent + lines.append(tuple) + height = height + ascent + descent + avail = avail1 + self.height = height + # + # Call a function for all words in a line + def visit(self, wordfunc, anchorfunc): + avail1 = self.width - self.indent_left - self.indent_right + avail = avail1 - self.indent_hang + v = self.top + i = 0 + for tuple in self.lines: + wordcount, firstfont, charcount, width, stretch, \ + ascent, descent = tuple + h = self.left + self.indent_left + if i == 0: h = h + self.indent_hang + extra = 0 + if self.just == 'r': h = h + avail - width + elif self.just == 'c': h = h + (avail - width) / 2 + elif self.just == 'lr' and stretch > 0: + extra = avail - width + v2 = v + ascent + descent + for j in range(i, i+wordcount): + word = self.words[j] + if type(word) is Int: + ok = anchorfunc(self, tuple, word, \ + h, v) + if ok is not None: return ok + continue + fo, te, wi, sp, st, as, de = word + if extra > 0 and stretch > 0: + ex = extra * st / stretch + extra = extra - ex + stretch = stretch - st + else: + ex = 0 + h2 = h + wi + sp + ex + ok = wordfunc(self, tuple, word, h, v, \ + h2, v2, (j==i), (j==i+wordcount-1)) + if ok is not None: return ok + h = h2 + v = v2 + i = i + wordcount + avail = avail1 + # + # Render a paragraph in "drawing object" d, using the rectangle + # given by (left, top, right) with an unspecified bottom. + # Return the computed bottom of the text. + def render(self, d, left, top, right): + if self.width != right-left: + self.layout(right-left) + self.left = left + self.top = top + self.right = right + self.bottom = self.top + self.height + self.anchorid = 0 + try: + self.d = d + self.visit(self.__class__._renderword, \ + self.__class__._renderanchor) + finally: + self.d = None + return self.bottom + # + def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast): + if word[0] is not None: self.d.setfont(word[0]) + baseline = v + tuple[5] + self.d.text((h, baseline - word[5]), word[1]) + if self.anchorid > 0: + self.d.line((h, baseline+2), (h2, baseline+2)) + # + def _renderanchor(self, tuple, word, h, v): + self.anchorid = word + # + # Return which anchor(s) was hit by the mouse + def hitcheck(self, mouseh, mousev): + self.mouseh = mouseh + self.mousev = mousev + self.anchorid = 0 + self.hits = [] + self.visit(self.__class__._hitcheckword, \ + self.__class__._hitcheckanchor) + return self.hits + # + def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast): + if self.anchorid > 0 and h <= self.mouseh <= h2 and \ + v <= self.mousev <= v2: + self.hits.append(self.anchorid) + # + def _hitcheckanchor(self, tuple, word, h, v): + self.anchorid = word + # + # Return whether the given anchor id is present + def hasanchor(self, id): + return id in self.words or -id in self.words + # + # Extract the raw text from the word list, substituting one space + # for non-empty inter-word space, and terminating with '\n' + def extract(self): + text = '' + for w in self.words: + if type(w) is not Int: + word = w[1] + if w[3]: word = word + ' ' + text = text + word + return text + '\n' + # + # Return which character position was hit by the mouse, as + # an offset in the entire text as returned by extract(). + # Return None if the mouse was not in this paragraph + def whereis(self, d, mouseh, mousev): + if mousev < self.top or mousev > self.bottom: + return None + self.mouseh = mouseh + self.mousev = mousev + self.lastfont = None + self.charcount = 0 + try: + self.d = d + return self.visit(self.__class__._whereisword, \ + self.__class__._whereisanchor) + finally: + self.d = None + # + def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): + fo, te, wi, sp, st, as, de = word + if fo is not None: self.lastfont = fo + h = h1 + if isfirst: h1 = 0 + if islast: h2 = 999999 + if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2): + self.charcount = self.charcount + len(te) + (sp > 0) + return + if self.lastfont is not None: + self.d.setfont(self.lastfont) + cc = 0 + for c in te: + cw = self.d.textwidth(c) + if self.mouseh <= h + cw/2: + return self.charcount + cc + cc = cc+1 + h = h+cw + self.charcount = self.charcount + cc + if self.mouseh <= (h+h2) / 2: + return self.charcount + else: + return self.charcount + 1 + # + def _whereisanchor(self, tuple, word, h, v): + pass + # + # Return screen position corresponding to position in paragraph. + # Return tuple (h, vtop, vbaseline, vbottom). + # This is more or less the inverse of whereis() + def screenpos(self, d, pos): + if pos < 0: + ascent, descent = self.lines[0][5:7] + return self.left, self.top, self.top + ascent, \ + self.top + ascent + descent + self.pos = pos + self.lastfont = None + try: + self.d = d + ok = self.visit(self.__class__._screenposword, \ + self.__class__._screenposanchor) + finally: + self.d = None + if ok is None: + ascent, descent = self.lines[-1][5:7] + ok = self.right, self.bottom - ascent - descent, \ + self.bottom - descent, self.bottom + return ok + # + def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): + fo, te, wi, sp, st, as, de = word + if fo is not None: self.lastfont = fo + cc = len(te) + (sp > 0) + if self.pos > cc: + self.pos = self.pos - cc + return + if self.pos < cc: + self.d.setfont(self.lastfont) + h = h1 + self.d.textwidth(te[:self.pos]) + else: + h = h2 + ascent, descent = tuple[5:7] + return h, v1, v1+ascent, v2 + # + def _screenposanchor(self, tuple, word, h, v): + pass + # + # Invert the stretch of text between pos1 and pos2. + # If pos1 is None, the beginning is implied; + # if pos2 is None, the end is implied. + # Undoes its own effect when called again with the same arguments + def invert(self, d, pos1, pos2): + if pos1 is None: + pos1 = self.left, self.top, self.top, self.top + else: + pos1 = self.screenpos(d, pos1) + if pos2 is None: + pos2 = self.right, self.bottom,self.bottom,self.bottom + else: + pos2 = self.screenpos(d, pos2) + h1, top1, baseline1, bottom1 = pos1 + h2, top2, baseline2, bottom2 = pos2 + if bottom1 <= top2: + d.invert((h1, top1), (self.right, bottom1)) + h1 = self.left + if bottom1 < top2: + d.invert((h1, bottom1), (self.right, top2)) + top1, bottom1 = top2, bottom2 + d.invert((h1, top1), (h2, bottom2)) diff --git a/Lib/lib-old/addpack.py b/Lib/lib-old/addpack.py index 3d09236..2fb2601 100644 --- a/Lib/lib-old/addpack.py +++ b/Lib/lib-old/addpack.py @@ -33,35 +33,35 @@ # # If no directory is found, ImportError is raised. -_packs = {} # {pack: [pathname, ...], ...} +_packs = {} # {pack: [pathname, ...], ...} def addpack(pack, *locations): - import os - if os.path.isabs(pack): - base = os.path.basename(pack) - else: - base = pack - if _packs.has_key(base): - return - import sys - path = [] - for loc in _flatten(locations) + sys.path: - fn = os.path.join(loc, base) - if fn not in path and os.path.isdir(fn): - path.append(fn) - if pack != base and pack not in path and os.path.isdir(pack): - path.append(pack) - if not path: raise ImportError, 'package ' + pack + ' not found' - _packs[base] = path - for fn in path: - if fn not in sys.path: - sys.path.append(fn) + import os + if os.path.isabs(pack): + base = os.path.basename(pack) + else: + base = pack + if _packs.has_key(base): + return + import sys + path = [] + for loc in _flatten(locations) + sys.path: + fn = os.path.join(loc, base) + if fn not in path and os.path.isdir(fn): + path.append(fn) + if pack != base and pack not in path and os.path.isdir(pack): + path.append(pack) + if not path: raise ImportError, 'package ' + pack + ' not found' + _packs[base] = path + for fn in path: + if fn not in sys.path: + sys.path.append(fn) def _flatten(locations): - locs = [] - for loc in locations: - if type(loc) == type(''): - locs.append(loc) - else: - locs = locs + _flatten(loc) - return locs + locs = [] + for loc in locations: + if type(loc) == type(''): + locs.append(loc) + else: + locs = locs + _flatten(loc) + return locs diff --git a/Lib/lib-old/codehack.py b/Lib/lib-old/codehack.py index 248205b..0b5e3a1 100644 --- a/Lib/lib-old/codehack.py +++ b/Lib/lib-old/codehack.py @@ -36,46 +36,46 @@ identchars = string.ascii_letters + string.digits + '_' # Identifier characters _namecache = {} # The cache def getcodename(co): - try: - return co.co_name - except AttributeError: - pass - key = `co` # arbitrary but uniquely identifying string - if _namecache.has_key(key): return _namecache[key] - filename = co.co_filename - code = co.co_code - name = '' - if ord(code[0]) == SET_LINENO: - lineno = ord(code[1]) | ord(code[2]) << 8 - line = linecache.getline(filename, lineno) - words = line.split() - if len(words) >= 2 and words[0] in ('def', 'class'): - name = words[1] - for i in range(len(name)): - if name[i] not in identchars: - name = name[:i] - break - _namecache[key] = name - return name + try: + return co.co_name + except AttributeError: + pass + key = `co` # arbitrary but uniquely identifying string + if _namecache.has_key(key): return _namecache[key] + filename = co.co_filename + code = co.co_code + name = '' + if ord(code[0]) == SET_LINENO: + lineno = ord(code[1]) | ord(code[2]) << 8 + line = linecache.getline(filename, lineno) + words = line.split() + if len(words) >= 2 and words[0] in ('def', 'class'): + name = words[1] + for i in range(len(name)): + if name[i] not in identchars: + name = name[:i] + break + _namecache[key] = name + return name # Use the above routine to find a function's name. def getfuncname(func): - try: - return func.func_name - except AttributeError: - pass - return getcodename(func.func_code) + try: + return func.func_name + except AttributeError: + pass + return getcodename(func.func_code) # A part of the above code to extract just the line number from a code object. def getlineno(co): - try: - return co.co_firstlineno - except AttributeError: - pass - code = co.co_code - if ord(code[0]) == SET_LINENO: - return ord(code[1]) | ord(code[2]) << 8 - else: - return -1 + try: + return co.co_firstlineno + except AttributeError: + pass + code = co.co_code + if ord(code[0]) == SET_LINENO: + return ord(code[1]) | ord(code[2]) << 8 + else: + return -1 diff --git a/Lib/lib-old/dump.py b/Lib/lib-old/dump.py index ec895b7..60bdba8 100644 --- a/Lib/lib-old/dump.py +++ b/Lib/lib-old/dump.py @@ -23,41 +23,41 @@ # Dump a whole symbol table # def dumpsymtab(dict): - for key in dict.keys(): - dumpvar(key, dict[key]) + for key in dict.keys(): + dumpvar(key, dict[key]) # Dump a single variable # def dumpvar(name, x): - import sys - t = type(x) - if t == type({}): - print name, '= {}' - for key in x.keys(): - item = x[key] - if not printable(item): - print '#', - print name, '[', `key`, '] =', `item` - elif t in (type(''), type(0), type(0.0), type([]), type(())): - if not printable(x): - print '#', - print name, '=', `x` - elif t == type(sys): - print 'import', name, '#', x - else: - print '#', name, '=', x + import sys + t = type(x) + if t == type({}): + print name, '= {}' + for key in x.keys(): + item = x[key] + if not printable(item): + print '#', + print name, '[', `key`, '] =', `item` + elif t in (type(''), type(0), type(0.0), type([]), type(())): + if not printable(x): + print '#', + print name, '=', `x` + elif t == type(sys): + print 'import', name, '#', x + else: + print '#', name, '=', x # check if a value is printable in a way that can be read back with input() # def printable(x): - t = type(x) - if t in (type(''), type(0), type(0.0)): - return 1 - if t in (type([]), type(())): - for item in x: - if not printable(item): - return 0 - return 1 - if x == {}: - return 1 - return 0 + t = type(x) + if t in (type(''), type(0), type(0.0)): + return 1 + if t in (type([]), type(())): + for item in x: + if not printable(item): + return 0 + return 1 + if x == {}: + return 1 + return 0 diff --git a/Lib/lib-old/find.py b/Lib/lib-old/find.py index ccd9fdb..39ad771 100644 --- a/Lib/lib-old/find.py +++ b/Lib/lib-old/find.py @@ -6,21 +6,21 @@ _debug = 0 _prune = ['(*)'] def find(pattern, dir = os.curdir): - list = [] - names = os.listdir(dir) - names.sort() - for name in names: - if name in (os.curdir, os.pardir): - continue - fullname = os.path.join(dir, name) - if fnmatch.fnmatch(name, pattern): - list.append(fullname) - if os.path.isdir(fullname) and not os.path.islink(fullname): - for p in _prune: - if fnmatch.fnmatch(name, p): - if _debug: print "skip", `fullname` - break - else: - if _debug: print "descend into", `fullname` - list = list + find(pattern, fullname) - return list + list = [] + names = os.listdir(dir) + names.sort() + for name in names: + if name in (os.curdir, os.pardir): + continue + fullname = os.path.join(dir, name) + if fnmatch.fnmatch(name, pattern): + list.append(fullname) + if os.path.isdir(fullname) and not os.path.islink(fullname): + for p in _prune: + if fnmatch.fnmatch(name, p): + if _debug: print "skip", `fullname` + break + else: + if _debug: print "descend into", `fullname` + list = list + find(pattern, fullname) + return list diff --git a/Lib/lib-old/fmt.py b/Lib/lib-old/fmt.py index dfea987..997d37a 100644 --- a/Lib/lib-old/fmt.py +++ b/Lib/lib-old/fmt.py @@ -12,96 +12,96 @@ import Para # Formatter back-end to do nothing at all with the paragraphs class NullBackEnd: - # - def __init__(self): - pass - # - def addpara(self, p): - pass - # - def bgn_anchor(self, id): - pass - # - def end_anchor(self, id): - pass + # + def __init__(self): + pass + # + def addpara(self, p): + pass + # + def bgn_anchor(self, id): + pass + # + def end_anchor(self, id): + pass # Formatter back-end to collect the paragraphs in a list class SavingBackEnd(NullBackEnd): - # - def __init__(self): - self.paralist = [] - # - def addpara(self, p): - self.paralist.append(p) - # - def hitcheck(self, h, v): - hits = [] - for p in self.paralist: - if p.top <= v <= p.bottom: - for id in p.hitcheck(h, v): - if id not in hits: - hits.append(id) - return hits - # - def extract(self): - text = '' - for p in self.paralist: - text = text + (p.extract()) - return text - # - def extractpart(self, long1, long2): - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - text = '' - while para1 < para2: - ptext = self.paralist[para1].extract() - text = text + ptext[pos1:] - pos1 = 0 - para1 = para1 + 1 - ptext = self.paralist[para2].extract() - return text + ptext[pos1:pos2] - # - def whereis(self, d, h, v): - total = 0 - for i in range(len(self.paralist)): - p = self.paralist[i] - result = p.whereis(d, h, v) - if result is not None: - return i, result - return None - # - def roundtowords(self, long1, long2): - i, offset = long1 - text = self.paralist[i].extract() - while offset > 0 and text[offset-1] != ' ': offset = offset-1 - long1 = i, offset - # - i, offset = long2 - text = self.paralist[i].extract() - n = len(text) - while offset < n-1 and text[offset] != ' ': offset = offset+1 - long2 = i, offset - # - return long1, long2 - # - def roundtoparagraphs(self, long1, long2): - long1 = long1[0], 0 - long2 = long2[0], len(self.paralist[long2[0]].extract()) - return long1, long2 + # + def __init__(self): + self.paralist = [] + # + def addpara(self, p): + self.paralist.append(p) + # + def hitcheck(self, h, v): + hits = [] + for p in self.paralist: + if p.top <= v <= p.bottom: + for id in p.hitcheck(h, v): + if id not in hits: + hits.append(id) + return hits + # + def extract(self): + text = '' + for p in self.paralist: + text = text + (p.extract()) + return text + # + def extractpart(self, long1, long2): + if long1 > long2: long1, long2 = long2, long1 + para1, pos1 = long1 + para2, pos2 = long2 + text = '' + while para1 < para2: + ptext = self.paralist[para1].extract() + text = text + ptext[pos1:] + pos1 = 0 + para1 = para1 + 1 + ptext = self.paralist[para2].extract() + return text + ptext[pos1:pos2] + # + def whereis(self, d, h, v): + total = 0 + for i in range(len(self.paralist)): + p = self.paralist[i] + result = p.whereis(d, h, v) + if result is not None: + return i, result + return None + # + def roundtowords(self, long1, long2): + i, offset = long1 + text = self.paralist[i].extract() + while offset > 0 and text[offset-1] != ' ': offset = offset-1 + long1 = i, offset + # + i, offset = long2 + text = self.paralist[i].extract() + n = len(text) + while offset < n-1 and text[offset] != ' ': offset = offset+1 + long2 = i, offset + # + return long1, long2 + # + def roundtoparagraphs(self, long1, long2): + long1 = long1[0], 0 + long2 = long2[0], len(self.paralist[long2[0]].extract()) + return long1, long2 # Formatter back-end to send the text directly to the drawing object class WritingBackEnd(NullBackEnd): - # - def __init__(self, d, width): - self.d = d - self.width = width - self.lineno = 0 - # - def addpara(self, p): - self.lineno = p.render(self.d, 0, self.lineno, self.width) + # + def __init__(self, d, width): + self.d = d + self.width = width + self.lineno = 0 + # + def addpara(self, p): + self.lineno = p.render(self.d, 0, self.lineno, self.width) # A formatter receives a stream of formatting instructions and assembles @@ -125,192 +125,192 @@ class WritingBackEnd(NullBackEnd): # needvspace(nlines) # addword(word, nspaces) class BaseFormatter: - # - def __init__(self, d, b): - # Drawing object used for text measurements - self.d = d - # - # BackEnd object receiving completed paragraphs - self.b = b - # - # Parameters of the formatting model - self.leftindent = 0 - self.just = 'l' - self.font = None - self.blanklines = 0 - # - # Parameters derived from the current font - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - # Parameter derived from the default font - self.n_space = self.space - # - # Current paragraph being built - self.para = None - self.nospace = 1 - # - # Font to set on the next word - self.nextfont = None - # - def newpara(self): - return Para.Para() - # - def setfont(self, font): - if font is None: return - self.font = self.nextfont = font - d = self.d - d.setfont(font) - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - def setleftindent(self, nspaces): - self.leftindent = int(self.n_space * nspaces) - if self.para: - hang = self.leftindent - self.para.indent_left - if hang > 0 and self.para.getlength() <= hang: - self.para.makehangingtag(hang) - self.nospace = 1 - else: - self.flush() - # - def setrightindent(self, nspaces): - self.rightindent = int(self.n_space * nspaces) - if self.para: - self.para.indent_right = self.rightindent - self.flush() - # - def setjust(self, just): - self.just = just - if self.para: - self.para.just = self.just - # - def flush(self): - if self.para: - self.b.addpara(self.para) - self.para = None - if self.font is not None: - self.d.setfont(self.font) - self.nospace = 1 - # - def vspace(self, nlines): - self.flush() - if nlines > 0: - self.para = self.newpara() - tuple = None, '', 0, 0, 0, int(nlines*self.line), 0 - self.para.words.append(tuple) - self.flush() - self.blanklines = self.blanklines + nlines - # - def needvspace(self, nlines): - self.flush() # Just to be sure - if nlines > self.blanklines: - self.vspace(nlines - self.blanklines) - # - def addword(self, text, space): - if self.nospace and not text: - return - self.nospace = 0 - self.blanklines = 0 - if not self.para: - self.para = self.newpara() - self.para.indent_left = self.leftindent - self.para.just = self.just - self.nextfont = self.font - space = int(space * self.space) - self.para.words.append((self.nextfont, text, - self.d.textwidth(text), space, space, - self.ascent, self.descent)) - self.nextfont = None - # - def bgn_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.bgn_anchor(id) - # - def end_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.end_anchor(id) + # + def __init__(self, d, b): + # Drawing object used for text measurements + self.d = d + # + # BackEnd object receiving completed paragraphs + self.b = b + # + # Parameters of the formatting model + self.leftindent = 0 + self.just = 'l' + self.font = None + self.blanklines = 0 + # + # Parameters derived from the current font + self.space = d.textwidth(' ') + self.line = d.lineheight() + self.ascent = d.baseline() + self.descent = self.line - self.ascent + # + # Parameter derived from the default font + self.n_space = self.space + # + # Current paragraph being built + self.para = None + self.nospace = 1 + # + # Font to set on the next word + self.nextfont = None + # + def newpara(self): + return Para.Para() + # + def setfont(self, font): + if font is None: return + self.font = self.nextfont = font + d = self.d + d.setfont(font) + self.space = d.textwidth(' ') + self.line = d.lineheight() + self.ascent = d.baseline() + self.descent = self.line - self.ascent + # + def setleftindent(self, nspaces): + self.leftindent = int(self.n_space * nspaces) + if self.para: + hang = self.leftindent - self.para.indent_left + if hang > 0 and self.para.getlength() <= hang: + self.para.makehangingtag(hang) + self.nospace = 1 + else: + self.flush() + # + def setrightindent(self, nspaces): + self.rightindent = int(self.n_space * nspaces) + if self.para: + self.para.indent_right = self.rightindent + self.flush() + # + def setjust(self, just): + self.just = just + if self.para: + self.para.just = self.just + # + def flush(self): + if self.para: + self.b.addpara(self.para) + self.para = None + if self.font is not None: + self.d.setfont(self.font) + self.nospace = 1 + # + def vspace(self, nlines): + self.flush() + if nlines > 0: + self.para = self.newpara() + tuple = None, '', 0, 0, 0, int(nlines*self.line), 0 + self.para.words.append(tuple) + self.flush() + self.blanklines = self.blanklines + nlines + # + def needvspace(self, nlines): + self.flush() # Just to be sure + if nlines > self.blanklines: + self.vspace(nlines - self.blanklines) + # + def addword(self, text, space): + if self.nospace and not text: + return + self.nospace = 0 + self.blanklines = 0 + if not self.para: + self.para = self.newpara() + self.para.indent_left = self.leftindent + self.para.just = self.just + self.nextfont = self.font + space = int(space * self.space) + self.para.words.append((self.nextfont, text, + self.d.textwidth(text), space, space, + self.ascent, self.descent)) + self.nextfont = None + # + def bgn_anchor(self, id): + if not self.para: + self.nospace = 0 + self.addword('', 0) + self.para.bgn_anchor(id) + # + def end_anchor(self, id): + if not self.para: + self.nospace = 0 + self.addword('', 0) + self.para.end_anchor(id) # Measuring object for measuring text as viewed on a tty class NullMeasurer: - # - def __init__(self): - pass - # - def setfont(self, font): - pass - # - def textwidth(self, text): - return len(text) - # - def lineheight(self): - return 1 - # - def baseline(self): - return 0 + # + def __init__(self): + pass + # + def setfont(self, font): + pass + # + def textwidth(self, text): + return len(text) + # + def lineheight(self): + return 1 + # + def baseline(self): + return 0 # Drawing object for writing plain ASCII text to a file class FileWriter: - # - def __init__(self, fp): - self.fp = fp - self.lineno, self.colno = 0, 0 - # - def setfont(self, font): - pass - # - def text(self, (h, v), str): - if not str: return - if '\n' in str: - raise ValueError, 'can\'t write \\n' - while self.lineno < v: - self.fp.write('\n') - self.colno, self.lineno = 0, self.lineno + 1 - while self.lineno > v: - # XXX This should never happen... - self.fp.write('\033[A') # ANSI up arrow - self.lineno = self.lineno - 1 - if self.colno < h: - self.fp.write(' ' * (h - self.colno)) - elif self.colno > h: - self.fp.write('\b' * (self.colno - h)) - self.colno = h - self.fp.write(str) - self.colno = h + len(str) + # + def __init__(self, fp): + self.fp = fp + self.lineno, self.colno = 0, 0 + # + def setfont(self, font): + pass + # + def text(self, (h, v), str): + if not str: return + if '\n' in str: + raise ValueError, 'can\'t write \\n' + while self.lineno < v: + self.fp.write('\n') + self.colno, self.lineno = 0, self.lineno + 1 + while self.lineno > v: + # XXX This should never happen... + self.fp.write('\033[A') # ANSI up arrow + self.lineno = self.lineno - 1 + if self.colno < h: + self.fp.write(' ' * (h - self.colno)) + elif self.colno > h: + self.fp.write('\b' * (self.colno - h)) + self.colno = h + self.fp.write(str) + self.colno = h + len(str) # Formatting class to do nothing at all with the data class NullFormatter(BaseFormatter): - # - def __init__(self): - d = NullMeasurer() - b = NullBackEnd() - BaseFormatter.__init__(self, d, b) + # + def __init__(self): + d = NullMeasurer() + b = NullBackEnd() + BaseFormatter.__init__(self, d, b) # Formatting class to write directly to a file class WritingFormatter(BaseFormatter): - # - def __init__(self, fp, width): - dm = NullMeasurer() - dw = FileWriter(fp) - b = WritingBackEnd(dw, width) - BaseFormatter.__init__(self, dm, b) - self.blanklines = 1 - # - # Suppress multiple blank lines - def needvspace(self, nlines): - BaseFormatter.needvspace(self, min(1, nlines)) + # + def __init__(self, fp, width): + dm = NullMeasurer() + dw = FileWriter(fp) + b = WritingBackEnd(dw, width) + BaseFormatter.__init__(self, dm, b) + self.blanklines = 1 + # + # Suppress multiple blank lines + def needvspace(self, nlines): + BaseFormatter.needvspace(self, min(1, nlines)) # A "FunnyFormatter" writes ASCII text with a twist: *bold words*, @@ -320,10 +320,10 @@ class WritingFormatter(BaseFormatter): # Moreover, if the font is in upper case, the text is converted to # UPPER CASE. class FunnyFormatter(WritingFormatter): - # - def flush(self): - if self.para: finalize(self.para) - WritingFormatter.flush(self) + # + def flush(self): + if self.para: finalize(self.para) + WritingFormatter.flush(self) # Surrounds *bold words* and _italic text_ in a paragraph with @@ -334,33 +334,33 @@ openchar = \ closechar = \ {'b':'*', 'i':'_', 'u':'_', 'q':'\'', 'B':'*', 'I':'_', 'U':'_', 'Q':'\''} def finalize(para): - oldfont = curfont = 'r' - para.words.append(('r', '', 0, 0, 0, 0)) # temporary, deleted at end - for i in range(len(para.words)): - fo, te, wi = para.words[i][:3] - if fo is not None: curfont = fo - if curfont != oldfont: - if closechar.has_key(oldfont): - c = closechar[oldfont] - j = i-1 - while j > 0 and para.words[j][1] == '': j = j-1 - fo1, te1, wi1 = para.words[j][:3] - te1 = te1 + c - wi1 = wi1 + len(c) - para.words[j] = (fo1, te1, wi1) + \ - para.words[j][3:] - if openchar.has_key(curfont) and te: - c = openchar[curfont] - te = c + te - wi = len(c) + wi - para.words[i] = (fo, te, wi) + \ - para.words[i][3:] - if te: oldfont = curfont - else: oldfont = 'r' - if curfont in string.uppercase: - te = string.upper(te) - para.words[i] = (fo, te, wi) + para.words[i][3:] - del para.words[-1] + oldfont = curfont = 'r' + para.words.append(('r', '', 0, 0, 0, 0)) # temporary, deleted at end + for i in range(len(para.words)): + fo, te, wi = para.words[i][:3] + if fo is not None: curfont = fo + if curfont != oldfont: + if closechar.has_key(oldfont): + c = closechar[oldfont] + j = i-1 + while j > 0 and para.words[j][1] == '': j = j-1 + fo1, te1, wi1 = para.words[j][:3] + te1 = te1 + c + wi1 = wi1 + len(c) + para.words[j] = (fo1, te1, wi1) + \ + para.words[j][3:] + if openchar.has_key(curfont) and te: + c = openchar[curfont] + te = c + te + wi = len(c) + wi + para.words[i] = (fo, te, wi) + \ + para.words[i][3:] + if te: oldfont = curfont + else: oldfont = 'r' + if curfont in string.uppercase: + te = string.upper(te) + para.words[i] = (fo, te, wi) + para.words[i][3:] + del para.words[-1] # Formatter back-end to draw the text in a window. @@ -368,256 +368,256 @@ def finalize(para): # to minimize the delay before the user sees anything. # This manages the entire "document" of the window. class StdwinBackEnd(SavingBackEnd): - # - def __init__(self, window, drawnow): - self.window = window - self.drawnow = drawnow - self.width = window.getwinsize()[0] - self.selection = None - self.height = 0 - window.setorigin(0, 0) - window.setdocsize(0, 0) - self.d = window.begindrawing() - SavingBackEnd.__init__(self) - # - def finish(self): - self.d.close() - self.d = None - self.window.setdocsize(0, self.height) - # - def addpara(self, p): - self.paralist.append(p) - if self.drawnow: - self.height = \ - p.render(self.d, 0, self.height, self.width) - else: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - # - def resize(self): - self.window.change((0, 0), (self.width, self.height)) - self.width = self.window.getwinsize()[0] - self.height = 0 - for p in self.paralist: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - self.window.change((0, 0), (self.width, self.height)) - self.window.setdocsize(0, self.height) - # - def redraw(self, area): - d = self.window.begindrawing() - (left, top), (right, bottom) = area - d.erase(area) - d.cliprect(area) - for p in self.paralist: - if top < p.bottom and p.top < bottom: - v = p.render(d, p.left, p.top, p.right) - if self.selection: - self.invert(d, self.selection) - d.close() - # - def setselection(self, new): - if new: - long1, long2 = new - pos1 = long1[:3] - pos2 = long2[:3] - new = pos1, pos2 - if new != self.selection: - d = self.window.begindrawing() - if self.selection: - self.invert(d, self.selection) - if new: - self.invert(d, new) - d.close() - self.selection = new - # - def getselection(self): - return self.selection - # - def extractselection(self): - if self.selection: - a, b = self.selection - return self.extractpart(a, b) - else: - return None - # - def invert(self, d, region): - long1, long2 = region - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - while para1 < para2: - self.paralist[para1].invert(d, pos1, None) - pos1 = None - para1 = para1 + 1 - self.paralist[para2].invert(d, pos1, pos2) - # - def search(self, prog): - import re, string - if type(prog) is type(''): - prog = re.compile(string.lower(prog)) - if self.selection: - iold = self.selection[0][0] - else: - iold = -1 - hit = None - for i in range(len(self.paralist)): - if i == iold or i < iold and hit: - continue - p = self.paralist[i] - text = string.lower(p.extract()) - match = prog.search(text) - if match: - a, b = match.group(0) - long1 = i, a - long2 = i, b - hit = long1, long2 - if i > iold: - break - if hit: - self.setselection(hit) - i = hit[0][0] - p = self.paralist[i] - self.window.show((p.left, p.top), (p.right, p.bottom)) - return 1 - else: - return 0 - # - def showanchor(self, id): - for i in range(len(self.paralist)): - p = self.paralist[i] - if p.hasanchor(id): - long1 = i, 0 - long2 = i, len(p.extract()) - hit = long1, long2 - self.setselection(hit) - self.window.show( - (p.left, p.top), (p.right, p.bottom)) - break + # + def __init__(self, window, drawnow): + self.window = window + self.drawnow = drawnow + self.width = window.getwinsize()[0] + self.selection = None + self.height = 0 + window.setorigin(0, 0) + window.setdocsize(0, 0) + self.d = window.begindrawing() + SavingBackEnd.__init__(self) + # + def finish(self): + self.d.close() + self.d = None + self.window.setdocsize(0, self.height) + # + def addpara(self, p): + self.paralist.append(p) + if self.drawnow: + self.height = \ + p.render(self.d, 0, self.height, self.width) + else: + p.layout(self.width) + p.left = 0 + p.top = self.height + p.right = self.width + p.bottom = self.height + p.height + self.height = p.bottom + # + def resize(self): + self.window.change((0, 0), (self.width, self.height)) + self.width = self.window.getwinsize()[0] + self.height = 0 + for p in self.paralist: + p.layout(self.width) + p.left = 0 + p.top = self.height + p.right = self.width + p.bottom = self.height + p.height + self.height = p.bottom + self.window.change((0, 0), (self.width, self.height)) + self.window.setdocsize(0, self.height) + # + def redraw(self, area): + d = self.window.begindrawing() + (left, top), (right, bottom) = area + d.erase(area) + d.cliprect(area) + for p in self.paralist: + if top < p.bottom and p.top < bottom: + v = p.render(d, p.left, p.top, p.right) + if self.selection: + self.invert(d, self.selection) + d.close() + # + def setselection(self, new): + if new: + long1, long2 = new + pos1 = long1[:3] + pos2 = long2[:3] + new = pos1, pos2 + if new != self.selection: + d = self.window.begindrawing() + if self.selection: + self.invert(d, self.selection) + if new: + self.invert(d, new) + d.close() + self.selection = new + # + def getselection(self): + return self.selection + # + def extractselection(self): + if self.selection: + a, b = self.selection + return self.extractpart(a, b) + else: + return None + # + def invert(self, d, region): + long1, long2 = region + if long1 > long2: long1, long2 = long2, long1 + para1, pos1 = long1 + para2, pos2 = long2 + while para1 < para2: + self.paralist[para1].invert(d, pos1, None) + pos1 = None + para1 = para1 + 1 + self.paralist[para2].invert(d, pos1, pos2) + # + def search(self, prog): + import re, string + if type(prog) is type(''): + prog = re.compile(string.lower(prog)) + if self.selection: + iold = self.selection[0][0] + else: + iold = -1 + hit = None + for i in range(len(self.paralist)): + if i == iold or i < iold and hit: + continue + p = self.paralist[i] + text = string.lower(p.extract()) + match = prog.search(text) + if match: + a, b = match.group(0) + long1 = i, a + long2 = i, b + hit = long1, long2 + if i > iold: + break + if hit: + self.setselection(hit) + i = hit[0][0] + p = self.paralist[i] + self.window.show((p.left, p.top), (p.right, p.bottom)) + return 1 + else: + return 0 + # + def showanchor(self, id): + for i in range(len(self.paralist)): + p = self.paralist[i] + if p.hasanchor(id): + long1 = i, 0 + long2 = i, len(p.extract()) + hit = long1, long2 + self.setselection(hit) + self.window.show( + (p.left, p.top), (p.right, p.bottom)) + break # GL extensions class GLFontCache: - # - def __init__(self): - self.reset() - self.setfont('') - # - def reset(self): - self.fontkey = None - self.fonthandle = None - self.fontinfo = None - self.fontcache = {} - # - def close(self): - self.reset() - # - def setfont(self, fontkey): - if fontkey == '': - fontkey = 'Times-Roman 12' - elif ' ' not in fontkey: - fontkey = fontkey + ' 12' - if fontkey == self.fontkey: - return - if self.fontcache.has_key(fontkey): - handle = self.fontcache[fontkey] - else: - import string - i = string.index(fontkey, ' ') - name, sizestr = fontkey[:i], fontkey[i:] - size = eval(sizestr) - key1 = name + ' 1' - key = name + ' ' + `size` - # NB key may differ from fontkey! - if self.fontcache.has_key(key): - handle = self.fontcache[key] - else: - if self.fontcache.has_key(key1): - handle = self.fontcache[key1] - else: - import fm - handle = fm.findfont(name) - self.fontcache[key1] = handle - handle = handle.scalefont(size) - self.fontcache[fontkey] = \ - self.fontcache[key] = handle - self.fontkey = fontkey - if self.fonthandle != handle: - self.fonthandle = handle - self.fontinfo = handle.getfontinfo() - handle.setfont() + # + def __init__(self): + self.reset() + self.setfont('') + # + def reset(self): + self.fontkey = None + self.fonthandle = None + self.fontinfo = None + self.fontcache = {} + # + def close(self): + self.reset() + # + def setfont(self, fontkey): + if fontkey == '': + fontkey = 'Times-Roman 12' + elif ' ' not in fontkey: + fontkey = fontkey + ' 12' + if fontkey == self.fontkey: + return + if self.fontcache.has_key(fontkey): + handle = self.fontcache[fontkey] + else: + import string + i = string.index(fontkey, ' ') + name, sizestr = fontkey[:i], fontkey[i:] + size = eval(sizestr) + key1 = name + ' 1' + key = name + ' ' + `size` + # NB key may differ from fontkey! + if self.fontcache.has_key(key): + handle = self.fontcache[key] + else: + if self.fontcache.has_key(key1): + handle = self.fontcache[key1] + else: + import fm + handle = fm.findfont(name) + self.fontcache[key1] = handle + handle = handle.scalefont(size) + self.fontcache[fontkey] = \ + self.fontcache[key] = handle + self.fontkey = fontkey + if self.fonthandle != handle: + self.fonthandle = handle + self.fontinfo = handle.getfontinfo() + handle.setfont() class GLMeasurer(GLFontCache): - # - def textwidth(self, text): - return self.fonthandle.getstrwidth(text) - # - def baseline(self): - return self.fontinfo[6] - self.fontinfo[3] - # - def lineheight(self): - return self.fontinfo[6] + # + def textwidth(self, text): + return self.fonthandle.getstrwidth(text) + # + def baseline(self): + return self.fontinfo[6] - self.fontinfo[3] + # + def lineheight(self): + return self.fontinfo[6] class GLWriter(GLFontCache): - # - # NOTES: - # (1) Use gl.ortho2 to use X pixel coordinates! - # - def text(self, (h, v), text): - import gl, fm - gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3]) - fm.prstr(text) - # - def setfont(self, fontkey): - oldhandle = self.fonthandle - GLFontCache.setfont(fontkey) - if self.fonthandle != oldhandle: - handle.setfont() + # + # NOTES: + # (1) Use gl.ortho2 to use X pixel coordinates! + # + def text(self, (h, v), text): + import gl, fm + gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3]) + fm.prstr(text) + # + def setfont(self, fontkey): + oldhandle = self.fonthandle + GLFontCache.setfont(fontkey) + if self.fonthandle != oldhandle: + handle.setfont() class GLMeasurerWriter(GLMeasurer, GLWriter): - pass + pass class GLBackEnd(SavingBackEnd): - # - def __init__(self, wid): - import gl - gl.winset(wid) - self.wid = wid - self.width = gl.getsize()[1] - self.height = 0 - self.d = GLMeasurerWriter() - SavingBackEnd.__init__(self) - # - def finish(self): - pass - # - def addpara(self, p): - self.paralist.append(p) - self.height = p.render(self.d, 0, self.height, self.width) - # - def redraw(self): - import gl - gl.winset(self.wid) - width = gl.getsize()[1] - if width != self.width: - setdocsize = 1 - self.width = width - for p in self.paralist: - p.top = p.bottom = None - d = self.d - v = 0 - for p in self.paralist: - v = p.render(d, 0, v, width) + # + def __init__(self, wid): + import gl + gl.winset(wid) + self.wid = wid + self.width = gl.getsize()[1] + self.height = 0 + self.d = GLMeasurerWriter() + SavingBackEnd.__init__(self) + # + def finish(self): + pass + # + def addpara(self, p): + self.paralist.append(p) + self.height = p.render(self.d, 0, self.height, self.width) + # + def redraw(self): + import gl + gl.winset(self.wid) + width = gl.getsize()[1] + if width != self.width: + setdocsize = 1 + self.width = width + for p in self.paralist: + p.top = p.bottom = None + d = self.d + v = 0 + for p in self.paralist: + v = p.render(d, 0, v, width) diff --git a/Lib/lib-old/grep.py b/Lib/lib-old/grep.py index bdefbe6..2926746 100644 --- a/Lib/lib-old/grep.py +++ b/Lib/lib-old/grep.py @@ -8,72 +8,72 @@ opt_show_filename = 0 opt_show_lineno = 1 def grep(pat, *files): - return ggrep(RE_SYNTAX_GREP, pat, files) + return ggrep(RE_SYNTAX_GREP, pat, files) def egrep(pat, *files): - return ggrep(RE_SYNTAX_EGREP, pat, files) + return ggrep(RE_SYNTAX_EGREP, pat, files) def emgrep(pat, *files): - return ggrep(RE_SYNTAX_EMACS, pat, files) + return ggrep(RE_SYNTAX_EMACS, pat, files) def ggrep(syntax, pat, files): - if len(files) == 1 and type(files[0]) == type([]): - files = files[0] - global opt_show_filename - opt_show_filename = (len(files) != 1) - syntax = regex.set_syntax(syntax) - try: - prog = regex.compile(pat) - finally: - syntax = regex.set_syntax(syntax) - for filename in files: - fp = open(filename, 'r') - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno + 1 - if prog.search(line) >= 0: - showline(filename, lineno, line, prog) - fp.close() + if len(files) == 1 and type(files[0]) == type([]): + files = files[0] + global opt_show_filename + opt_show_filename = (len(files) != 1) + syntax = regex.set_syntax(syntax) + try: + prog = regex.compile(pat) + finally: + syntax = regex.set_syntax(syntax) + for filename in files: + fp = open(filename, 'r') + lineno = 0 + while 1: + line = fp.readline() + if not line: break + lineno = lineno + 1 + if prog.search(line) >= 0: + showline(filename, lineno, line, prog) + fp.close() def pgrep(pat, *files): - if len(files) == 1 and type(files[0]) == type([]): - files = files[0] - global opt_show_filename - opt_show_filename = (len(files) != 1) - import re - prog = re.compile(pat) - for filename in files: - fp = open(filename, 'r') - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno + 1 - if prog.search(line): - showline(filename, lineno, line, prog) - fp.close() + if len(files) == 1 and type(files[0]) == type([]): + files = files[0] + global opt_show_filename + opt_show_filename = (len(files) != 1) + import re + prog = re.compile(pat) + for filename in files: + fp = open(filename, 'r') + lineno = 0 + while 1: + line = fp.readline() + if not line: break + lineno = lineno + 1 + if prog.search(line): + showline(filename, lineno, line, prog) + fp.close() def showline(filename, lineno, line, prog): - if line[-1:] == '\n': line = line[:-1] - if opt_show_lineno: - prefix = `lineno`.rjust(3) + ': ' - else: - prefix = '' - if opt_show_filename: - prefix = filename + ': ' + prefix - print prefix + line - if opt_show_where: - start, end = prog.regs()[0] - line = line[:start] - if '\t' not in line: - prefix = ' ' * (len(prefix) + start) - else: - prefix = ' ' * len(prefix) - for c in line: - if c != '\t': c = ' ' - prefix = prefix + c - if start == end: prefix = prefix + '\\' - else: prefix = prefix + '^'*(end-start) - print prefix + if line[-1:] == '\n': line = line[:-1] + if opt_show_lineno: + prefix = `lineno`.rjust(3) + ': ' + else: + prefix = '' + if opt_show_filename: + prefix = filename + ': ' + prefix + print prefix + line + if opt_show_where: + start, end = prog.regs()[0] + line = line[:start] + if '\t' not in line: + prefix = ' ' * (len(prefix) + start) + else: + prefix = ' ' * len(prefix) + for c in line: + if c != '\t': c = ' ' + prefix = prefix + c + if start == end: prefix = prefix + '\\' + else: prefix = prefix + '^'*(end-start) + print prefix diff --git a/Lib/lib-old/lockfile.py b/Lib/lib-old/lockfile.py index 3aaeac0..cde9b48 100644 --- a/Lib/lib-old/lockfile.py +++ b/Lib/lib-old/lockfile.py @@ -1,15 +1,15 @@ import struct, fcntl def writelock(f): - _lock(f, fcntl.F_WRLCK) + _lock(f, fcntl.F_WRLCK) def readlock(f): - _lock(f, fcntl.F_RDLCK) + _lock(f, fcntl.F_RDLCK) def unlock(f): - _lock(f, fcntl.F_UNLCK) + _lock(f, fcntl.F_UNLCK) def _lock(f, op): - dummy = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, - struct.pack('2h8l', op, - 0, 0, 0, 0, 0, 0, 0, 0, 0)) + dummy = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, + struct.pack('2h8l', op, + 0, 0, 0, 0, 0, 0, 0, 0, 0)) diff --git a/Lib/lib-old/newdir.py b/Lib/lib-old/newdir.py index 937c49e..356becc 100644 --- a/Lib/lib-old/newdir.py +++ b/Lib/lib-old/newdir.py @@ -5,69 +5,69 @@ # the current local name space by default def listattrs(x): - try: - dictkeys = x.__dict__.keys() - except (AttributeError, TypeError): - dictkeys = [] - # - try: - methods = x.__methods__ - except (AttributeError, TypeError): - methods = [] - # - try: - members = x.__members__ - except (AttributeError, TypeError): - members = [] - # - try: - the_class = x.__class__ - except (AttributeError, TypeError): - the_class = None - # - try: - bases = x.__bases__ - except (AttributeError, TypeError): - bases = () - # - total = dictkeys + methods + members - if the_class: - # It's a class instace; add the class's attributes - # that are functions (methods)... - class_attrs = listattrs(the_class) - class_methods = [] - for name in class_attrs: - if is_function(getattr(the_class, name)): - class_methods.append(name) - total = total + class_methods - elif bases: - # It's a derived class; add the base class attributes - for base in bases: - base_attrs = listattrs(base) - total = total + base_attrs - total.sort() - return total - i = 0 - while i+1 < len(total): - if total[i] == total[i+1]: - del total[i+1] - else: - i = i+1 - return total + try: + dictkeys = x.__dict__.keys() + except (AttributeError, TypeError): + dictkeys = [] + # + try: + methods = x.__methods__ + except (AttributeError, TypeError): + methods = [] + # + try: + members = x.__members__ + except (AttributeError, TypeError): + members = [] + # + try: + the_class = x.__class__ + except (AttributeError, TypeError): + the_class = None + # + try: + bases = x.__bases__ + except (AttributeError, TypeError): + bases = () + # + total = dictkeys + methods + members + if the_class: + # It's a class instace; add the class's attributes + # that are functions (methods)... + class_attrs = listattrs(the_class) + class_methods = [] + for name in class_attrs: + if is_function(getattr(the_class, name)): + class_methods.append(name) + total = total + class_methods + elif bases: + # It's a derived class; add the base class attributes + for base in bases: + base_attrs = listattrs(base) + total = total + base_attrs + total.sort() + return total + i = 0 + while i+1 < len(total): + if total[i] == total[i+1]: + del total[i+1] + else: + i = i+1 + return total # Helper to recognize functions def is_function(x): - return type(x) == type(is_function) + return type(x) == type(is_function) # Approximation of builtin dir(); but note that this lists the user's # variables by default, not the current local name space. def dir(x = None): - if x is not None: - return listattrs(x) - else: - import __main__ - return listattrs(__main__) + if x is not None: + return listattrs(x) + else: + import __main__ + return listattrs(__main__) diff --git a/Lib/lib-old/packmail.py b/Lib/lib-old/packmail.py index 9c2b566..e569108 100644 --- a/Lib/lib-old/packmail.py +++ b/Lib/lib-old/packmail.py @@ -8,104 +8,104 @@ from stat import ST_MTIME # Print help def help(): - print 'All fns have a file open for writing as first parameter' - print 'pack(f, fullname, name): pack fullname as name' - print 'packsome(f, directory, namelist): selected files from directory' - print 'packall(f, directory): pack all files from directory' - print 'packnotolder(f, directory, name): pack all files from directory' - print ' that are not older than a file there' - print 'packtree(f, directory): pack entire directory tree' + print 'All fns have a file open for writing as first parameter' + print 'pack(f, fullname, name): pack fullname as name' + print 'packsome(f, directory, namelist): selected files from directory' + print 'packall(f, directory): pack all files from directory' + print 'packnotolder(f, directory, name): pack all files from directory' + print ' that are not older than a file there' + print 'packtree(f, directory): pack entire directory tree' # Pack one file def pack(outfp, file, name): - fp = open(file, 'r') - outfp.write('echo ' + name + '\n') - outfp.write('sed "s/^X//" >"' + name + '" <<"!"\n') - while 1: - line = fp.readline() - if not line: break - if line[-1:] != '\n': - line = line + '\n' - outfp.write('X' + line) - outfp.write('!\n') - fp.close() + fp = open(file, 'r') + outfp.write('echo ' + name + '\n') + outfp.write('sed "s/^X//" >"' + name + '" <<"!"\n') + while 1: + line = fp.readline() + if not line: break + if line[-1:] != '\n': + line = line + '\n' + outfp.write('X' + line) + outfp.write('!\n') + fp.close() # Pack some files from a directory def packsome(outfp, dirname, names): - for name in names: - print name - file = os.path.join(dirname, name) - pack(outfp, file, name) + for name in names: + print name + file = os.path.join(dirname, name) + pack(outfp, file, name) # Pack all files from a directory def packall(outfp, dirname): - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - names.sort() - packsome(outfp, dirname, names) + names = os.listdir(dirname) + try: + names.remove('.') + except: + pass + try: + names.remove('..') + except: + pass + names.sort() + packsome(outfp, dirname, names) # Pack all files from a directory that are not older than a give one def packnotolder(outfp, dirname, oldest): - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - oldest = os.path.join(dirname, oldest) - st = os.stat(oldest) - mtime = st[ST_MTIME] - todo = [] - for name in names: - print name, '...', - st = os.stat(os.path.join(dirname, name)) - if st[ST_MTIME] >= mtime: - print 'Yes.' - todo.append(name) - else: - print 'No.' - todo.sort() - packsome(outfp, dirname, todo) + names = os.listdir(dirname) + try: + names.remove('.') + except: + pass + try: + names.remove('..') + except: + pass + oldest = os.path.join(dirname, oldest) + st = os.stat(oldest) + mtime = st[ST_MTIME] + todo = [] + for name in names: + print name, '...', + st = os.stat(os.path.join(dirname, name)) + if st[ST_MTIME] >= mtime: + print 'Yes.' + todo.append(name) + else: + print 'No.' + todo.sort() + packsome(outfp, dirname, todo) # Pack a whole tree (no exceptions) def packtree(outfp, dirname): - print 'packtree', dirname - outfp.write('mkdir ' + unixfix(dirname) + '\n') - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - subdirs = [] - for name in names: - fullname = os.path.join(dirname, name) - if os.path.isdir(fullname): - subdirs.append(fullname) - else: - print 'pack', fullname - pack(outfp, fullname, unixfix(fullname)) - for subdirname in subdirs: - packtree(outfp, subdirname) + print 'packtree', dirname + outfp.write('mkdir ' + unixfix(dirname) + '\n') + names = os.listdir(dirname) + try: + names.remove('.') + except: + pass + try: + names.remove('..') + except: + pass + subdirs = [] + for name in names: + fullname = os.path.join(dirname, name) + if os.path.isdir(fullname): + subdirs.append(fullname) + else: + print 'pack', fullname + pack(outfp, fullname, unixfix(fullname)) + for subdirname in subdirs: + packtree(outfp, subdirname) def unixfix(name): - comps = name.split(os.sep) - res = '' - for comp in comps: - if comp: - if res: res = res + '/' - res = res + comp - return res + comps = name.split(os.sep) + res = '' + for comp in comps: + if comp: + if res: res = res + '/' + res = res + comp + return res diff --git a/Lib/lib-old/poly.py b/Lib/lib-old/poly.py index f89bd14..fe6a1dc 100644 --- a/Lib/lib-old/poly.py +++ b/Lib/lib-old/poly.py @@ -6,47 +6,47 @@ # taken out by normalize(). def normalize(p): # Strip unnecessary zero coefficients - n = len(p) - while n: - if p[n-1]: return p[:n] - n = n-1 - return [] + n = len(p) + while n: + if p[n-1]: return p[:n] + n = n-1 + return [] def plus(a, b): - if len(a) < len(b): a, b = b, a # make sure a is the longest - res = a[:] # make a copy - for i in range(len(b)): - res[i] = res[i] + b[i] - return normalize(res) + if len(a) < len(b): a, b = b, a # make sure a is the longest + res = a[:] # make a copy + for i in range(len(b)): + res[i] = res[i] + b[i] + return normalize(res) def minus(a, b): - neg_b = map(lambda x: -x, b[:]) - return plus(a, neg_b) + neg_b = map(lambda x: -x, b[:]) + return plus(a, neg_b) def one(power, coeff): # Representation of coeff * x**power - res = [] - for i in range(power): res.append(0) - return res + [coeff] + res = [] + for i in range(power): res.append(0) + return res + [coeff] def times(a, b): - res = [] - for i in range(len(a)): - for j in range(len(b)): - res = plus(res, one(i+j, a[i]*b[j])) - return res + res = [] + for i in range(len(a)): + for j in range(len(b)): + res = plus(res, one(i+j, a[i]*b[j])) + return res def power(a, n): # Raise polynomial a to the positive integral power n - if n == 0: return [1] - if n == 1: return a - if n/2*2 == n: - b = power(a, n/2) - return times(b, b) - return times(power(a, n-1), a) + if n == 0: return [1] + if n == 1: return a + if n/2*2 == n: + b = power(a, n/2) + return times(b, b) + return times(power(a, n-1), a) def der(a): # First derivative - res = a[1:] - for i in range(len(res)): - res[i] = res[i] * (i+1) - return res + res = a[1:] + for i in range(len(res)): + res[i] = res[i] * (i+1) + return res # Computing a primitive function would require rational arithmetic... diff --git a/Lib/lib-old/rand.py b/Lib/lib-old/rand.py index c299d0a..a557b69 100644 --- a/Lib/lib-old/rand.py +++ b/Lib/lib-old/rand.py @@ -4,10 +4,10 @@ import whrandom def srand(seed): - whrandom.seed(seed%256, seed/256%256, seed/65536%256) + whrandom.seed(seed%256, seed/256%256, seed/65536%256) def rand(): - return int(whrandom.random() * 32768.0) % 32768 + return int(whrandom.random() * 32768.0) % 32768 def choice(seq): - return seq[rand() % len(seq)] + return seq[rand() % len(seq)] diff --git a/Lib/lib-old/tb.py b/Lib/lib-old/tb.py index 57851aa..9063559 100644 --- a/Lib/lib-old/tb.py +++ b/Lib/lib-old/tb.py @@ -12,166 +12,166 @@ def br(): browser(sys.last_traceback) def tb(): printtb(sys.last_traceback) def browser(tb): - if not tb: - print 'No traceback.' - return - tblist = [] - while tb: - tblist.append(tb) - tb = tb.tb_next - ptr = len(tblist)-1 - tb = tblist[ptr] - while 1: - if tb != tblist[ptr]: - tb = tblist[ptr] - print `ptr` + ':', - printtbheader(tb) - try: - line = raw_input('TB: ') - except KeyboardInterrupt: - print '\n[Interrupted]' - break - except EOFError: - print '\n[EOF]' - break - cmd = line.strip() - if cmd: - if cmd == 'quit': - break - elif cmd == 'list': - browserlist(tb) - elif cmd == 'up': - if ptr-1 >= 0: ptr = ptr-1 - else: print 'Bottom of stack.' - elif cmd == 'down': - if ptr+1 < len(tblist): ptr = ptr+1 - else: print 'Top of stack.' - elif cmd == 'locals': - printsymbols(tb.tb_frame.f_locals) - elif cmd == 'globals': - printsymbols(tb.tb_frame.f_globals) - elif cmd in ('?', 'help'): - browserhelp() - else: - browserexec(tb, cmd) + if not tb: + print 'No traceback.' + return + tblist = [] + while tb: + tblist.append(tb) + tb = tb.tb_next + ptr = len(tblist)-1 + tb = tblist[ptr] + while 1: + if tb != tblist[ptr]: + tb = tblist[ptr] + print `ptr` + ':', + printtbheader(tb) + try: + line = raw_input('TB: ') + except KeyboardInterrupt: + print '\n[Interrupted]' + break + except EOFError: + print '\n[EOF]' + break + cmd = line.strip() + if cmd: + if cmd == 'quit': + break + elif cmd == 'list': + browserlist(tb) + elif cmd == 'up': + if ptr-1 >= 0: ptr = ptr-1 + else: print 'Bottom of stack.' + elif cmd == 'down': + if ptr+1 < len(tblist): ptr = ptr+1 + else: print 'Top of stack.' + elif cmd == 'locals': + printsymbols(tb.tb_frame.f_locals) + elif cmd == 'globals': + printsymbols(tb.tb_frame.f_globals) + elif cmd in ('?', 'help'): + browserhelp() + else: + browserexec(tb, cmd) def browserlist(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - last = lineno - first = max(1, last-10) - for i in range(first, last+1): - if i == lineno: prefix = '***' + `i`.rjust(4) + ':' - else: prefix = `i`.rjust(7) + ':' - line = linecache.getline(filename, i) - if line[-1:] == '\n': line = line[:-1] - print prefix + line + filename = tb.tb_frame.f_code.co_filename + lineno = tb.tb_lineno + last = lineno + first = max(1, last-10) + for i in range(first, last+1): + if i == lineno: prefix = '***' + `i`.rjust(4) + ':' + else: prefix = `i`.rjust(7) + ':' + line = linecache.getline(filename, i) + if line[-1:] == '\n': line = line[:-1] + print prefix + line def browserexec(tb, cmd): - locals = tb.tb_frame.f_locals - globals = tb.tb_frame.f_globals - try: - exec cmd+'\n' in globals, locals - except: - t, v = sys.exc_info()[:2] - print '*** Exception:', - if type(t) is type(''): - print t, - else: - print t.__name__, - if v is not None: - print ':', v, - print - print 'Type help to get help.' + locals = tb.tb_frame.f_locals + globals = tb.tb_frame.f_globals + try: + exec cmd+'\n' in globals, locals + except: + t, v = sys.exc_info()[:2] + print '*** Exception:', + if type(t) is type(''): + print t, + else: + print t.__name__, + if v is not None: + print ':', v, + print + print 'Type help to get help.' def browserhelp(): - print - print ' This is the traceback browser. Commands are:' - print ' up : move one level up in the call stack' - print ' down : move one level down in the call stack' - print ' locals : print all local variables at this level' - print ' globals : print all global variables at this level' - print ' list : list source code around the failure' - print ' help : print help (what you are reading now)' - print ' quit : back to command interpreter' - print ' Typing any other 1-line statement will execute it' - print ' using the current level\'s symbol tables' - print + print + print ' This is the traceback browser. Commands are:' + print ' up : move one level up in the call stack' + print ' down : move one level down in the call stack' + print ' locals : print all local variables at this level' + print ' globals : print all global variables at this level' + print ' list : list source code around the failure' + print ' help : print help (what you are reading now)' + print ' quit : back to command interpreter' + print ' Typing any other 1-line statement will execute it' + print ' using the current level\'s symbol tables' + print def printtb(tb): - while tb: - print1tb(tb) - tb = tb.tb_next + while tb: + print1tb(tb) + tb = tb.tb_next def print1tb(tb): - printtbheader(tb) - if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: - printsymbols(tb.tb_frame.f_locals) + printtbheader(tb) + if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: + printsymbols(tb.tb_frame.f_locals) def printtbheader(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - info = '"' + filename + '"(' + `lineno` + ')' - line = linecache.getline(filename, lineno) - if line: - info = info + ': ' + line.strip() - print info + filename = tb.tb_frame.f_code.co_filename + lineno = tb.tb_lineno + info = '"' + filename + '"(' + `lineno` + ')' + line = linecache.getline(filename, lineno) + if line: + info = info + ': ' + line.strip() + print info def printsymbols(d): - keys = d.keys() - keys.sort() - for name in keys: - print ' ' + name.ljust(12) + ':', - printobject(d[name], 4) - print + keys = d.keys() + keys.sort() + for name in keys: + print ' ' + name.ljust(12) + ':', + printobject(d[name], 4) + print def printobject(v, maxlevel): - if v is None: - print 'None', - elif type(v) in (type(0), type(0.0)): - print v, - elif type(v) is type(''): - if len(v) > 20: - print `v[:17] + '...'`, - else: - print `v`, - elif type(v) is type(()): - print '(', - printlist(v, maxlevel) - print ')', - elif type(v) is type([]): - print '[', - printlist(v, maxlevel) - print ']', - elif type(v) is type({}): - print '{', - printdict(v, maxlevel) - print '}', - else: - print v, + if v is None: + print 'None', + elif type(v) in (type(0), type(0.0)): + print v, + elif type(v) is type(''): + if len(v) > 20: + print `v[:17] + '...'`, + else: + print `v`, + elif type(v) is type(()): + print '(', + printlist(v, maxlevel) + print ')', + elif type(v) is type([]): + print '[', + printlist(v, maxlevel) + print ']', + elif type(v) is type({}): + print '{', + printdict(v, maxlevel) + print '}', + else: + print v, def printlist(v, maxlevel): - n = len(v) - if n == 0: return - if maxlevel <= 0: - print '...', - return - for i in range(min(6, n)): - printobject(v[i], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', + n = len(v) + if n == 0: return + if maxlevel <= 0: + print '...', + return + for i in range(min(6, n)): + printobject(v[i], maxlevel-1) + if i+1 < n: print ',', + if n > 6: print '...', def printdict(v, maxlevel): - keys = v.keys() - n = len(keys) - if n == 0: return - if maxlevel <= 0: - print '...', - return - keys.sort() - for i in range(min(6, n)): - key = keys[i] - print `key` + ':', - printobject(v[key], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', + keys = v.keys() + n = len(keys) + if n == 0: return + if maxlevel <= 0: + print '...', + return + keys.sort() + for i in range(min(6, n)): + key = keys[i] + print `key` + ':', + printobject(v[key], maxlevel-1) + if i+1 < n: print ',', + if n > 6: print '...', diff --git a/Lib/lib-old/util.py b/Lib/lib-old/util.py index 6cb1433..104af1e 100644 --- a/Lib/lib-old/util.py +++ b/Lib/lib-old/util.py @@ -10,16 +10,16 @@ # If it occurs more than once, remove the first occurrence. # def remove(item, list): - if item in list: list.remove(item) + if item in list: list.remove(item) # Return a string containing a file's contents. # def readfile(fn): - return readopenfile(open(fn, 'r')) + return readopenfile(open(fn, 'r')) # Read an open file until EOF. # def readopenfile(fp): - return fp.read() + return fp.read() diff --git a/Lib/lib-old/zmod.py b/Lib/lib-old/zmod.py index 7259bf8..55f49df 100644 --- a/Lib/lib-old/zmod.py +++ b/Lib/lib-old/zmod.py @@ -1,7 +1,7 @@ # module 'zmod' # Compute properties of mathematical "fields" formed by taking -# Z/n (the whole numbers modulo some whole number n) and an +# Z/n (the whole numbers modulo some whole number n) and an # irreducible polynomial (i.e., a polynomial with only complex zeros), # e.g., Z/5 and X**2 + 2. # @@ -30,65 +30,65 @@ P = poly.plus(poly.one(0, 2), poly.one(2, 1)) # 2 + x**2 # Return x modulo y. Returns >= 0 even if x < 0. def mod(x, y): - return divmod(x, y)[1] + return divmod(x, y)[1] # Normalize a polynomial modulo n and modulo p. def norm(a, n, p): - a = poly.modulo(a, p) - a = a[:] - for i in range(len(a)): a[i] = mod(a[i], n) - a = poly.normalize(a) - return a + a = poly.modulo(a, p) + a = a[:] + for i in range(len(a)): a[i] = mod(a[i], n) + a = poly.normalize(a) + return a # Make a list of all n^d elements of the proposed field. def make_all(mat): - all = [] - for row in mat: - for a in row: - all.append(a) - return all + all = [] + for row in mat: + for a in row: + all.append(a) + return all def make_elements(n, d): - if d == 0: return [poly.one(0, 0)] - sub = make_elements(n, d-1) - all = [] - for a in sub: - for i in range(n): - all.append(poly.plus(a, poly.one(d-1, i))) - return all + if d == 0: return [poly.one(0, 0)] + sub = make_elements(n, d-1) + all = [] + for a in sub: + for i in range(n): + all.append(poly.plus(a, poly.one(d-1, i))) + return all def make_inv(all, n, p): - x = poly.one(1, 1) - inv = [] - for a in all: - inv.append(norm(poly.times(a, x), n, p)) - return inv + x = poly.one(1, 1) + inv = [] + for a in all: + inv.append(norm(poly.times(a, x), n, p)) + return inv def checkfield(n, p): - all = make_elements(n, len(p)-1) - inv = make_inv(all, n, p) - all1 = all[:] - inv1 = inv[:] - all1.sort() - inv1.sort() - if all1 == inv1: print 'BINGO!' - else: - print 'Sorry:', n, p - print all - print inv + all = make_elements(n, len(p)-1) + inv = make_inv(all, n, p) + all1 = all[:] + inv1 = inv[:] + all1.sort() + inv1.sort() + if all1 == inv1: print 'BINGO!' + else: + print 'Sorry:', n, p + print all + print inv def rj(s, width): - if type(s) is not type(''): s = `s` - n = len(s) - if n >= width: return s - return ' '*(width - n) + s + if type(s) is not type(''): s = `s` + n = len(s) + if n >= width: return s + return ' '*(width - n) + s def lj(s, width): - if type(s) is not type(''): s = `s` - n = len(s) - if n >= width: return s - return s + ' '*(width - n) + if type(s) is not type(''): s = `s` + n = len(s) + if n >= width: return s + return s + ' '*(width - n) |