rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
-t: decode string 'Aladdin:open sesame'"""
-t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
def test(): """Small test program""" import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') except getopt.error, msg: sys.stdout = sys.stderr print msg print """usage: basd64 [-d] [-e] [-u] [-t] [file|-] -d, -u: decode -e: encode (default) -t: decode string 'Aladdin:open sesame'""" sys.exit(2) func = encode for o, a in opts: if o == '-e': func = encode if o == '-d': func = decode if o == '-u': func = decode if o == '-t': test1(); return if args and args[0] != '-': func(open(args[0], 'rb'), sys.stdout) else: func(sys.stdin, sys.stdout)
class PyShell(MultiEditorWindow):
class PyShell(PyShellEditorWindow):
def write(self, s): # Override base class write self.tkconsole.console.write(s)
flist = FileList(root) MultiEditorWindow.__init__(self, flist, None, None)
flist = PyShellFileList(root) PyShellEditorWindow.__init__(self, flist, None, None)
def __init__(self, flist=None): self.interp = ModifiedInterpreter(self) if flist is None: root = Tk() fixwordbreaks(root) root.withdraw() flist = FileList(root)
reply = MultiEditorWindow.close(self)
reply = PyShellEditorWindow.close(self)
def close(self): # Extend base class method if self.executing: # XXX Need to ask a question here if not tkMessageBox.askokcancel( "Cancel?", "The program is still running; do you want to cancel it?", default="ok", master=self.text): return "cancel" self.canceled = 1 if self.reading: self.top.quit() return "cancel" reply = MultiEditorWindow.close(self) if reply != "cancel": # Restore std streams sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdin = sys.__stdin__ # Break cycles self.interp = None self.console = None return reply
def interact(self):
def begin(self):
def interact(self): self.resetoutput() self.write("Python %s on %s\n%s\n" % (sys.version, sys.platform, sys.copyright)) try: sys.ps1 except AttributeError: sys.ps1 = ">>> " self.showprompt() import Tkinter Tkinter._default_root = None self.top.mainloop()
flist = FileList(root)
flist = PyShellFileList(root)
def main(): global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = FileList(root) if sys.argv[1:]: for filename in sys.argv[1:]: flist.open(filename) t = PyShell(flist) t.interact()
t.interact()
flist.pyshell = t t.begin() root.mainloop()
def main(): global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = FileList(root) if sys.argv[1:]: for filename in sys.argv[1:]: flist.open(filename) t = PyShell(flist) t.interact()
os.close(r2w[rd])
os.close(r2w[rd]) ; os.close( rd ) p.unregister( r2w[rd] ) p.unregister( rd )
def test_poll1(): """Basic functional test of poll object Create a bunch of pipe and test that poll works with them. """ print 'Running poll test 1' p = select.poll() NUM_PIPES = 12 MSG = " This is a test." MSG_LEN = len(MSG) readers = [] writers = [] r2w = {} w2r = {} for i in range(NUM_PIPES): rd, wr = os.pipe() p.register(rd, select.POLLIN) p.register(wr, select.POLLOUT) readers.append(rd) writers.append(wr) r2w[rd] = wr w2r[wr] = rd while writers: ready = p.poll() ready_writers = find_ready_matching(ready, select.POLLOUT) if not ready_writers: raise RuntimeError, "no pipes ready for writing" wr = random.choice(ready_writers) os.write(wr, MSG) ready = p.poll() ready_readers = find_ready_matching(ready, select.POLLIN) if not ready_readers: raise RuntimeError, "no pipes ready for reading" rd = random.choice(ready_readers) buf = os.read(rd, MSG_LEN) assert len(buf) == MSG_LEN print buf os.close(r2w[rd]) writers.remove(r2w[rd]) poll_unit_tests() print 'Poll test 1 complete'
if fdlist[0] == (p.fileno(),select.POLLHUP):
fd, flags = fdlist[0] if flags & select.POLLHUP:
def test_poll2(): print 'Running poll test 2' cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' p = os.popen(cmd, 'r') pollster = select.poll() pollster.register( p, select.POLLIN ) for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10: if verbose: print 'timeout =', tout fdlist = pollster.poll(tout) if (fdlist == []): continue if fdlist[0] == (p.fileno(),select.POLLHUP): line = p.readline() if line != "": print 'error: pipe seems to be closed, but still returns data' continue elif fdlist[0] == (p.fileno(),select.POLLIN): line = p.readline() if verbose: print `line` if not line: if verbose: print 'EOF' break continue else: print 'Unexpected return value from select.poll:', fdlist p.close() print 'Poll test 2 complete'
elif fdlist[0] == (p.fileno(),select.POLLIN):
elif flags & select.POLLIN:
def test_poll2(): print 'Running poll test 2' cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' p = os.popen(cmd, 'r') pollster = select.poll() pollster.register( p, select.POLLIN ) for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10: if verbose: print 'timeout =', tout fdlist = pollster.poll(tout) if (fdlist == []): continue if fdlist[0] == (p.fileno(),select.POLLHUP): line = p.readline() if line != "": print 'error: pipe seems to be closed, but still returns data' continue elif fdlist[0] == (p.fileno(),select.POLLIN): line = p.readline() if verbose: print `line` if not line: if verbose: print 'EOF' break continue else: print 'Unexpected return value from select.poll:', fdlist p.close() print 'Poll test 2 complete'
verify (D().meth(4) == "D(4)C(4)B(4)A(4)")
vereq(D().meth(4), "D(4)C(4)B(4)A(4)") class mysuper(super): def __init__(self, *args): return super(mysuper, self).__init__(*args) class E(D): def meth(self, a): return "E(%r)" % a + mysuper(E, self).meth(a) vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)") class F(E): def meth(self, a): s = self.__super return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a) F._F__super = mysuper(F) vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)") try: super(D, 42) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D, 42)" try: super(D, C()) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D, C())" try: super(D).__get__(12) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D).__get__(12)" try: super(D).__get__(C()) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D).__get__(C())"
def meth(self, a): return "D(%r)" % a + super(D, self).meth(a)
return self.sslobj.read(size)
data = self.sslobj.read(size) while len(data) < size: data += self.sslobj.read(len(data)-size) return data
def read(self, size): """Read 'size' bytes from remote.""" return self.sslobj.read(size)
self.sslobj.write(data)
bytes = len(data) while bytes > 0: sent = self.sslobj.write(data) if sent == bytes: break data = data[sent:] bytes = bytes - sent
def send(self, data): """Send data to remote.""" self.sslobj.write(data)
return
return command
def reinitialize_command (self, command): """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This gives provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You'll have to re-finalize the command object (by calling 'finalize_options()' or 'ensure_finalized()') before using it for real.
def write(self, arg, move=0): x, y = start = self._position
def write(self, text, move=False): """ Write text at the current pen position. If move is true, the pen is moved to the bottom-right corner of the text. By default, move is False. Example: >>> turtle.write('The race is on!') >>> turtle.write('Home = (0, 0)', True) """ x, y = self._position
def write(self, arg, move=0): x, y = start = self._position x = x-1 # correction -- calibrated for Windows item = self._canvas.create_text(x, y, text=str(arg), anchor="sw", fill=self._color) self._items.append(item) if move: x0, y0, x1, y1 = self._canvas.bbox(item) self._goto(x1, y1) self._draw_turtle()
text=str(arg), anchor="sw",
text=str(text), anchor="sw",
def write(self, arg, move=0): x, y = start = self._position x = x-1 # correction -- calibrated for Windows item = self._canvas.create_text(x, y, text=str(arg), anchor="sw", fill=self._color) self._items.append(item) if move: x0, y0, x1, y1 = self._canvas.bbox(item) self._goto(x1, y1) self._draw_turtle()
self._canvas.lower(item)
def fill(self, flag): if self._filling: path = tuple(self._path) smooth = self._filling < 0 if len(path) > 2: item = self._canvas._create('polygon', path, {'fill': self._color, 'smooth': smooth}) self._items.append(item) self._canvas.lower(item) if self._tofill: for item in self._tofill: self._canvas.itemconfigure(item, fill=self._color) self._items.append(item) self._path = [] self._tofill = [] self._filling = flag if flag: self._path.append(self._position) self.forward(0)
start = self._angle - 90.0
start = self._angle - (self._fullcircle / 4.0)
def circle(self, radius, extent=None): if extent is None: extent = self._fullcircle x0, y0 = self._position xc = x0 - radius * sin(self._angle * self._invradian) yc = y0 - radius * cos(self._angle * self._invradian) if radius >= 0.0: start = self._angle - 90.0 else: start = self._angle + 90.0 extent = -extent if self._filling: if abs(extent) >= self._fullcircle: item = self._canvas.create_oval(xc-radius, yc-radius, xc+radius, yc+radius, width=self._width, outline="") self._tofill.append(item) item = self._canvas.create_arc(xc-radius, yc-radius, xc+radius, yc+radius, style="chord", start=start, extent=extent, width=self._width, outline="") self._tofill.append(item) if self._drawing: if abs(extent) >= self._fullcircle: item = self._canvas.create_oval(xc-radius, yc-radius, xc+radius, yc+radius, width=self._width, outline=self._color) self._items.append(item) item = self._canvas.create_arc(xc-radius, yc-radius, xc+radius, yc+radius, style="arc", start=start, extent=extent, width=self._width, outline=self._color) self._items.append(item) angle = start + extent x1 = xc + abs(radius) * cos(angle * self._invradian) y1 = yc - abs(radius) * sin(angle * self._invradian) self._angle = (self._angle + extent) % self._fullcircle self._position = x1, y1 if self._filling: self._path.append(self._position) self._draw_turtle()
start = self._angle + 90.0
start = self._angle + (self._fullcircle / 4.0)
def circle(self, radius, extent=None): if extent is None: extent = self._fullcircle x0, y0 = self._position xc = x0 - radius * sin(self._angle * self._invradian) yc = y0 - radius * cos(self._angle * self._invradian) if radius >= 0.0: start = self._angle - 90.0 else: start = self._angle + 90.0 extent = -extent if self._filling: if abs(extent) >= self._fullcircle: item = self._canvas.create_oval(xc-radius, yc-radius, xc+radius, yc+radius, width=self._width, outline="") self._tofill.append(item) item = self._canvas.create_arc(xc-radius, yc-radius, xc+radius, yc+radius, style="chord", start=start, extent=extent, width=self._width, outline="") self._tofill.append(item) if self._drawing: if abs(extent) >= self._fullcircle: item = self._canvas.create_oval(xc-radius, yc-radius, xc+radius, yc+radius, width=self._width, outline=self._color) self._items.append(item) item = self._canvas.create_arc(xc-radius, yc-radius, xc+radius, yc+radius, style="arc", start=start, extent=extent, width=self._width, outline=self._color) self._items.append(item) angle = start + extent x1 = xc + abs(radius) * cos(angle * self._invradian) y1 = yc - abs(radius) * sin(angle * self._invradian) self._angle = (self._angle + extent) % self._fullcircle self._position = x1, y1 if self._filling: self._path.append(self._position) self._draw_turtle()
x0, y0 = start = self._position
x0, y0 = self._position
def _goto(self, x1, y1): x0, y0 = start = self._position self._position = map(float, (x1, y1)) if self._filling: self._path.append(self._position) if self._drawing: if self._tracing: dx = float(x1 - x0) dy = float(y1 - y0) distance = hypot(dx, dy) nhops = int(distance) item = self._canvas.create_line(x0, y0, x0, y0, width=self._width, capstyle="round", fill=self._color) try: for i in range(1, 1+nhops): x, y = x0 + dx*i/nhops, y0 + dy*i/nhops self._canvas.coords(item, x0, y0, x, y) self._draw_turtle((x,y)) self._canvas.update() self._canvas.after(10) # in case nhops==0 self._canvas.coords(item, x0, y0, x1, y1) self._canvas.itemconfigure(item, arrow="none") except Tkinter.TclError: # Probably the window was closed! return else: item = self._canvas.create_line(x0, y0, x1, y1, width=self._width, capstyle="round", fill=self._color) self._items.append(item) self._draw_turtle()
self._canvas.after(10)
self._canvas.after(self._delay)
def _goto(self, x1, y1): x0, y0 = start = self._position self._position = map(float, (x1, y1)) if self._filling: self._path.append(self._position) if self._drawing: if self._tracing: dx = float(x1 - x0) dy = float(y1 - y0) distance = hypot(dx, dy) nhops = int(distance) item = self._canvas.create_line(x0, y0, x0, y0, width=self._width, capstyle="round", fill=self._color) try: for i in range(1, 1+nhops): x, y = x0 + dx*i/nhops, y0 + dy*i/nhops self._canvas.coords(item, x0, y0, x, y) self._draw_turtle((x,y)) self._canvas.update() self._canvas.after(10) # in case nhops==0 self._canvas.coords(item, x0, y0, x1, y1) self._canvas.itemconfigure(item, arrow="none") except Tkinter.TclError: # Probably the window was closed! return else: item = self._canvas.create_line(x0, y0, x1, y1, width=self._width, capstyle="round", fill=self._color) self._items.append(item) self._draw_turtle()
def _draw_turtle(self,position=[]):
def speed(self, speed): """ Set the turtle's speed. speed must one of these five strings: 'fastest' is a 0 ms delay 'fast' is a 5 ms delay 'normal' is a 10 ms delay 'slow' is a 15 ms delay 'slowest' is a 20 ms delay Example: >>> turtle.speed('slow') """ try: speed = speed.strip().lower() self._delay = speeds.index(speed) * 5 except: raise ValueError("%r is not a valid speed. speed must be " "one of %s" % (speed, speeds)) def delay(self, delay): """ Set the drawing delay in milliseconds. This is intended to allow finer control of the drawing speed than the speed() method Example: >>> turtle.delay(15) """ if int(delay) < 0: raise ValueError("delay must be greater than or equal to 0") self._delay = int(delay) def _draw_turtle(self, position=[]):
def _draw_turtle(self,position=[]): if not self._tracing: return if position == []: position = self._position x,y = position distance = 8 dx = distance * cos(self._angle*self._invradian) dy = distance * sin(self._angle*self._invradian) self._delete_turtle() self._arrow = self._canvas.create_line(x-dx,y+dy,x,y, width=self._width, arrow="last", capstyle="round", fill=self._color) self._canvas.update()
pen = _pen if not pen: _pen = pen = Pen() return pen
if not _pen: _pen = Pen() return _pen class Turtle(Pen): pass """For documentation of the following functions see the RawPen methods with the same names """
def _getpen(): global _pen pen = _pen if not pen: _pen = pen = Pen() return pen
if __name__ == '__main__': _root.mainloop()
def demo2(): speed('fast') width(3) setheading(towards(0,0)) x,y = position() r = (x**2+y**2)**.5/2.0 right(90) pendown = True for i in range(18): if pendown: up() pendown = False else: down() pendown = True circle(r,10) sleep(2) reset() left(90) l = 10 color("green") width(3) left(180) sp = 5 for i in range(-2,16): if i > 0: color(1.0-0.05*i,0,0.05*i) fill(1) color("green") for j in range(3): forward(l) left(120) l += 10 left(15) if sp > 0: sp = sp-1 speed(speeds[sp]) color(0.25,0,0.75) fill(0) color("green") left(130) up() forward(90) color("red") speed('fastest') down(); turtle=Turtle() turtle.reset() turtle.left(90) turtle.speed('normal') turtle.up() turtle.goto(280,40) turtle.left(24) turtle.down() turtle.speed('fast') turtle.color("blue") turtle.width(2) speed('fastest') setheading(towards(turtle)) while ( abs(position()[0]-turtle.position()[0])>4 or abs(position()[1]-turtle.position()[1])>4): turtle.forward(3.5) turtle.left(0.6) setheading(towards(turtle)) forward(4) write("CAUGHT! ", move=True)
def demo(): reset() tracer(1) up() backward(100) down() # draw 3 squares; the last filled width(3) for i in range(3): if i == 2: fill(1) for j in range(4): forward(20) left(90) if i == 2: color("maroon") fill(0) up() forward(30) down() width(1) color("black") # move out of the way tracer(0) up() right(90) forward(100) right(90) forward(100) right(180) down() # some text write("startstart", 1) write("start", 1) color("red") # staircase for i in range(5): forward(20) left(90) forward(20) right(90) # filled staircase fill(1) for i in range(5): forward(20) left(90) forward(20) right(90) fill(0) # more text write("end") if __name__ == '__main__': _root.mainloop()
print "*** skipping leakage tests ***"
if verbose: print "*** skipping leakage tests ***"
def test_lineterminator(self): class mydialect(csv.Dialect): delimiter = ";" escapechar = '\\' doublequote = False skipinitialspace = True lineterminator = '\r\n' quoting = csv.QUOTE_NONE d = mydialect()
class MissingSectionHeaderError(Error):
class InterpolationDepthError(Error): def __init__(self, option, section, rawval): Error.__init__(self, "Value interpolation too deeply recursive:\n" "\tsection: [%s]\n" "\toption : %s\n" "\trawval : %s\n" % (section, option, rawval)) self.option = option self.section = section class ParsingError(Error): def __init__(self, filename): Error.__init__(self, 'File contains parsing errors: %s' % filename) self.filename = filename self.errors = [] def append(self, lineno, line): self.errors.append((lineno, line)) self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line) class MissingSectionHeaderError(ParsingError):
def __init__(self, reference, option, section, rawval): Error.__init__(self, "Bad value substitution:\n" "\tsection: [%s]\n" "\toption : %s\n" "\tkey : %s\n" "\trawval : %s\n" % (section, option, reference, rawval)) self.reference = reference self.option = option self.section = section
class ParsingError(Error): def __init__(self, filename): Error.__init__(self, 'File contains parsing errors: %s' % filename) self.filename = filename self.errors = [] def append(self, lineno, line): self.errors.append((lineno, line)) self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
def __init__(self, filename, lineno, line): Error.__init__( self, 'File contains no section headers.\nfile: %s, line: %d\n%s' % (filename, lineno, line)) self.filename = filename self.lineno = lineno self.line = line
return self.__sections.has_key(section)
return section in self.sections()
def has_section(self, section): """Indicate whether the named section is present in the configuration.
try: opts = self.__sections[section] except KeyError: raise NoSectionError(section) return opts.has_key(option)
return option in self.options(section)
def has_option(self, section, option): """Return whether the given section has the given option.""" try: opts = self.__sections[section] except KeyError: raise NoSectionError(section) return opts.has_key(option)
return value
break if value.find("%(") >= 0: raise InterpolationDepthError(option, section, rawval) return value
def get(self, section, option, raw=0, vars=None): """Get an option value for a given section.
print "font=%r" % font
def __init__(self, root=None, font=None, name=None, exists=False, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name
_tryorder = ["galeon", "skipstone", "mozilla", "netscape",
_tryorder = ["galeon", "skipstone", "mozilla-firefox", "mozilla-firebird", "mozilla", "netscape",
def open_new(self, url): self.open(url)
if _iscommand("mozilla"): register("mozilla", None, Netscape("mozilla")) if _iscommand("netscape"): register("netscape", None, Netscape("netscape"))
for browser in ("mozilla-firefox", "mozilla-firebird", "mozilla", "netscape"): if _iscommand(browser): register(browser, None, Netscape(browser))
def open_new(self, url): self.open(url)
_combine = { ' ': ' ', '. ': '-', ' .': '+', '..': '^' }
def dump(tag, x, lo, hi): for i in xrange(lo, hi): print tag, x[i],
atags = atags + '.' * la btags = btags + '.' * lb
atags += '^' * la btags += '^' * lb
def fancy_replace(a, alo, ahi, b, blo, bhi): if TRACE: print '*** fancy_replace', alo, ahi, blo, bhi dump('>', a, alo, ahi) dump('<', b, blo, bhi) # don't synch up unless the lines have a similarity score of at # least cutoff; best_ratio tracks the best score seen so far best_ratio, cutoff = 0.74, 0.75 cruncher = SequenceMatcher(IS_CHARACTER_JUNK) eqi, eqj = None, None # 1st indices of equal lines (if any) # search for the pair that matches best without being identical # (identical lines must be junk lines, & we don't want to synch up # on junk -- unless we have to) for j in xrange(blo, bhi): bj = b[j] cruncher.set_seq2(bj) for i in xrange(alo, ahi): ai = a[i] if ai == bj: if eqi is None: eqi, eqj = i, j continue cruncher.set_seq1(ai) # computing similarity is expensive, so use the quick # upper bounds first -- have seen this speed up messy # compares by a factor of 3. # note that ratio() is only expensive to compute the first # time it's called on a sequence pair; the expensive part # of the computation is cached by cruncher if cruncher.real_quick_ratio() > best_ratio and \ cruncher.quick_ratio() > best_ratio and \ cruncher.ratio() > best_ratio: best_ratio, best_i, best_j = cruncher.ratio(), i, j if best_ratio < cutoff: # no non-identical "pretty close" pair if eqi is None: # no identical pair either -- treat it as a straight replace plain_replace(a, alo, ahi, b, blo, bhi) return # no close pair, but an identical pair -- synch up on that best_i, best_j, best_ratio = eqi, eqj, 1.0 else: # there's a close pair, so forget the identical pair (if any) eqi = None # a[best_i] very similar to b[best_j]; eqi is None iff they're not # identical if TRACE: print '*** best_ratio', best_ratio, best_i, best_j dump('>', a, best_i, best_i+1) dump('<', b, best_j, best_j+1) # pump out diffs from before the synch point fancy_helper(a, alo, best_i, b, blo, best_j) # do intraline marking on the synch pair aelt, belt = a[best_i], b[best_j] if eqi is None: # pump out a '-', '+', '?' triple for the synched lines; atags = btags = "" cruncher.set_seqs(aelt, belt) for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes(): la, lb = ai2 - ai1, bj2 - bj1 if tag == 'replace': atags = atags + '.' * la btags = btags + '.' * lb elif tag == 'delete': atags = atags + '.' * la elif tag == 'insert': btags = btags + '.' * lb elif tag == 'equal': atags = atags + ' ' * la btags = btags + ' ' * lb else: raise ValueError, 'unknown tag ' + `tag` la, lb = len(atags), len(btags) if la < lb: atags = atags + ' ' * (lb - la) elif lb < la: btags = btags + ' ' * (la - lb) combined = map(lambda x,y: _combine[x+y], atags, btags) printq(aelt, belt, string.rstrip(string.join(combined, ''))) else: # the synch pair is identical print ' ', aelt, # pump out diffs from after the synch point fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
atags = atags + '.' * la
atags += '-' * la
def fancy_replace(a, alo, ahi, b, blo, bhi): if TRACE: print '*** fancy_replace', alo, ahi, blo, bhi dump('>', a, alo, ahi) dump('<', b, blo, bhi) # don't synch up unless the lines have a similarity score of at # least cutoff; best_ratio tracks the best score seen so far best_ratio, cutoff = 0.74, 0.75 cruncher = SequenceMatcher(IS_CHARACTER_JUNK) eqi, eqj = None, None # 1st indices of equal lines (if any) # search for the pair that matches best without being identical # (identical lines must be junk lines, & we don't want to synch up # on junk -- unless we have to) for j in xrange(blo, bhi): bj = b[j] cruncher.set_seq2(bj) for i in xrange(alo, ahi): ai = a[i] if ai == bj: if eqi is None: eqi, eqj = i, j continue cruncher.set_seq1(ai) # computing similarity is expensive, so use the quick # upper bounds first -- have seen this speed up messy # compares by a factor of 3. # note that ratio() is only expensive to compute the first # time it's called on a sequence pair; the expensive part # of the computation is cached by cruncher if cruncher.real_quick_ratio() > best_ratio and \ cruncher.quick_ratio() > best_ratio and \ cruncher.ratio() > best_ratio: best_ratio, best_i, best_j = cruncher.ratio(), i, j if best_ratio < cutoff: # no non-identical "pretty close" pair if eqi is None: # no identical pair either -- treat it as a straight replace plain_replace(a, alo, ahi, b, blo, bhi) return # no close pair, but an identical pair -- synch up on that best_i, best_j, best_ratio = eqi, eqj, 1.0 else: # there's a close pair, so forget the identical pair (if any) eqi = None # a[best_i] very similar to b[best_j]; eqi is None iff they're not # identical if TRACE: print '*** best_ratio', best_ratio, best_i, best_j dump('>', a, best_i, best_i+1) dump('<', b, best_j, best_j+1) # pump out diffs from before the synch point fancy_helper(a, alo, best_i, b, blo, best_j) # do intraline marking on the synch pair aelt, belt = a[best_i], b[best_j] if eqi is None: # pump out a '-', '+', '?' triple for the synched lines; atags = btags = "" cruncher.set_seqs(aelt, belt) for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes(): la, lb = ai2 - ai1, bj2 - bj1 if tag == 'replace': atags = atags + '.' * la btags = btags + '.' * lb elif tag == 'delete': atags = atags + '.' * la elif tag == 'insert': btags = btags + '.' * lb elif tag == 'equal': atags = atags + ' ' * la btags = btags + ' ' * lb else: raise ValueError, 'unknown tag ' + `tag` la, lb = len(atags), len(btags) if la < lb: atags = atags + ' ' * (lb - la) elif lb < la: btags = btags + ' ' * (la - lb) combined = map(lambda x,y: _combine[x+y], atags, btags) printq(aelt, belt, string.rstrip(string.join(combined, ''))) else: # the synch pair is identical print ' ', aelt, # pump out diffs from after the synch point fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
btags = btags + '.' * lb
btags += '+' * lb
def fancy_replace(a, alo, ahi, b, blo, bhi): if TRACE: print '*** fancy_replace', alo, ahi, blo, bhi dump('>', a, alo, ahi) dump('<', b, blo, bhi) # don't synch up unless the lines have a similarity score of at # least cutoff; best_ratio tracks the best score seen so far best_ratio, cutoff = 0.74, 0.75 cruncher = SequenceMatcher(IS_CHARACTER_JUNK) eqi, eqj = None, None # 1st indices of equal lines (if any) # search for the pair that matches best without being identical # (identical lines must be junk lines, & we don't want to synch up # on junk -- unless we have to) for j in xrange(blo, bhi): bj = b[j] cruncher.set_seq2(bj) for i in xrange(alo, ahi): ai = a[i] if ai == bj: if eqi is None: eqi, eqj = i, j continue cruncher.set_seq1(ai) # computing similarity is expensive, so use the quick # upper bounds first -- have seen this speed up messy # compares by a factor of 3. # note that ratio() is only expensive to compute the first # time it's called on a sequence pair; the expensive part # of the computation is cached by cruncher if cruncher.real_quick_ratio() > best_ratio and \ cruncher.quick_ratio() > best_ratio and \ cruncher.ratio() > best_ratio: best_ratio, best_i, best_j = cruncher.ratio(), i, j if best_ratio < cutoff: # no non-identical "pretty close" pair if eqi is None: # no identical pair either -- treat it as a straight replace plain_replace(a, alo, ahi, b, blo, bhi) return # no close pair, but an identical pair -- synch up on that best_i, best_j, best_ratio = eqi, eqj, 1.0 else: # there's a close pair, so forget the identical pair (if any) eqi = None # a[best_i] very similar to b[best_j]; eqi is None iff they're not # identical if TRACE: print '*** best_ratio', best_ratio, best_i, best_j dump('>', a, best_i, best_i+1) dump('<', b, best_j, best_j+1) # pump out diffs from before the synch point fancy_helper(a, alo, best_i, b, blo, best_j) # do intraline marking on the synch pair aelt, belt = a[best_i], b[best_j] if eqi is None: # pump out a '-', '+', '?' triple for the synched lines; atags = btags = "" cruncher.set_seqs(aelt, belt) for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes(): la, lb = ai2 - ai1, bj2 - bj1 if tag == 'replace': atags = atags + '.' * la btags = btags + '.' * lb elif tag == 'delete': atags = atags + '.' * la elif tag == 'insert': btags = btags + '.' * lb elif tag == 'equal': atags = atags + ' ' * la btags = btags + ' ' * lb else: raise ValueError, 'unknown tag ' + `tag` la, lb = len(atags), len(btags) if la < lb: atags = atags + ' ' * (lb - la) elif lb < la: btags = btags + ' ' * (la - lb) combined = map(lambda x,y: _combine[x+y], atags, btags) printq(aelt, belt, string.rstrip(string.join(combined, ''))) else: # the synch pair is identical print ' ', aelt, # pump out diffs from after the synch point fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
atags = atags + ' ' * la btags = btags + ' ' * lb
atags += ' ' * la btags += ' ' * lb
def fancy_replace(a, alo, ahi, b, blo, bhi): if TRACE: print '*** fancy_replace', alo, ahi, blo, bhi dump('>', a, alo, ahi) dump('<', b, blo, bhi) # don't synch up unless the lines have a similarity score of at # least cutoff; best_ratio tracks the best score seen so far best_ratio, cutoff = 0.74, 0.75 cruncher = SequenceMatcher(IS_CHARACTER_JUNK) eqi, eqj = None, None # 1st indices of equal lines (if any) # search for the pair that matches best without being identical # (identical lines must be junk lines, & we don't want to synch up # on junk -- unless we have to) for j in xrange(blo, bhi): bj = b[j] cruncher.set_seq2(bj) for i in xrange(alo, ahi): ai = a[i] if ai == bj: if eqi is None: eqi, eqj = i, j continue cruncher.set_seq1(ai) # computing similarity is expensive, so use the quick # upper bounds first -- have seen this speed up messy # compares by a factor of 3. # note that ratio() is only expensive to compute the first # time it's called on a sequence pair; the expensive part # of the computation is cached by cruncher if cruncher.real_quick_ratio() > best_ratio and \ cruncher.quick_ratio() > best_ratio and \ cruncher.ratio() > best_ratio: best_ratio, best_i, best_j = cruncher.ratio(), i, j if best_ratio < cutoff: # no non-identical "pretty close" pair if eqi is None: # no identical pair either -- treat it as a straight replace plain_replace(a, alo, ahi, b, blo, bhi) return # no close pair, but an identical pair -- synch up on that best_i, best_j, best_ratio = eqi, eqj, 1.0 else: # there's a close pair, so forget the identical pair (if any) eqi = None # a[best_i] very similar to b[best_j]; eqi is None iff they're not # identical if TRACE: print '*** best_ratio', best_ratio, best_i, best_j dump('>', a, best_i, best_i+1) dump('<', b, best_j, best_j+1) # pump out diffs from before the synch point fancy_helper(a, alo, best_i, b, blo, best_j) # do intraline marking on the synch pair aelt, belt = a[best_i], b[best_j] if eqi is None: # pump out a '-', '+', '?' triple for the synched lines; atags = btags = "" cruncher.set_seqs(aelt, belt) for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes(): la, lb = ai2 - ai1, bj2 - bj1 if tag == 'replace': atags = atags + '.' * la btags = btags + '.' * lb elif tag == 'delete': atags = atags + '.' * la elif tag == 'insert': btags = btags + '.' * lb elif tag == 'equal': atags = atags + ' ' * la btags = btags + ' ' * lb else: raise ValueError, 'unknown tag ' + `tag` la, lb = len(atags), len(btags) if la < lb: atags = atags + ' ' * (lb - la) elif lb < la: btags = btags + ' ' * (la - lb) combined = map(lambda x,y: _combine[x+y], atags, btags) printq(aelt, belt, string.rstrip(string.join(combined, ''))) else: # the synch pair is identical print ' ', aelt, # pump out diffs from after the synch point fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
la, lb = len(atags), len(btags) if la < lb: atags = atags + ' ' * (lb - la) elif lb < la: btags = btags + ' ' * (la - lb) combined = map(lambda x,y: _combine[x+y], atags, btags) printq(aelt, belt, string.rstrip(string.join(combined, '')))
printq(aelt, belt, atags, btags)
def fancy_replace(a, alo, ahi, b, blo, bhi): if TRACE: print '*** fancy_replace', alo, ahi, blo, bhi dump('>', a, alo, ahi) dump('<', b, blo, bhi) # don't synch up unless the lines have a similarity score of at # least cutoff; best_ratio tracks the best score seen so far best_ratio, cutoff = 0.74, 0.75 cruncher = SequenceMatcher(IS_CHARACTER_JUNK) eqi, eqj = None, None # 1st indices of equal lines (if any) # search for the pair that matches best without being identical # (identical lines must be junk lines, & we don't want to synch up # on junk -- unless we have to) for j in xrange(blo, bhi): bj = b[j] cruncher.set_seq2(bj) for i in xrange(alo, ahi): ai = a[i] if ai == bj: if eqi is None: eqi, eqj = i, j continue cruncher.set_seq1(ai) # computing similarity is expensive, so use the quick # upper bounds first -- have seen this speed up messy # compares by a factor of 3. # note that ratio() is only expensive to compute the first # time it's called on a sequence pair; the expensive part # of the computation is cached by cruncher if cruncher.real_quick_ratio() > best_ratio and \ cruncher.quick_ratio() > best_ratio and \ cruncher.ratio() > best_ratio: best_ratio, best_i, best_j = cruncher.ratio(), i, j if best_ratio < cutoff: # no non-identical "pretty close" pair if eqi is None: # no identical pair either -- treat it as a straight replace plain_replace(a, alo, ahi, b, blo, bhi) return # no close pair, but an identical pair -- synch up on that best_i, best_j, best_ratio = eqi, eqj, 1.0 else: # there's a close pair, so forget the identical pair (if any) eqi = None # a[best_i] very similar to b[best_j]; eqi is None iff they're not # identical if TRACE: print '*** best_ratio', best_ratio, best_i, best_j dump('>', a, best_i, best_i+1) dump('<', b, best_j, best_j+1) # pump out diffs from before the synch point fancy_helper(a, alo, best_i, b, blo, best_j) # do intraline marking on the synch pair aelt, belt = a[best_i], b[best_j] if eqi is None: # pump out a '-', '+', '?' triple for the synched lines; atags = btags = "" cruncher.set_seqs(aelt, belt) for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes(): la, lb = ai2 - ai1, bj2 - bj1 if tag == 'replace': atags = atags + '.' * la btags = btags + '.' * lb elif tag == 'delete': atags = atags + '.' * la elif tag == 'insert': btags = btags + '.' * lb elif tag == 'equal': atags = atags + ' ' * la btags = btags + ' ' * lb else: raise ValueError, 'unknown tag ' + `tag` la, lb = len(atags), len(btags) if la < lb: atags = atags + ' ' * (lb - la) elif lb < la: btags = btags + ' ' * (la - lb) combined = map(lambda x,y: _combine[x+y], atags, btags) printq(aelt, belt, string.rstrip(string.join(combined, ''))) else: # the synch pair is identical print ' ', aelt, # pump out diffs from after the synch point fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
def printq(aline, bline, qline):
def printq(aline, bline, atags, btags):
def printq(aline, bline, qline): common = min(count_leading(aline, "\t"), count_leading(bline, "\t")) common = min(common, count_leading(qline[:common], " ")) qline = "\t" * common + qline[common:] print '-', aline, '+', bline, '?', qline
common = min(common, count_leading(qline[:common], " ")) qline = "\t" * common + qline[common:] print '-', aline, '+', bline, '?', qline
common = min(common, count_leading(atags[:common], " ")) print "-", aline, if count_leading(atags, " ") < len(atags): print "?", "\t" * common + atags[common:] print "+", bline, if count_leading(btags, " ") < len(btags): print "?", "\t" * common + btags[common:]
def printq(aline, bline, qline): common = min(count_leading(aline, "\t"), count_leading(bline, "\t")) common = min(common, count_leading(qline[:common], " ")) qline = "\t" * common + qline[common:] print '-', aline, '+', bline, '?', qline
new = Request(newurl, req.get_data())
new = Request(newurl, req.get_data(), req.headers)
def http_error_302(self, req, fp, code, msg, headers): if headers.has_key('location'): newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl)
rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"')
rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
def find_user_password(self, realm, authuri): user, password = HTTPPasswordMgr.find_user_password(self,realm,authuri) if user is not None: return user, password return HTTPPasswordMgr.find_user_password(self, None, authuri)
module = filename
module = filename or "<unknown>"
def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} if isinstance(message, Warning): text = str(message) category = message.__class__ else: text = message message = category(message) key = (text, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if ((msg is None or msg.match(text)) and issubclass(category, cat) and (mod is None or mod.match(module)) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise message # Other actions if action == "once": registry[key] = 1 oncekey = (text, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (text, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%r) in warnings.filters:\n %s" % (action, item)) # Print message and context showwarning(message, category, filename, lineno)
p = subprocess.Popen(cmdline, close_fds=True)
if sys.platform[:3] == 'win': p = subprocess.Popen(cmdline) else: p = subprocess.Popen(cmdline, close_fds=True)
def open(self, url, new=0, autoraise=1): cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] try: p = subprocess.Popen(cmdline, close_fds=True) return not p.wait() except OSError: return False
setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None)
def open(self, url, new=0, autoraise=1): cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None) try: p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid) return (p.poll() is None) except OSError: return False
p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid)
if sys.platform[:3] == 'win': p = subprocess.Popen(cmdline) else: setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None) p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid)
def open(self, url, new=0, autoraise=1): cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None) try: p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid) return (p.poll() is None) except OSError: return False
self.assertEqual( posixpath.expanduser("~") + "/", posixpath.expanduser("~/") )
if posixpath.expanduser("~") != '/': self.assertEqual( posixpath.expanduser("~") + "/", posixpath.expanduser("~/") )
def test_expanduser(self): self.assertEqual(posixpath.expanduser("foo"), "foo") try: import pwd except ImportError: pass else: self.assert_(isinstance(posixpath.expanduser("~/"), basestring)) self.assertEqual( posixpath.expanduser("~") + "/", posixpath.expanduser("~/") ) self.assert_(isinstance(posixpath.expanduser("~root/"), basestring)) self.assert_(isinstance(posixpath.expanduser("~foo/"), basestring))
raise ValueError, "overflow in number field"
raise ValueError("overflow in number field")
def itn(n, digits=8, posix=False): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar allows storing numbers greater than # that if necessary. A leading 0200 byte indicates this particular # encoding, the following digits-1 bytes are a big-endian # representation. This allows values up to (256**(digits-1))-1. if 0 <= n < 8 ** (digits - 1): s = "%0*o" % (digits - 1, n) + NUL else: if posix: raise ValueError, "overflow in number field" if n < 0: # XXX We mimic GNU tar's behaviour with negative numbers, # this could raise OverflowError. n = struct.unpack("L", struct.pack("l", n))[0] s = "" for i in xrange(digits - 1): s = chr(n & 0377) + s n >>= 8 s = chr(0200) + s return s
raise IOError, "end of file reached"
raise IOError("end of file reached")
def copyfileobj(src, dst, length=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ if length == 0: return if length is None: shutil.copyfileobj(src, dst) return BUFSIZE = 16 * 1024 blocks, remainder = divmod(length, BUFSIZE) for b in xrange(blocks): buf = src.read(BUFSIZE) if len(buf) < BUFSIZE: raise IOError, "end of file reached" dst.write(buf) if remainder != 0: buf = src.read(remainder) if len(buf) < remainder: raise IOError, "end of file reached" dst.write(buf) return
raise CompressionError, "zlib module is not available"
raise CompressionError("zlib module is not available")
def __init__(self, name, mode, comptype, fileobj, bufsize): """Construct a _Stream object. """ self._extfileobj = True if fileobj is None: fileobj = _LowLevelFile(name, mode) self._extfileobj = False
raise CompressionError, "bz2 module is not available"
raise CompressionError("bz2 module is not available")
def __init__(self, name, mode, comptype, fileobj, bufsize): """Construct a _Stream object. """ self._extfileobj = True if fileobj is None: fileobj = _LowLevelFile(name, mode) self._extfileobj = False
raise ReadError, "not a gzip file"
raise ReadError("not a gzip file")
def _init_read_gz(self): """Initialize for reading a gzip compressed fileobj. """ self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) self.dbuf = ""
raise CompressionError, "unsupported compression method"
raise CompressionError("unsupported compression method")
def _init_read_gz(self): """Initialize for reading a gzip compressed fileobj. """ self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) self.dbuf = ""
raise StreamError, "seeking backwards is not allowed"
raise StreamError("seeking backwards is not allowed")
def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) for i in xrange(blocks): self.read(self.bufsize) self.read(remainder) else: raise StreamError, "seeking backwards is not allowed" return self.pos
raise ValueError, "file is closed"
raise ValueError("file is closed")
def _readnormal(self, size=None): """Read operation for regular files. """ if self.closed: raise ValueError, "file is closed" self.fileobj.seek(self.offset + self.pos) bytesleft = self.size - self.pos if size is None: bytestoread = bytesleft else: bytestoread = min(size, bytesleft) self.pos += bytestoread return self.__read(bytestoread)
raise ValueError, "file is closed"
raise ValueError("file is closed")
def _readsparse(self, size=None): """Read operation for sparse files. """ if self.closed: raise ValueError, "file is closed"
raise ValueError, "I/O operation on closed file"
raise ValueError("I/O operation on closed file")
def __iter__(self): """Get an iterator over the file object. """ if self.closed: raise ValueError, "I/O operation on closed file" return self
raise ValueError, "truncated header"
raise ValueError("truncated header")
def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: raise ValueError, "truncated header" if buf.count(NUL) == BLOCKSIZE: raise ValueError, "empty header"
raise ValueError, "empty header"
raise ValueError("empty header")
def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: raise ValueError, "truncated header" if buf.count(NUL) == BLOCKSIZE: raise ValueError, "empty header"
raise ValueError, "invalid header"
raise ValueError("invalid header")
def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: raise ValueError, "truncated header" if buf.count(NUL) == BLOCKSIZE: raise ValueError, "empty header"
raise ValueError, "mode must be 'r', 'a' or 'w'"
raise ValueError("mode must be 'r', 'a' or 'w'")
def __init__(self, name=None, mode="r", fileobj=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ self.name = name
raise ValueError, "nothing to open"
raise ValueError("nothing to open")
def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
raise ReadError, "file could not be opened successfully"
raise ReadError("file could not be opened successfully")
def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
raise CompressionError, "unknown compression type %r" % comptype
raise CompressionError("unknown compression type %r" % comptype)
def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
raise ValueError, "mode must be 'r' or 'w'"
raise ValueError("mode must be 'r' or 'w'")
def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
raise ValueError, "undiscernible mode"
raise ValueError("undiscernible mode")
def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
raise ValueError, "mode must be 'r', 'a' or 'w'"
raise ValueError("mode must be 'r', 'a' or 'w'")
def taropen(cls, name, mode="r", fileobj=None): """Open uncompressed tar archive name for reading or writing. """ if len(mode) > 1 or mode not in "raw": raise ValueError, "mode must be 'r', 'a' or 'w'" return cls(name, mode, fileobj)
raise ValueError, "mode must be 'r' or 'w'"
raise ValueError("mode must be 'r' or 'w'")
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
raise CompressionError, "gzip module is not available"
raise CompressionError("gzip module is not available")
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
raise ReadError, "not a gzip file"
raise ReadError("not a gzip file")
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
raise ValueError, "mode must be 'r' or 'w'."
raise ValueError("mode must be 'r' or 'w'.")
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'."
raise CompressionError, "bz2 module is not available"
raise CompressionError("bz2 module is not available")
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'."
raise ReadError, "not a bzip2 file"
raise ReadError("not a bzip2 file")
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'."
raise KeyError, "filename %r not found" % name
raise KeyError("filename %r not found" % name)
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurence is assumed to be the most up-to-date version. """ tarinfo = self._getmember(name) if tarinfo is None: raise KeyError, "filename %r not found" % name return tarinfo
raise ValueError, "file is too large (>= 8 GB)"
raise ValueError("file is too large (>= 8 GB)")
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw")
raise ValueError, "linkname is too long (>%d)" \ % (LENGTH_LINK)
raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK))
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw")
raise ValueError, "name is too long (>%d)" \ % (LENGTH_NAME)
raise ValueError("name is too long (>%d)" % (LENGTH_NAME))
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw")
raise StreamError, "cannot extract (sym)link as file object"
raise StreamError("cannot extract (sym)link as file object")
def extractfile(self, member): """Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() """ self._check("r")
raise ExtractError, "fifo not supported by system"
raise ExtractError("fifo not supported by system")
def makefifo(self, tarinfo, targetpath): """Make a fifo called targetpath. """ if hasattr(os, "mkfifo"): os.mkfifo(targetpath) else: raise ExtractError, "fifo not supported by system"
raise ExtractError, "special devices not supported by system"
raise ExtractError("special devices not supported by system")
def makedev(self, tarinfo, targetpath): """Make a character or block device called targetpath. """ if not hasattr(os, "mknod") or not hasattr(os, "makedev"): raise ExtractError, "special devices not supported by system"
raise IOError, "link could not be created"
raise IOError("link could not be created")
def makelink(self, tarinfo, targetpath): """Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link. """ linkpath = tarinfo.linkname try: if tarinfo.issym(): os.symlink(linkpath, targetpath) else: # See extract(). os.link(tarinfo._link_target, targetpath) except AttributeError: if tarinfo.issym(): linkpath = os.path.join(os.path.dirname(tarinfo.name), linkpath) linkpath = normpath(linkpath)
raise ExtractError, "could not change owner"
raise ExtractError("could not change owner")
def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: try: g = grp.getgrgid(tarinfo.gid)[2] except KeyError: g = os.getgid() try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: try: u = pwd.getpwuid(tarinfo.uid)[2] except KeyError: u = os.getuid() try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: if sys.platform != "os2emx": os.chown(targetpath, u, g) except EnvironmentError, e: raise ExtractError, "could not change owner"
raise ExtractError, "could not change mode"
raise ExtractError("could not change mode")
def chmod(self, tarinfo, targetpath): """Set file permissions of targetpath according to tarinfo. """ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) except EnvironmentError, e: raise ExtractError, "could not change mode"
raise ExtractError, "could not change modification time"
raise ExtractError("could not change modification time")
def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return if sys.platform == "win32" and tarinfo.isdir(): # According to msdn.microsoft.com, it is an error (EACCES) # to use utime() on directories. return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) except EnvironmentError, e: raise ExtractError, "could not change modification time"
self._dbg(2, "0x%X: %s" % (self.offset, e))
self._dbg(2, "0x%X: empty or invalid block: %s" % (self.offset, e))
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
raise ReadError, str(e)
raise ReadError("empty, unreadable or compressed " "file: %s" % e)
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
raise IOError, "%s is closed" % self.__class__.__name__
raise IOError("%s is closed" % self.__class__.__name__)
def _check(self, mode=None): """Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode. """ if self.closed: raise IOError, "%s is closed" % self.__class__.__name__ if mode is not None and self._mode not in mode: raise IOError, "bad operation for mode %r" % self._mode
raise IOError, "bad operation for mode %r" % self._mode
raise IOError("bad operation for mode %r" % self._mode)
def _check(self, mode=None): """Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode. """ if self.closed: raise IOError, "%s is closed" % self.__class__.__name__ if mode is not None and self._mode not in mode: raise IOError, "bad operation for mode %r" % self._mode
raise ValueError, "unknown compression constant"
raise ValueError("unknown compression constant")
def __init__(self, file, mode="r", compression=TAR_PLAIN): if compression == TAR_PLAIN: self.tarfile = TarFile.taropen(file, mode) elif compression == TAR_GZIPPED: self.tarfile = TarFile.gzopen(file, mode) else: raise ValueError, "unknown compression constant" if mode[0:1] == "r": members = self.tarfile.getmembers() for m in members: m.filename = m.name m.file_size = m.size m.date_time = time.gmtime(m.mtime)[:6]
ifp = open(args)
ifp = open(args[0])
def main(): global DEBUG # opts, args = getopt.getopt(sys.argv[1:], "D", ["debug"]) for opt, arg in opts: if opt in ("-D", "--debug"): DEBUG = DEBUG + 1 if len(args) == 0: ifp = sys.stdin ofp = sys.stdout elif len(args) == 1: ifp = open(args) ofp = sys.stdout elif len(args) == 2: ifp = open(args[0]) ofp = open(args[1], "w") else: usage() sys.exit(2) table = load_table(open(os.path.join(sys.path[0], 'conversion.xml'))) convert(ifp, ofp, table)
def test_05_no_pop_tops(self): self.run_test(no_pop_tops)
## def test_05_no_pop_tops(self):
container.set_payload(msg)
container.attach(msg)
def _parsebody(self, container, fp): # Parse the body, but first split the payload on the content-type # boundary if present. boundary = container.get_boundary() isdigest = (container.get_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately. Otherwise, just parse the rest of # the body as a single message. Note: any exceptions raised in the # recursive parse need to have their line numbers coerced. if boundary: preamble = epilogue = None # Split into subparts. The first boundary we're looking for won't # have the leading newline since we're at the start of the body # text. separator = '--' + boundary payload = fp.read() start = payload.find(separator) if start < 0: raise Errors.BoundaryError( "Couldn't find starting boundary: %s" % boundary) if start > 0: # there's some pre-MIME boundary preamble preamble = payload[0:start] # Find out what kind of line endings we're using start += len(separator) cre = re.compile('\r\n|\r|\n') mo = cre.search(payload, start) if mo: start += len(mo.group(0)) * (1 + isdigest) # We create a compiled regexp first because we need to be able to # specify the start position, and the module function doesn't # support this signature. :( cre = re.compile('(?P<sep>\r\n|\r|\n)' + re.escape(separator) + '--') mo = cre.search(payload, start) if not mo: raise Errors.BoundaryError( "Couldn't find terminating boundary: %s" % boundary) terminator = mo.start() linesep = mo.group('sep') if mo.end() < len(payload): # there's some post-MIME boundary epilogue epilogue = payload[mo.end():] # We split the textual payload on the boundary separator, which # includes the trailing newline. If the container is a # multipart/digest then the subparts are by default message/rfc822 # instead of text/plain. In that case, they'll have an extra # newline before the headers to distinguish the message's headers # from the subpart headers. separator += linesep * (1 + isdigest) parts = payload[start:terminator].split(linesep + separator) for part in parts: msgobj = self.parsestr(part) container.preamble = preamble container.epilogue = epilogue container.attach(msgobj) elif container.get_main_type() == 'multipart': # Very bad. A message is a multipart with no boundary! raise Errors.BoundaryError( 'multipart message with no defined boundary') elif container.get_type() == 'message/delivery-status': # This special kind of type contains blocks of headers separated # by a blank line. We'll represent each header block as a # separate Message object blocks = [] while 1: blockmsg = self._class() self._parseheaders(blockmsg, fp) if not len(blockmsg): # No more header blocks left break blocks.append(blockmsg) container.set_payload(blocks) elif container.get_main_type() == 'message': # Create a container for the payload, but watch out for there not # being any headers left try: msg = self.parse(fp) except Errors.HeaderParseError: msg = self._class() self._parsebody(msg, fp) container.set_payload(msg) else: container.set_payload(fp.read())
t = _translations.setdefault(key, class_(open(mofile, 'rb')))
t = _translations.get(key) if t is None: t = _translations.setdefault(key, class_(open(mofile, 'rb')))
def translation(domain, localedir=None, languages=None, class_=None): if class_ is None: class_ = GNUTranslations mofile = find(domain, localedir, languages) if mofile is None: raise IOError(ENOENT, 'No translation file found for domain', domain) key = os.path.abspath(mofile) # TBD: do we need to worry about the file pointer getting collected? t = _translations.setdefault(key, class_(open(mofile, 'rb'))) return t
def input(files=(), inplace=0, backup=""):
def input(files=None, inplace=0, backup=""):
def input(files=(), inplace=0, backup=""): global _state if _state and _state._file: raise RuntimeError, "input() already active" _state = FileInput(files, inplace, backup) return _state
def __init__(self, files=(), inplace=0, backup=""):
def __init__(self, files=None, inplace=0, backup=""):
def __init__(self, files=(), inplace=0, backup=""): if type(files) == type(''): files = (files,) else: files = tuple(files) if not files: files = tuple(sys.argv[1:]) if not files: files = ('-',) self._files = files self._inplace = inplace self._backup = backup self._savestdout = None self._output = None self._filename = None self._lineno = 0 self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = None
files = tuple(files)
if files is None: files = sys.argv[1:]
def __init__(self, files=(), inplace=0, backup=""): if type(files) == type(''): files = (files,) else: files = tuple(files) if not files: files = tuple(sys.argv[1:]) if not files: files = ('-',) self._files = files self._inplace = inplace self._backup = backup self._savestdout = None self._output = None self._filename = None self._lineno = 0 self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = None
files = tuple(sys.argv[1:]) if not files: files = ('-',)
files = ('-',) else: files = tuple(files)
def __init__(self, files=(), inplace=0, backup=""): if type(files) == type(''): files = (files,) else: files = tuple(files) if not files: files = tuple(sys.argv[1:]) if not files: files = ('-',) self._files = files self._inplace = inplace self._backup = backup self._savestdout = None self._output = None self._filename = None self._lineno = 0 self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = None
except:
except AttributeError:
def close(self): self.sync() try: self.dict.close() except: pass self.dict = 0
import imp
def load_dynamic(self, name, filename, file): if name not in self.ok_dynamic_modules: raise ImportError, "untrusted dynamic module: %s" % name if sys.modules.has_key(name): src = sys.modules[name] else: import imp src = imp.load_dynamic(name, filename, file) dst = self.copy_except(src, []) return dst