rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
def tearDown(self): GettextBaseTest.tearDown(self) | def setUp(self): GettextBaseTest.setUp(self) self.localedir = os.curdir self.mofile = MOFILE gettext.install('gettext', self.localedir) |
|
def tearDown(self): GettextBaseTest.tearDown(self) | def tearDown(self): GettextBaseTest.tearDown(self) |
|
self.build_temp, | self.implib_dir, | def msvc_prelink_hack (self, sources, ext, extra_args): |
value = value[:m.start()] + done[n] + after | value = value[:m.start()] + str(done[n]) + after | def parse_makefile(fn, g=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ from distutils.text_file import TextFile fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1) if g is None: g = {} done = {} notdone = {} while 1: line = fp.readline() if line is None: # eof break m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here while notdone: for name in notdone.keys(): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] fp.close() # save the results in the global dictionary g.update(done) return g |
except ValueError: pass done[name] = string.strip(value) | except ValueError: done[name] = string.strip(value) else: done[name] = value | def parse_makefile(fn, g=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ from distutils.text_file import TextFile fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1) if g is None: g = {} done = {} notdone = {} while 1: line = fp.readline() if line is None: # eof break m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here while notdone: for name in notdone.keys(): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] fp.close() # save the results in the global dictionary g.update(done) return g |
while n > 0 and line[n-1] in (' ', '\t'): | while n > 0 and line[n-1] in " \t\r": | def decode(input, output): """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods.""" new = '' while 1: line = input.readline() if not line: break i, n = 0, len(line) if n > 0 and line[n-1] == '\n': partial = 0; n = n-1 # Strip trailing whitespace while n > 0 and line[n-1] in (' ', '\t'): n = n-1 else: partial = 1 while i < n: c = line[i] if c != ESCAPE: new = new + c; i = i+1 elif i+1 == n and not partial: partial = 1; break elif i+1 < n and line[i+1] == ESCAPE: new = new + ESCAPE; i = i+2 elif i+2 < n and ishex(line[i+1]) and ishex(line[i+2]): new = new + chr(unhex(line[i+1:i+3])); i = i+3 else: # Bad escape sequence -- leave it in new = new + c; i = i+1 if not partial: output.write(new + '\n') new = '' if new: output.write(new) |
if neg_opt.has_key(option): | is_string = type(value) is StringType if neg_opt.has_key(option) and is_string: | def _set_command_options (self, command_obj, option_dict=None): """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command'). |
elif option in bool_opts: | elif option in bool_opts and is_string: | def _set_command_options (self, command_obj, option_dict=None): """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command'). |
... >>> x/2 | ... >>> x//2 | >>> def f(x): |
x/2 | x//2 | >>> def f(x): |
... >>> print x/0 | ... >>> print x//0 | >>> def f(x): |
... >>> print 'pre-exception output', x/0 | ... >>> print 'pre-exception output', x//0 | >>> def f(x): |
print 'pre-exception output', x/0 | print 'pre-exception output', x//0 | >>> def f(x): |
... >>> 1/0 | ... >>> 1//0 | >>> def f(x): |
1/0 | 1//0 | >>> def f(x): |
You may override this method in order to use Message parsing on tagged data in RFC822-like formats with special header formats. | You may override this method in order to use Message parsing on tagged data in RFC 2822-like formats with special header formats. | def isheader(self, line): """Determine whether a given line is a legal header. |
"""Determine whether a line is a legal end of RFC-822 headers. You may override this method if your application wants to bend the rules, e.g. to strip trailing whitespace, or to recognize MH template separators ('--------'). For convenience (e.g. for code reading from sockets) a line consisting of \r\n also matches. | """Determine whether a line is a legal end of RFC 2822 headers. You may override this method if your application wants to bend the rules, e.g. to strip trailing whitespace, or to recognize MH template separators ('--------'). For convenience (e.g. for code reading from sockets) a line consisting of \r\n also matches. | def islast(self, line): """Determine whether a line is a legal end of RFC-822 headers. |
You may override this method in order to use Message parsing on tagged data in RFC822-like formats that support embedded comments or free-text data. | You may override this method in order to use Message parsing on tagged data in RFC 2822-like formats that support embedded comments or free-text data. | def iscomment(self, line): """Determine whether a line should be skipped entirely. |
RFC-822 in front of you. | RFC 2822 in front of you. http://www.faqs.org/rfcs/rfc2822.html | def parseaddr(address): """Parse an address into a (realname, mailaddr) tuple.""" a = AddrlistClass(address) list = a.getaddrlist() if not list: return (None, None) else: return list[0] |
If `allowcomments' is non-zero, embedded RFC-822 comments are allowed within the parsed fragment. | If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed within the parsed fragment. | def getdelimited(self, beginchar, endchars, allowcomments = 1): """Parse a header fragment delimited by special characters. |
def getatom(self): """Parse an RFC-822 atom.""" | def getatom(self, atomends=None): """Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).""" | def getatom(self): """Parse an RFC-822 atom.""" atomlist = [''] |
if self.field[self.pos] in self.atomends: | if self.field[self.pos] in atomends: | def getatom(self): """Parse an RFC-822 atom.""" atomlist = [''] |
"""Parse a sequence of RFC-822 phrases. A phrase is a sequence of words, which are in turn either RFC-822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. | """Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. | def getphraselist(self): """Parse a sequence of RFC-822 phrases. |
elif self.field[self.pos] in self.atomends: | elif self.field[self.pos] in self.phraseends: | def getphraselist(self): """Parse a sequence of RFC-822 phrases. |
else: plist.append(self.getatom()) | else: plist.append(self.getatom(self.phraseends)) | def getphraselist(self): """Parse a sequence of RFC-822 phrases. |
xover_lines.append(elem[0], elem[1], elem[2], elem[3], elem[4], elem[5:-2], elem[-2], elem[-1]) | xover_lines.append((elem[0], elem[1], elem[2], elem[3], elem[4], string.split(elem[5]), elem[6], elem[7])) | def xover(self,start,end): resp, lines = self.longcmd('XOVER ' + start + '-' + end) xover_lines = [] for line in lines: elem = string.splitfields(line,"\t") try: xover_lines.append(elem[0], elem[1], elem[2], elem[3], elem[4], elem[5:-2], elem[-2], elem[-1]) except IndexError: raise error_data,line return resp,xover_lines |
if sys.platform[:4] != 'java': int(testme) long(testme) float(testme) oct(testme) hex(testme) else: print "__int__: ()" print "__long__: ()" print "__float__: ()" print "__oct__: ()" print "__hex__: ()" | int(testme) long(testme) float(testme) oct(testme) hex(testme) | def __%(method)s__(self, *args): print "__%(method)s__:", args |
try: hash(C1()) except TypeError: pass else: raise TestFailed, "hash(C1()) should raise an exception" | check_exc("hash(C1())", TypeError) | def __cmp__(self, other): return 0 |
try: hash(C2()) except TypeError: pass else: raise TestFailed, "hash(C2()) should raise an exception" | check_exc("hash(C2())", TypeError) | def __eq__(self, other): return 1 |
Returns a file object; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed. | Returns an object with a file-like interface; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed. | def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", prefix=template, dir=None): """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to os.fdopen (default "w+b"). 'bufsize' -- the buffer size argument to os.fdopen (default -1). The file is created as mkstemp() would do it. Returns a file object; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed. """ if dir is None: dir = gettempdir() if 'b' in mode: flags = _bin_openflags else: flags = _text_openflags # Setting O_TEMPORARY in the flags causes the OS to delete # the file when it is closed. This is only supported by Windows. if _os.name == 'nt': flags |= _os.O_TEMPORARY (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) file = _os.fdopen(fd, mode, bufsize) return _TemporaryFileWrapper(file, name) |
Returns a file object. The file has no name, and will cease to exist when it is closed. | Returns an object with a file-like interface. The file has no name, and will cease to exist when it is closed. | def TemporaryFile(mode='w+b', bufsize=-1, suffix="", prefix=template, dir=None): """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'directory' -- as for mkstemp. 'mode' -- the mode argument to os.fdopen (default "w+b"). 'bufsize' -- the buffer size argument to os.fdopen (default -1). The file is created as mkstemp() would do it. |
cur = self._make_iter_cursor() | try: cur = self._make_iter_cursor() except AttributeError: return | def iteritems(self): try: cur = self._make_iter_cursor() |
if not self._dict['Download-URL']: return "%s: This package needs to be installed manually (no Download-URL field)" % _fmtpackagename(self) | if not self._dict.get('Download-URL'): return "%s: This package needs to be installed manually (no Download-URL field)" % self.fullname() | def installSinglePackage(self, output=None): """Download, unpack and install a single package. If output is given it should be a file-like object and it will receive a log of what happened.""" if not self._dict['Download-URL']: return "%s: This package needs to be installed manually (no Download-URL field)" % _fmtpackagename(self) msg = self.downloadPackageOnly(output) if msg: return "%s: download: %s" % (self.fullname(), msg) msg = self.unpackPackageOnly(output) if msg: return "%s: unpack: %s" % (self.fullname(), msg) return self.installPackageOnly(output) |
simple_err(struct.calcsize, 'Q') | simple_err(struct.calcsize, 'Z') | def simple_err(func, *args): try: apply(func, args) except struct.error: pass else: raise TestFailed, "%s%s did not raise struct.error" % ( func.__name__, args) |
def badpack(fmt, arg, got, exp): return def badunpack(fmt, arg, got, exp): return "unpack(%s, %s) -> (%s,) `fmt`, `arg`, `got`, `exp`) isbigendian = struct.pack('=h', 1) == '\0\1' | isbigendian = struct.pack('=i', 1)[0] == chr(0) | def badpack(fmt, arg, got, exp): return |
exit = 'Use Cmd-Q to quit.' | eof = 'Cmd-Q' | def setquit(): """Define new built-ins 'quit' and 'exit'. These are simply strings that display a hint on how to exit. """ if os.sep == ':': exit = 'Use Cmd-Q to quit.' elif os.sep == '\\': exit = 'Use Ctrl-Z plus Return to exit.' else: exit = 'Use Ctrl-D (i.e. EOF) to exit.' __builtin__.quit = __builtin__.exit = exit |
exit = 'Use Ctrl-Z plus Return to exit.' | eof = 'Ctrl-Z plus Return' | def setquit(): """Define new built-ins 'quit' and 'exit'. These are simply strings that display a hint on how to exit. """ if os.sep == ':': exit = 'Use Cmd-Q to quit.' elif os.sep == '\\': exit = 'Use Ctrl-Z plus Return to exit.' else: exit = 'Use Ctrl-D (i.e. EOF) to exit.' __builtin__.quit = __builtin__.exit = exit |
exit = 'Use Ctrl-D (i.e. EOF) to exit.' __builtin__.quit = __builtin__.exit = exit | eof = 'Ctrl-D (i.e. EOF)' class Quitter(object): def __init__(self, name): self.name = name def __repr__(self): return 'Use %s() or %s to exit' % (self.name, eof) def __call__(self, code=None): raise SystemExit(code) __builtin__.quit = Quitter('quit') __builtin__.exit = Quitter('exit') | def setquit(): """Define new built-ins 'quit' and 'exit'. These are simply strings that display a hint on how to exit. """ if os.sep == ':': exit = 'Use Cmd-Q to quit.' elif os.sep == '\\': exit = 'Use Ctrl-Z plus Return to exit.' else: exit = 'Use Ctrl-D (i.e. EOF) to exit.' __builtin__.quit = __builtin__.exit = exit |
str = '%s %s %s\r\n' % (method, url, self._http_vsn_str) try: self.send(str) except socket.error, v: if v[0] != 32 or not self.auto_open: raise self.send(str) | str = '%s %s %s' % (method, url, self._http_vsn_str) self._output(str) | def putrequest(self, method, url, skip_host=0): """Send a request to the server. |
str = '%s: %s\r\n' % (header, value) self.send(str) | str = '%s: %s' % (header, value) self._output(str) | def putheader(self, header, value): """Send a request header line to the server. |
self.send('\r\n') | self._send_output() | def endheaders(self): """Indicate that the last header line has been sent to the server.""" |
return | def test(): """Test this module. A hodge podge of tests collected here, because they have too many external dependencies for the regular test suite. """ import sys import getopt opts, args = getopt.getopt(sys.argv[1:], 'd') dl = 0 for o, a in opts: if o == '-d': dl = dl + 1 host = 'www.python.org' selector = '/' if args[0:]: host = args[0] if args[1:]: selector = args[1] h = HTTP() h.set_debuglevel(dl) h.connect(host) h.putrequest('GET', selector) h.endheaders() status, reason, headers = h.getreply() print 'status =', status print 'reason =', reason print "read", len(h.getfile().read()) print if headers: for header in headers.headers: print header.strip() print # minimal test that code to extract host from url works class HTTP11(HTTP): _http_vsn = 11 _http_vsn_str = 'HTTP/1.1' h = HTTP11('www.python.org') h.putrequest('GET', 'http://www.python.org/~jeremy/') h.endheaders() h.getreply() h.close() if hasattr(socket, 'ssl'): for host, selector in (('sourceforge.net', '/projects/python'), ('dbserv2.theopalgroup.com', '/mediumfile'), ('dbserv2.theopalgroup.com', '/smallfile'), ): print "https://%s%s" % (host, selector) hs = HTTPS() hs.connect(host) hs.putrequest('GET', selector) hs.endheaders() status, reason, headers = hs.getreply() print 'status =', status print 'reason =', reason print "read", len(hs.getfile().read()) print if headers: for header in headers.headers: print header.strip() print return # Test a buggy server -- returns garbled status line. # http://www.yahoo.com/promotions/mom_com97/supermom.html c = HTTPConnection("promotions.yahoo.com") c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") r = c.getresponse() print r.status, r.version lines = r.read().split("\n") print "\n".join(lines[:5]) c = HTTPConnection("promotions.yahoo.com", strict=1) c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") try: r = c.getresponse() except BadStatusLine, err: print "strict mode failed as expected" print err else: print "XXX strict mode should have failed" for strict in 0, 1: h = HTTP(strict=strict) h.connect("promotions.yahoo.com") h.putrequest('GET', "/promotions/mom_com97/supermom.html") h.endheaders() status, reason, headers = h.getreply() assert (strict and status == -1) or status == 200, (strict, status) |
|
result.addError(self,self.__exc_info()) | result.addError(self,sys.exc_info()) | def __call__(self, result=None): if result is None: result = self.defaultTestResult() result.startTest(self) testMethod = getattr(self, self.__testMethodName) try: try: self.setUp() except: result.addError(self,self.__exc_info()) return |
result.addFailure(self,self.__exc_info()) | result.addFailure(self,sys.exc_info()) | def __call__(self, result=None): if result is None: result = self.defaultTestResult() result.startTest(self) testMethod = getattr(self, self.__testMethodName) try: try: self.setUp() except: result.addError(self,self.__exc_info()) return |
def __exc_info(self): """Return a version of sys.exc_info() with the traceback frame minimised; usually the top level of the traceback frame is not needed. """ exctype, excvalue, tb = sys.exc_info() newtb = tb.tb_next if newtb is None: return (exctype, excvalue, tb) return (exctype, excvalue, newtb) | def __exc_info(self): """Return a version of sys.exc_info() with the traceback frame minimised; usually the top level of the traceback frame is not needed. """ exctype, excvalue, tb = sys.exc_info() newtb = tb.tb_next if newtb is None: return (exctype, excvalue, tb) return (exctype, excvalue, newtb) |
|
module = __import__(parts) | parts_copy = parts[:] while parts_copy: try: module = __import__(string.join(parts_copy,'.')) break except ImportError: del parts_copy[-1] if not parts_copy: raise | def loadTestsFromName(self, name, module=None): parts = string.split(name, '.') if module is None: if not parts: raise ValueError, "incomplete test name: %s" % name else: module = __import__(parts) parts = parts[1:] obj = module for part in parts: obj = getattr(obj, part) |
Usage: %(progName)s [options] [test[:(casename|prefix-)]] [...] | Usage: %(progName)s [options] [test] [...] | def run(self, test): "Run the given test case or test suite." result = self._makeResult() startTime = time.time() test(result) stopTime = time.time() timeTaken = float(stopTime - startTime) result.printErrors() self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (run, run == 1 and "" or "s", timeTaken)) self.stream.writeln() if not result.wasSuccessful(): self.stream.write("FAILED (") failed, errored = map(len, (result.failures, result.errors)) if failed: self.stream.write("failures=%d" % failed) if errored: if failed: self.stream.write(", ") self.stream.write("errors=%d" % errored) self.stream.writeln(")") else: self.stream.writeln("OK") return result |
if item > self.len-1 or item < -self.len: raise IndexError if item < 0: item += self.len return strftime(self.format, (item,)*9).capitalize() | if isinstance(item, int): if item < 0: item += self.len if not 0 <= item < self.len: raise IndexError, "out of range" return strftime(self.format, (item,)*9).capitalize() elif isinstance(item, type(slice(0))): return [self[e] for e in range(self.len)].__getslice__(item.start, item.stop) | def __getitem__(self, item): if item > self.len-1 or item < -self.len: raise IndexError if item < 0: item += self.len return strftime(self.format, (item,)*9).capitalize() |
month_name = _localized_name('%B', 12) month_abbr = _localized_name('%b', 12) | month_name = _localized_name('%B', 13) month_abbr = _localized_name('%b', 13) | def __len__(self): return self.len |
linker_so=('%s -mcygwin -mdll' % self.linker_dll)) | linker_so=('%s -mcygwin %s' % (self.linker_dll, shared_option))) | def __init__ (self, verbose=0, dry_run=0, force=0): |
linker_so='%s -mno-cygwin -mdll %s' % (self.linker_dll, entry_point)) | linker_so='%s -mno-cygwin %s %s' % (self.linker_dll, shared_option, entry_point)) | def __init__ (self, verbose=0, dry_run=0, force=0): |
r = gl.getgdesc(GL.GD_BITS_NORM_SNG_RED) g = gl.getgdesc(GL.GD_BITS_NORM_SNG_GREEN) b = gl.getgdesc(GL.GD_BITS_NORM_SNG_BLUE) if (r, g, b) <> (3, 3, 2): raise Error, 'Sorry, can only grab rgb8 on 8-bit Indigo' | if not is_entry_indigo(): raise Error, 'Sorry, can only grab rgb8 on entry level Indigo' | def grab_rgb8(w, h, pf): if gl.getdisplaymode() <> DMRGB: raise Error, 'Sorry, can only grab rgb8 in single-buf rgbmode' if pf <> 1 and pf <> 0: raise Error, 'Sorry, can only grab rgb8 with packfactor 1' r = gl.getgdesc(GL.GD_BITS_NORM_SNG_RED) g = gl.getgdesc(GL.GD_BITS_NORM_SNG_GREEN) b = gl.getgdesc(GL.GD_BITS_NORM_SNG_BLUE) if (r, g, b) <> (3, 3, 2): raise Error, 'Sorry, can only grab rgb8 on 8-bit Indigo' # XXX Dirty Dirty here. # XXX Set buffer to cmap mode, grab image and set it back. # XXX (Shouldn't be necessary???) gl.cmode() gl.gconfig() gl.pixmode(GL.PM_SIZE, 8) data = gl.lrectread(0, 0, w-1, h-1) data = data[:w*h] # BUG FIX for python lrectread gl.RGBmode() gl.gconfig() gl.pixmode(GL.PM_SIZE, 32) return data, None |
self.colormapinited = 1 | def initcolormap(self): if self.format == 'rgb': gl.RGBmode() gl.gconfig() self.colormapinited = 1 gl.RGBcolor(200, 200, 200) # XXX rather light grey gl.clear() return gl.cmode() gl.gconfig() self.skipchrom = 0 if self.offset == 0: self.mask = 0x7ff else: self.mask = 0xfff if not self.quiet: sys.stderr.write('Initializing color map...') self._initcmap() self.colormapinited = 1 self.clear() if not self.quiet: sys.stderr.write(' Done.\n') |
|
self.colormapinited = 1 self.clear() | gl.clear() | def initcolormap(self): if self.format == 'rgb': gl.RGBmode() gl.gconfig() self.colormapinited = 1 gl.RGBcolor(200, 200, 200) # XXX rather light grey gl.clear() return gl.cmode() gl.gconfig() self.skipchrom = 0 if self.offset == 0: self.mask = 0x7ff else: self.mask = 0xfff if not self.quiet: sys.stderr.write('Initializing color map...') self._initcmap() self.colormapinited = 1 self.clear() if not self.quiet: sys.stderr.write(' Done.\n') |
if self.offset == 0: gl.color(0x800) | if gl.getdisplaymode() in (DMRGB, DMRGBDOUBLE): gl.RGBcolor(200, 200, 200) | def clear(self): if not self.colormapinited: raise CallError if self.offset == 0: gl.color(0x800) gl.clear() else: gl.clear() |
else: | return gl.writemask(0xffffffff) gl.clear() def clearto(self, r, g, b): if not self.colormapinited: raise CallError if gl.getdisplaymode() in (DMRGB, DMRGBDOUBLE): gl.RGBcolor(r, g, b) | def clear(self): if not self.colormapinited: raise CallError if self.offset == 0: gl.color(0x800) gl.clear() else: gl.clear() |
return index = self.color0[0] self.fixcolor0 = 1 gl.mapcolor(index, r, g, b) gl.writemask(0xffffffff) gl.clear() gl.gflush() | def clear(self): if not self.colormapinited: raise CallError if self.offset == 0: gl.color(0x800) gl.clear() else: gl.clear() |
|
c0bits, c1bits, c2bits = self.c0bits, self.c1bits, self.c2bits | c0bits = self.c0bits c1bits = self.c1bits c2bits = self.c2bits | def _initcmap(self): convcolor = choose_conversion(self.format) maxbits = gl.getgdesc(GL.GD_BITS_NORM_SNG_CMODE) if maxbits > 11: maxbits = 11 c0bits, c1bits, c2bits = self.c0bits, self.c1bits, self.c2bits if c0bits+c1bits+c2bits > maxbits: if self.fallback and c0bits < maxbits: # Cannot display frames in this mode, use grey self.skipchrom = 1 c1bits = c2bits = 0 convcolor = choose_conversion('grey') else: raise Error, 'Sorry, '+`maxbits`+ \ ' bits max on this machine' maxc0 = 1 << c0bits maxc1 = 1 << c1bits maxc2 = 1 << c2bits if self.offset == 0 and maxbits == 11: offset = 2048 else: offset = self.offset if maxbits <> 11: offset = offset & ((1<<maxbits)-1) # XXX why is this here? # for i in range(512, MAXMAP): # gl.mapcolor(i, 0, 0, 0) # gl.gflush() for c0 in range(maxc0): c0v = c0/float(maxc0-1) for c1 in range(maxc1): if maxc1 == 1: c1v = 0 else: c1v = c1/float(maxc1-1) for c2 in range(maxc2): if maxc2 == 1: c2v = 0 else: c2v = c2/float(maxc2-1) index = offset + c0 + (c1<<c0bits) + \ (c2 << (c0bits+c1bits)) if index < MAXMAP: rv, gv, bv = \ convcolor(c0v, c1v, c2v) r, g, b = int(rv*255.0), \ int(gv*255.0), \ int(bv*255.0) gl.mapcolor(index, r, g, b) gl.gflush() # send the colormap changes to the X server |
self.color0 = None self.fixcolor0 = 0 | def _initcmap(self): convcolor = choose_conversion(self.format) maxbits = gl.getgdesc(GL.GD_BITS_NORM_SNG_CMODE) if maxbits > 11: maxbits = 11 c0bits, c1bits, c2bits = self.c0bits, self.c1bits, self.c2bits if c0bits+c1bits+c2bits > maxbits: if self.fallback and c0bits < maxbits: # Cannot display frames in this mode, use grey self.skipchrom = 1 c1bits = c2bits = 0 convcolor = choose_conversion('grey') else: raise Error, 'Sorry, '+`maxbits`+ \ ' bits max on this machine' maxc0 = 1 << c0bits maxc1 = 1 << c1bits maxc2 = 1 << c2bits if self.offset == 0 and maxbits == 11: offset = 2048 else: offset = self.offset if maxbits <> 11: offset = offset & ((1<<maxbits)-1) # XXX why is this here? # for i in range(512, MAXMAP): # gl.mapcolor(i, 0, 0, 0) # gl.gflush() for c0 in range(maxc0): c0v = c0/float(maxc0-1) for c1 in range(maxc1): if maxc1 == 1: c1v = 0 else: c1v = c1/float(maxc1-1) for c2 in range(maxc2): if maxc2 == 1: c2v = 0 else: c2v = c2/float(maxc2-1) index = offset + c0 + (c1<<c0bits) + \ (c2 << (c0bits+c1bits)) if index < MAXMAP: rv, gv, bv = \ convcolor(c0v, c1v, c2v) r, g, b = int(rv*255.0), \ int(gv*255.0), \ int(bv*255.0) gl.mapcolor(index, r, g, b) gl.gflush() # send the colormap changes to the X server |
|
pass | print '[BasicVinFile.warmcache() not implemented]' | def warmcache(self): pass |
if len(data) < ds: raise EOFError | if len(data) < ds: self.eofseen = 1 raise EOFError | def getnextframedata(self, ds, cs): if self.atframeheader: raise CallError if ds: data = self.fp.read(ds) if len(data) < ds: raise EOFError else: data = '' if cs: cdata = self.fp.read(cs) if len(cdata) < cs: raise EOFerror else: cdata = '' self.atframeheader = 1 self.framecount = self.framecount + 1 return (data, cdata) |
if len(cdata) < cs: raise EOFerror | if len(cdata) < cs: self.eofseen = 1 raise EOFError | def getnextframedata(self, ds, cs): if self.atframeheader: raise CallError if ds: data = self.fp.read(ds) if len(data) < ds: raise EOFError else: data = '' if cs: cdata = self.fp.read(cs) if len(cdata) < cs: raise EOFerror else: cdata = '' self.atframeheader = 1 self.framecount = self.framecount + 1 return (data, cdata) |
self.fp.write(`(t, ds, cs)` + '\n') | data = `(t, ds, cs)` n = len(data) if n < 63: data = data + ' '*(63-n) self.fp.write(data + '\n') | def writeframeheader(self, t, ds, cs): if not self.headerwritten: self.writeheader() if not self.atheader: raise CallError self.fp.write(`(t, ds, cs)` + '\n') self.atheader = 0 |
class VinFile(BasicVinFile, Displayer): | class VinFile(RandomVinFile, Displayer): | def writeframedata(self, data, cdata): if not self.headerwritten or self.atheader: raise CallError if data: self.fp.write(data) if cdata: self.fp.write(cdata) self.atheader = 1 self.framecount = self.framecount + 1 |
return BasicVinFile.initfp(self, fp, filename) | return RandomVinFile.initfp(self, fp, filename) | def initfp(self, fp, filename): self = Displayer.init(self) return BasicVinFile.initfp(self, fp, filename) |
badargs = 10, 10L, 34.5, "abc", {}, [], () for badarg in badargs: | for badarg in OTHERSTUFF: | def test_compare(self): t1 = timedelta(2, 3, 4) t2 = timedelta(2, 3, 4) self.failUnless(t1 == t2) self.failUnless(t1 <= t2) self.failUnless(t1 >= t2) self.failUnless(not t1 != t2) self.failUnless(not t1 < t2) self.failUnless(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) |
for badarg in badargs: | def test_compare(self): t1 = timedelta(2, 3, 4) t2 = timedelta(2, 3, 4) self.failUnless(t1 == t2) self.failUnless(t1 <= t2) self.failUnless(t1 >= t2) self.failUnless(not t1 != t2) self.failUnless(not t1 < t2) self.failUnless(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) |
|
badargs = 10, 10L, 34.5, "abc", {}, [], () for badarg in badargs: | for badarg in OTHERSTUFF: | def test_compare(self): t1 = self.theclass(2, 3, 4) t2 = self.theclass(2, 3, 4) self.failUnless(t1 == t2) self.failUnless(t1 <= t2) self.failUnless(t1 >= t2) self.failUnless(not t1 != t2) self.failUnless(not t1 < t2) self.failUnless(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) |
for badarg in badargs: | def test_compare(self): t1 = self.theclass(2, 3, 4) t2 = self.theclass(2, 3, 4) self.failUnless(t1 == t2) self.failUnless(t1 <= t2) self.failUnless(t1 >= t2) self.failUnless(not t1 != t2) self.failUnless(not t1 < t2) self.failUnless(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) |
|
badargs = (10, 10L, 34.5, "abc", {}, [], ()) if CMP_BUG_FIXED: badargs += (date(1, 1, 1), datetime(1, 1, 1, 1, 1), timedelta(9)) for badarg in badargs: | for badarg in OTHERSTUFF: | def test_comparing(self): args = [1, 2, 3, 4] t1 = self.theclass(*args) t2 = self.theclass(*args) self.failUnless(t1 == t2) self.failUnless(t1 <= t2) self.failUnless(t1 >= t2) self.failUnless(not t1 != t2) self.failUnless(not t1 < t2) self.failUnless(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) |
for badarg in badargs: | def test_comparing(self): args = [1, 2, 3, 4] t1 = self.theclass(*args) t2 = self.theclass(*args) self.failUnless(t1 == t2) self.failUnless(t1 <= t2) self.failUnless(t1 >= t2) self.failUnless(not t1 != t2) self.failUnless(not t1 < t2) self.failUnless(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) |
|
if CMP_BUG_FIXED: t2 = t2.replace(tzinfo=FixedOffset(0, "")) self.assertRaises(TypeError, lambda: t1 == t2) | t2 = t2.replace(tzinfo=FixedOffset(0, "")) self.assertRaises(TypeError, lambda: t1 == t2) | def test_mixed_compare(self): t1 = time(1, 2, 3) t2 = time(1, 2, 3) self.assertEqual(t1, t2) t2 = t2.replace(tzinfo=None) self.assertEqual(t1, t2) t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) if CMP_BUG_FIXED: t2 = t2.replace(tzinfo=FixedOffset(0, "")) self.assertRaises(TypeError, lambda: t1 == t2) |
if CMP_BUG_FIXED: t2 = t2.replace(tzinfo=FixedOffset(0, "")) self.assertRaises(TypeError, lambda: t1 == t2) | t2 = t2.replace(tzinfo=FixedOffset(0, "")) self.assertRaises(TypeError, lambda: t1 == t2) | def test_mixed_compare(self): t1 = datetime(1, 2, 3, 4, 5, 6, 7) t2 = datetime(1, 2, 3, 4, 5, 6, 7) self.assertEqual(t1, t2) t2 = t2.replace(tzinfo=None) self.assertEqual(t1, t2) t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) if CMP_BUG_FIXED: t2 = t2.replace(tzinfo=FixedOffset(0, "")) self.assertRaises(TypeError, lambda: t1 == t2) |
except (AttributeError, Tkinter.TclError): | except (KeyboardInterrupt, SystemExit): raise except Exception: | def __del__(self): try: if self.delete_font: self._call("font", "delete", self.name) except (AttributeError, Tkinter.TclError): pass |
def _handle_long_word(self, chunks, cur_line, cur_len, width): | def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): | def _handle_long_word(self, chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) |
cur_line.append(chunks[0][0:space_left]) chunks[0] = chunks[0][space_left:] | cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] | def _handle_long_word(self, chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) |
cur_line.append(chunks.pop(0)) | cur_line.append(reversed_chunks.pop()) | def _handle_long_word(self, chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) |
if chunks[0].strip() == '' and lines: del chunks[0] | if chunks[-1].strip() == '' and lines: del chunks[-1] | def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] |
l = len(chunks[0]) | l = len(chunks[-1]) | def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] |
cur_line.append(chunks.pop(0)) | cur_line.append(chunks.pop()) | def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] |
if chunks and len(chunks[0]) > width: | if chunks and len(chunks[-1]) > width: | def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] |
self.pos = self.pos + length return self.fp.read(length) | data = self.fp.read(length) self.pos = self.fp.tell() return data | def read(self, length = None): if self.pos >= self.stop: return '' remaining = self.stop - self.pos if length is None or length < 0: length = remaining elif length > remaining: length = remaining self.fp.seek(self.pos) self.pos = self.pos + length return self.fp.read(length) |
if len(data) < length: length = len(data) self.pos = self.pos + length | self.pos = self.fp.tell() | def readline(self, length = None): if self.pos >= self.stop: return '' if length is None: length = self.stop - self.pos self.fp.seek(self.pos) data = self.fp.readline(length) if len(data) < length: length = len(data) self.pos = self.pos + length return data |
pass | del self.fp | def close(self): pass |
index = self._tclCommands.index(name) del self._tclCommands[index] | try: self._tclCommands.remove(name) except ValueError: pass | def deletecommand(self, name): #print '- Tkinter: deleted command', name self.tk.deletecommand(name) index = self._tclCommands.index(name) del self._tclCommands[index] |
def _bind(self, what, sequence, func, add): | def _bind(self, what, sequence, func, add, needcleanup=1): | def _bind(self, what, sequence, func, add): if func: cmd = ("%sset _tkinter_break [%s %s]\n" 'if {"$_tkinter_break" == "break"} break\n') \ % (add and '+' or '', self._register(func, self._substitute), _string.join(self._subst_format)) apply(self.tk.call, what + (sequence, cmd)) elif func == '': apply(self.tk.call, what + (sequence, func)) else: return apply(self.tk.call, what + (sequence,)) |
self._register(func, self._substitute), | self._register(func, self._substitute, needcleanup), | def _bind(self, what, sequence, func, add): if func: cmd = ("%sset _tkinter_break [%s %s]\n" 'if {"$_tkinter_break" == "break"} break\n') \ % (add and '+' or '', self._register(func, self._substitute), _string.join(self._subst_format)) apply(self.tk.call, what + (sequence, cmd)) elif func == '': apply(self.tk.call, what + (sequence, func)) else: return apply(self.tk.call, what + (sequence,)) |
return self._bind(('bind', 'all'), sequence, func, add) | return self._bind(('bind', 'all'), sequence, func, add, 0) | def bind_all(self, sequence=None, func=None, add=None): return self._bind(('bind', 'all'), sequence, func, add) |
return self._bind(('bind', className), sequence, func, add) | return self._bind(('bind', className), sequence, func, add, 0) | def bind_class(self, className, sequence=None, func=None, add=None): return self._bind(('bind', className), sequence, func, add) |
def _register(self, func, subst=None): | def _register(self, func, subst=None, needcleanup=1): | def _register(self, func, subst=None): f = CallWrapper(func, subst, self).__call__ name = `id(f)` try: func = func.im_func except AttributeError: pass try: name = name + func.__name__ except AttributeError: pass self.tk.createcommand(name, f) if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(name) #print '+ Tkinter created command', name return name |
if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(name) | if needcleanup: if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(name) | def _register(self, func, subst=None): f = CallWrapper(func, subst, self).__call__ name = `id(f)` try: func = func.im_func except AttributeError: pass try: name = name + func.__name__ except AttributeError: pass self.tk.createcommand(name, f) if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(name) #print '+ Tkinter created command', name return name |
two, which is tricky on DOS/Windows and Mac OS.""" if not abspath (pathname): return os.path.join (new_root, pathname) elif os.name == 'posix': return os.path.join (new_root, pathname[1:]) | two, which is tricky on DOS/Windows and Mac OS. """ if os.name == 'posix': if not os.path.isabs (pathname): return os.path.join (new_root, pathname) else: return os.path.join (new_root, pathname[1:]) | def change_root (new_root, pathname): """Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS.""" if not abspath (pathname): return os.path.join (new_root, pathname) elif os.name == 'posix': return os.path.join (new_root, pathname[1:]) elif os.name == 'nt': (root_drive, root_path) = os.path.splitdrive (new_root) (drive, path) = os.path.splitdrive (pathname) raise RuntimeError, "I give up -- not sure how to do this on Windows" elif os.name == 'mac': raise RuntimeError, "no clue how to do this on Mac OS" else: raise DistutilsPlatformError, \ "nothing known about platform '%s'" % os.name |
(root_drive, root_path) = os.path.splitdrive (new_root) | def change_root (new_root, pathname): """Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS.""" if not abspath (pathname): return os.path.join (new_root, pathname) elif os.name == 'posix': return os.path.join (new_root, pathname[1:]) elif os.name == 'nt': (root_drive, root_path) = os.path.splitdrive (new_root) (drive, path) = os.path.splitdrive (pathname) raise RuntimeError, "I give up -- not sure how to do this on Windows" elif os.name == 'mac': raise RuntimeError, "no clue how to do this on Mac OS" else: raise DistutilsPlatformError, \ "nothing known about platform '%s'" % os.name |
|
raise RuntimeError, "I give up -- not sure how to do this on Windows" | if path[0] == '\\': path = path[1:] return os.path.join (new_root, path) | def change_root (new_root, pathname): """Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS.""" if not abspath (pathname): return os.path.join (new_root, pathname) elif os.name == 'posix': return os.path.join (new_root, pathname[1:]) elif os.name == 'nt': (root_drive, root_path) = os.path.splitdrive (new_root) (drive, path) = os.path.splitdrive (pathname) raise RuntimeError, "I give up -- not sure how to do this on Windows" elif os.name == 'mac': raise RuntimeError, "no clue how to do this on Mac OS" else: raise DistutilsPlatformError, \ "nothing known about platform '%s'" % os.name |
fn = os.path.join(fn, os.pardir, os.pardir, "Doc", "index.html") | fn = os.path.join(fn, os.pardir, os.pardir, "pythlp.chm") | def help_dialog(self, event=None): try: helpfile = os.path.join(os.path.dirname(__file__), self.helpfile) except NameError: helpfile = self.helpfile if self.flist: self.flist.open(helpfile) else: self.io.loadfile(helpfile) |
def python_docs(self, event=None): webbrowser.open(self.help_url) | def python_docs(self, event=None): os.startfile(self.help_url) else: def python_docs(self, event=None): webbrowser.open(self.help_url) | def python_docs(self, event=None): webbrowser.open(self.help_url) |
print 'Option', opt, 'require integer argument' | print 'Option', opt, 'requires integer argument' | def main(): global debug, looping, magnify, mindelta, nowait, quiet, regen, speed global threading, xoff, yoff # Parse command line try: opts, args = getopt.getopt(sys.argv[1:], 'M:dlm:nqr:s:tx:y:') except getopt.error, msg: sys.stdout = sys.stderr print 'Error:', msg, '\n' help() sys.exit(2) # Interpret options try: for opt, arg in opts: if opt == '-M': magnify = float(eval(arg)) if opt == '-d': debug = debug + 1 if opt == '-l': looping = 1 if opt == '-m': mindelta = string.atoi(arg) if opt == '-n': nowait = 1 if opt == '-q': quiet = 1 if opt == '-r': regen = string.atoi(arg) if opt == '-s': try: speed = float(eval(arg)) except: sys.stdout = sys.stderr print 'Option -s needs float argument' sys.exit(2) if opt == '-t': try: import thread threading = 1 except ImportError: print 'Sorry, this version of Python', print 'does not support threads:', print '-t ignored' if opt == '-x': xoff = string.atoi(arg) if opt == '-y': yoff = string.atoi(arg) except string.atoi_error: sys.stdout = sys.stderr print 'Option', opt, 'require integer argument' sys.exit(2) # Check validity of certain options combinations if nowait and looping: print 'Warning: -n and -l are mutually exclusive; -n ignored' nowait = 0 if xoff <> None and yoff == None: print 'Warning: -x without -y ignored' if xoff == None and yoff <> None: print 'Warning: -y without -x ignored' # Process all files if not args: args = ['film.video'] sts = 0 for filename in args: sts = (process(filename) or sts) # Exit with proper exit status sys.exit(sts) |
return string.translate(s, _normtable) | return string.lower(string.replace(s, "/", "\\")) | def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all |
'debug_script', | def _test(): import doctest doctest.testmod() |
|
class AnotherDateTimeClass(object): def __cmp__(self, other): return 0 their = AnotherDateTimeClass() | class SomeClass: pass their = SomeClass() self.assertEqual(our == their, False) self.assertEqual(their == our, False) self.assertEqual(our != their, True) self.assertEqual(their != our, True) self.assertRaises(TypeError, lambda: our < their) self.assertRaises(TypeError, lambda: their < our) | def test_mixed_compare(self): our = self.theclass(2000, 4, 5) self.assertRaises(TypeError, cmp, our, 1) self.assertRaises(TypeError, cmp, 1, our) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.