rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
class M2(object, D):
class M2(D, object):
def all_method(self): return "D b"
vereq(M2.__mro__, (M2, object, D, C))
vereq(M2.__mro__, (M2, D, C, object))
def all_method(self): return "M2 b"
class M3(M1, object, M2):
class M3(M1, M2, object):
def all_method(self): return "M2 b"
class F(D, E): pass vereq(F().spam(), "B") vereq(F().boo(), "B") vereq(F.__mro__, (F, D, E, B, C, A, object)) class G(E, D): pass vereq(G().spam(), "B") vereq(G().boo(), "C") vereq(G.__mro__, (G, E, D, C, B, A, object))
try: class F(D, E): pass except TypeError: pass else: raise TestFailed, "expected MRO order disagreement (F)" try: class G(E, D): pass except TypeError: pass else: raise TestFailed, "expected MRO order disagreement (G)" def ex5(): if verbose: print "Testing ex5 from C3 switch discussion..." class A(object): pass cla...
def boo(self): return "C"
class C3(C1, C2): __slots__ = [] class C4(C2, C1): __slots__ = []
def slotspecials(): if verbose: print "Testing __dict__ and __weakref__ in __slots__..." class D(object): __slots__ = ["__dict__"] a = D() verify(hasattr(a, "__dict__")) verify(not hasattr(a, "__weakref__")) a.foo = 42 vereq(a.__dict__, {"foo": 42}) class W(object): __slots__ = ["__weakref__"] a = W() verify(hasattr(...
class X(A,B,C,D):
class X(D,B,C,A):
def mro(cls): L = type.mro(cls) L.reverse() return L
pathlist = os.environ['PATH'].split(':')
pathlist = os.environ['PATH'].split(os.pathsep)
def msg(str): sys.stderr.write(str + '\n')
except:
except OSError:
def _run_child(self, cmd): if isinstance(cmd, types.StringTypes): cmd = ['/bin/sh', '-c', cmd] for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1)
"conjoin": conjoin_tests}
"conjoin": conjoin_tests, "weakref": weakref_tests, }
>>> def gencopy(iterator):
"contact_email", "licence", "classifiers",
"contact_email", "license", "classifiers",
def is_pure (self): return (self.has_pure_modules() and not self.has_ext_modules() and not self.has_c_libraries())
flags = 0x57
flags = 0x07
def _StandardPutFile(prompt, default=None): args = {} flags = 0x57 if prompt: args['message'] = prompt args['preferenceKey'] = 'PyMC' if _movablemodal: args['eventProc'] = None try: rr = Nav.NavPutFile(args) good = 1 except Nav.error, arg: good = 0 fss = macfs.FSSpec(':cancelled') else: fss = rr.selection[0] return fss...
_curfolder = macfs.FSSpec(":")
rv = None
def _SetFolder(folder): global _curfolder if _curfolder: rv = _curfolder else: _curfolder = macfs.FSSpec(":") _curfolder = macfs.FSSpec(folder) return rv
flags = 0x57
flags = 0x17
def _GetDirectory(prompt=None): args = {} flags = 0x57 if prompt: args['message'] = prompt args['preferenceKey'] = 'PyMC' if _movablemodal: args['eventProc'] = None try: rr = Nav.NavChooseFolder(args) good = 1 except Nav.error, arg: good = 0 fss = macfs.FSSpec(':cancelled') else: fss = rr.selection[0] return fss, good
if h[0] == 'P' and h[1] in '123456' and h[2] in ' \t\n\r':
if len(h) >= 3 and \ h[0] == 'P' and h[1] in '123456' and h[2] in ' \t\n\r':
def test_pnm(h, f): # PBM, PGM, PPM (portable {bit,gray,pix}map; together portable anymap) if h[0] == 'P' and h[1] in '123456' and h[2] in ' \t\n\r': return 'pnm'
moddir = os.path.join(os.getcwd(), 'Modules', srcdir)
moddir = os.path.join(os.getcwd(), srcdir, 'Modules')
def build_extensions(self):
input_charset = input_charset.lower()
input_charset = unicode(input_charset, 'ascii').lower()
def __init__(self, input_charset=DEFAULT_CHARSET): # RFC 2046, $4.1.2 says charsets are not case sensitive input_charset = input_charset.lower() # Set the input charset after filtering through the aliases self.input_charset = ALIASES.get(input_charset, input_charset) # We can try to guess which encoding and conversion ...
danger = [ x for x in tokens if x[0] == token.NAME and x[1] != 'n' ] if danger: raise ValueError, 'dangerous expression'
try: danger = [ x for x in tokens if x[0] == token.NAME and x[1] != 'n' ] except tokenize.TokenError: raise ValueError, \ 'plural forms expression error, maybe unbalanced parenthesis' else: if danger: raise ValueError, 'plural forms expression could be dangerous'
def c2py(plural): """ Gets a C expression as used in PO files for plural forms and returns a Python lambda function that implements an equivalent expression. """ # Security check, allow only the "n" identifier from StringIO import StringIO import token, tokenize tokens = tokenize.generate_tokens(StringIO(plural).readli...
expr = re.compile(r'\![^=]') plural = expr.sub(' not ', plural)
expr = re.compile(r'\!([^=])') plural = expr.sub(' not \\1', plural)
def c2py(plural): """ Gets a C expression as used in PO files for plural forms and returns a Python lambda function that implements an equivalent expression. """ # Security check, allow only the "n" identifier from StringIO import StringIO import token, tokenize tokens = tokenize.generate_tokens(StringIO(plural).readli...
if len(stack) == 0:
if len(stack) == 1:
def repl(x): return "test(%s, %s, %s)" % (x.group(1), x.group(2), expr.sub(repl, x.group(3)))
if mlen == 0 and tmsg.lower().startswith('project-id-version:'):
if mlen == 0:
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endia...
if len(sys.argv) != 2: sys.stderr.write('usage: telnet hostname\n')
if len(sys.argv) < 2: sys.stderr.write('usage: telnet hostname [port]\n')
def main(): if len(sys.argv) != 2: sys.stderr.write('usage: telnet hostname\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:...
s.connect(host, port)
s.connect((host, port))
def main(): if len(sys.argv) != 2: sys.stderr.write('usage: telnet hostname\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:...
import os,sys
import os,sys,copy
# dlltool --dllname python15.dll --def python15.def \
gcc_version = None dllwrap_version = None ld_version = None
obj_extension = ".o" static_lib_extension = ".a" shared_lib_extension = ".dll" static_lib_format = "lib%s%s" shared_lib_format = "%s%s" exe_extension = ".exe"
# dlltool --dllname python15.dll --def python15.def \
if check_config_h()<=0:
check_result = check_config_h() self.debug_print("Python's GCC status: %s" % check_result) if check_result[:2] <> "OK":
def __init__ (self, verbose=0, dry_run=0, force=0):
sys.stderr.write(self.compiler_type + ": gcc %s, ld %s, dllwrap %s\n" %
self.debug_print(self.compiler_type + ": gcc %s, ld %s, dllwrap %s\n" %
def __init__ (self, verbose=0, dry_run=0, force=0):
extra_preargs = list(extra_preargs or []) libraries = list(libraries or [])
extra_preargs = copy.copy(extra_preargs or []) libraries = copy.copy(libraries or [])
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None): # use separate copies, so can modify the lists extra_preargs = list(extra_preargs or []) librar...
return 2
return "OK, python was compiled with GCC"
def check_config_h(): """Checks if the GCC compiler is mentioned in config.h. If it is not, compiling probably doesn't work. """ # return values # 2: OK, python was compiled with GCC # 1: OK, python's config.h mentions __GCC__ # 0: uncertain, because we couldn't check it # -1: probably not OK, because we didn't fou...
return -1 else: return 1
return "not OK, because we didn't found __GCC__ in config.h" else: return "OK, python's config.h mentions __GCC__"
# is somewhere a #ifdef __GNUC__ or something similar
return 0
return "uncertain, because we couldn't check it"
# is somewhere a #ifdef __GNUC__ or something similar
Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, default, disabledforeground, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, state, takefocus, text, textvariable, underl...
STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, repeatdelay, repeatinterval, takefocus, text, textvariable, underline, wraplength WIDG...
def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER.
Valid resource names: anchor, background, bd, bg, bitmap, borderwidth, cursor, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, takefocus, text, textvariable, underline, width, wraplength."""
STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground, highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS height,...
def __init__(self, master=None, cnf={}, **kw): """Construct a label widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground,...
STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xsc...
def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER.
if o == '-b':
elif o == '-b':
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t...
if o == '-t':
elif o == '-t':
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t...
if o == '-s':
elif o == '-s':
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t...
[3:] intact. [0] = Time that needs to be charged to the parent frame's function. It is used so that a function call will not have to access the timing data for the parent frame. [1] = Total time spent in this frame's function, excluding time in subfunctions [2] = Cumulative time spent in this frame's function, includi...
[-2:] intact (frame and previous tuple). In case an internal error is detected, the -3 element is used as the function name. [ 0] = Time that needs to be charged to the parent frame's function. It is used so that a function call will not have to access the timing data for the parent frame. [ 1] = Total time spent in ...
def _get_time_times(timer=os.times): t = timer() return t[0] + t[1]
self.timings[]. The index is always the name stored in self.cur[4].
self.timings[]. The index is always the name stored in self.cur[-3].
def _get_time_times(timer=os.times): t = timer() return t[0] + t[1]
if self.cur and frame.f_back is not self.cur[4]:
if self.cur and frame.f_back is not self.cur[-2]:
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatc...
raise "Bad call", self.cur[3]
raise "Bad call", self.cur[-3]
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatc...
if self.cur and frame.f_back is not self.cur[4]: raise "Bad call[2]", self.cur[3]
if self.cur and frame.f_back is not self.cur[-2]: raise "Bad call[2]", self.cur[-3]
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatc...
if frame is not self.cur[4]: if frame is self.cur[4].f_back: self.trace_dispatch_return(self.cur[4], 0)
if frame is not self.cur[-2]: if frame is self.cur[-2].f_back: self.trace_dispatch_return(self.cur[-2], 0)
def trace_dispatch_return(self, frame, t): if frame is not self.cur[4]: if frame is self.cur[4].f_back: self.trace_dispatch_return(self.cur[4], 0) else: raise "Bad return", self.cur[3]
raise "Bad return", self.cur[3]
raise "Bad return", self.cur[-3]
def trace_dispatch_return(self, frame, t): if frame is not self.cur[4]: if frame is self.cur[4].f_back: self.trace_dispatch_return(self.cur[4], 0) else: raise "Bad return", self.cur[3]
if self.cur[5]: return
if self.cur[-1]: return
def set_cmd(self, cmd): if self.cur[5]: return # already set self.cmd = cmd self.simulate_call(cmd)
pframe = self.cur[4]
pframe = self.cur[-2]
def simulate_call(self, name): code = self.fake_code('profile', 0, name) if self.cur: pframe = self.cur[4] else: pframe = None frame = self.fake_frame(code, pframe) a = self.dispatch['call'](self, frame, 0) return
while self.cur[5]:
while self.cur[-1]:
def simulate_cmd_complete(self): get_time = self.get_time t = get_time() - self.t while self.cur[5]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self, self.cur[4], t) t = 0 self.t = get_time() - t
a = self.dispatch['return'](self, self.cur[4], t)
a = self.dispatch['return'](self, self.cur[-2], t)
def simulate_cmd_complete(self): get_time = self.get_time t = get_time() - self.t while self.cur[5]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self, self.cur[4], t) t = 0 self.t = get_time() - t
cmdline = "%s %s" % (interp, cmdline)
cmdline = "%s -u %s" % (interp, cmdline)
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scrip...
fi, fo = os.popen2(cmdline)
fi, fo = os.popen2(cmdline, 'b')
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scrip...
def compile_dir(dir, maxlevels=10, ddir=None, force=0):
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None):
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that wil...
py_compile.compile(fullname, None, dfile)
ok = py_compile.compile(fullname, None, dfile)
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that wil...
compile_dir(fullname, maxlevels - 1, dfile, force)
if not compile_dir(fullname, maxlevels - 1, dfile, force, rx): success = 0
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that wil...
opts, args = getopt.getopt(sys.argv[1:], 'lfd:')
opts, args = getopt.getopt(sys.argv[1:], 'lfd:x:')
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu...
print "usage: compileall [-l] [-f] [-d destdir] [directory ...]"
print "usage: python compileall.py [-l] [-f] [-d destdir] " \ "[-s regexp] [directory ...]"
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu...
print "if no directory arguments, -l sys.path is assumed"
print " if no directory arguments, -l sys.path is assumed" print "-x regexp: skip files matching the regular expression regexp" print " the regexp is search for in the full path of the file"
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu...
success = success and compile_dir(dir, maxlevels, ddir, force)
if not compile_dir(dir, maxlevels, ddir, force, rx): success = 0
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu...
sys.exit(not main())
exit_status = not main() sys.exit(exit_status)
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu...
('file://nonsensename/etc/passwd', None, (OSError, socket.error))
('file://nonsensename/etc/passwd', None, (EnvironmentError, socket.error))
def test_file(self): TESTFN = test_support.TESTFN f = open(TESTFN, 'w') try: f.write('hi there\n') f.close() urls = [ 'file:'+sanepathname2url(os.path.abspath(TESTFN)),
if ok:
if fss:
def interact(options, title): """Let the user interact with the dialog""" try: # Try to go to the "correct" dir for GetDirectory os.chdir(options['dir'].as_pathname()) except os.error: pass d = GetNewDialog(DIALOG_ID, -1) htext = d.GetDialogItemAsControl(TITLE_ITEM) SetDialogItemText(htext, title) path_ctl = d.GetDialo...
print >>sys.stderr, name, "exists:", os.path.exists(name)
def expect(got_this, expect_this): if test_support.verbose: print '%s =?= %s ...' % (`got_this`, `expect_this`), if got_this != expect_this: if test_support.verbose: print 'no' raise test_support.TestFailed, 'got %s, but expected %s' %\ (str(got_this), str(expect_this)) else: if test_support.verbose: print 'yes'
try: path = win32api.GetFullPathName(path) except win32api.error: pass
if path: try: path = win32api.GetFullPathName(path) except win32api.error: pass else: path = os.getcwd()
def _abspath(path): if not isabs(path): path = join(os.getcwd(), path) return normpath(path)
if string.find(string.lower(name), 'xml') >= 0:
if string.lower(name) == 'xml':
def parse_proc(self, i): rawdata = self.rawdata end = procclose.search(rawdata, i) if end is None: return -1 j = end.start(0) if illegal.search(rawdata, i+2, j): self.syntax_error('illegal character in processing instruction') res = tagfind.match(rawdata, i+2) if res is None: raise RuntimeError, 'unexpected call to par...
assert re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx') == 'xxxx'
assert re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx') == 'xxxx'
def bump_num(matchobj):
m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?',each)
def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ self.esmtp_features = {} self.putcmd("ehlo", name or self.local_hostname) (code,msg)=self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exc...
if ext in self.swig_ext():
if ext == ".i":
def swig_sources (self, sources):
swig_files.append(source)
swig_sources.append(source)
def swig_sources (self, sources):
if not swig_files:
if not swig_sources:
def swig_sources (self, sources):
d = dict(items={})
d = dict({})
def dict_constructor(): if verbose: print "Testing dict constructor ..." d = dict() vereq(d, {}) d = dict({}) vereq(d, {}) d = dict(items={}) vereq(d, {}) d = dict({1: 2, 'a': 'b'}) vereq(d, {1: 2, 'a': 'b'}) vereq(d, dict(d.items())) vereq(d, dict(items=d.iteritems())) for badarg in 0, 0L, 0j, "0", [0], (0,): try: dic...
vereq(d, dict(items=d.iteritems()))
vereq(d, dict(d.iteritems())) d = dict({'one':1, 'two':2}) vereq(d, dict(one=1, two=2)) vereq(d, dict(**d)) vereq(d, dict({"one": 1}, two=2)) vereq(d, dict([("two", 2)], one=1)) vereq(d, dict([("one", 100), ("two", 200)], **d)) verify(d is not dict(**d))
def dict_constructor(): if verbose: print "Testing dict constructor ..." d = dict() vereq(d, {}) d = dict({}) vereq(d, {}) d = dict(items={}) vereq(d, {}) d = dict({1: 2, 'a': 'b'}) vereq(d, {1: 2, 'a': 'b'}) vereq(d, dict(d.items())) vereq(d, dict(items=d.iteritems())) for badarg in 0, 0L, 0j, "0", [0], (0,): try: dic...
try: dict(senseless={}) except TypeError: pass else: raise TestFailed("no TypeError from dict(senseless={})")
def dict_constructor(): if verbose: print "Testing dict constructor ..." d = dict() vereq(d, {}) d = dict({}) vereq(d, {}) d = dict(items={}) vereq(d, {}) d = dict({1: 2, 'a': 'b'}) vereq(d, {1: 2, 'a': 'b'}) vereq(d, dict(d.items())) vereq(d, dict(items=d.iteritems())) for badarg in 0, 0L, 0j, "0", [0], (0,): try: dic...
d = dict(items=Mapping())
d = dict(Mapping())
def dict_constructor(): if verbose: print "Testing dict constructor ..." d = dict() vereq(d, {}) d = dict({}) vereq(d, {}) d = dict(items={}) vereq(d, {}) d = dict({1: 2, 'a': 'b'}) vereq(d, {1: 2, 'a': 'b'}) vereq(d, dict(d.items())) vereq(d, dict(items=d.iteritems())) for badarg in 0, 0L, 0j, "0", [0], (0,): try: dic...
vereq(dict(items={1: 2}), {1: 2})
def keywords(): if verbose: print "Testing keyword args to basic type constructors ..." vereq(int(x=1), 1) vereq(float(x=2), 2.0) vereq(long(x=3), 3L) vereq(complex(imag=42, real=666), complex(666, 42)) vereq(str(object=500), '500') vereq(unicode(string='abc', errors='strict'), u'abc') vereq(tuple(sequence=range(3)), (...
tuple, list, dict, file):
tuple, list, file):
def keywords(): if verbose: print "Testing keyword args to basic type constructors ..." vereq(int(x=1), 1) vereq(float(x=2), 2.0) vereq(long(x=3), 3L) vereq(complex(imag=42, real=666), complex(666, 42)) vereq(str(object=500), '500') vereq(unicode(string='abc', errors='strict'), u'abc') vereq(tuple(sequence=range(3)), (...
if type(url) == Types.StringType:
if type(url) == types.StringType:
def checkonly(package, url, version, verbose=0): if verbose >= VERBOSE_EACHFILE: print '%s:'%package if type(url) == Types.StringType: ok, newversion, fp = _check1version(package, url, version, verbose) else: for u in url: ok, newversion, fp = _check1version(package, u, version, verbose) if ok >= 0 and verbose < VERBOS...
def _test():
def test_main():
def _test(): threads = [] print "Creating" for i in range(NUM_THREADS): t = TempFileGreedy() threads.append(t) t.start() print "Starting" startEvent.set() print "Reaping" ok = errors = 0 for t in threads: t.join() ok += t.ok_count errors += t.error_count if t.error_count: print '%s errors:\n%s' % (t.getName(), t.err...
_test()
test_main()
def _test(): threads = [] print "Creating" for i in range(NUM_THREADS): t = TempFileGreedy() threads.append(t) t.start() print "Starting" startEvent.set() print "Reaping" ok = errors = 0 for t in threads: t.join() ok += t.ok_count errors += t.error_count if t.error_count: print '%s errors:\n%s' % (t.getName(), t.err...
def handle(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ self.raw_requestline = self.rfile.readline()
def parse_request(self): """Parse a request (internal). The request should be stored in self.raw_request; the results are in self.command, self.path, self.request_version and self.headers. Return value is 1 for success, 0 for failure; on failure, an error is sent back. """
def handle(self): """Handle a single HTTP request.
return
return 0
def handle(self): """Handle a single HTTP request.
mname = 'do_' + command
return 1 def handle(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ self.raw_requestline = self.rfile.readline() if not self.parse_request(): return mname = 'do_' +...
def handle(self): """Handle a single HTTP request.
self.send_error(501, "Unsupported method (%s)" % `command`)
self.send_error(501, "Unsupported method (%s)" % `self.command`)
def handle(self): """Handle a single HTTP request.
upp_dispose_handler = NewWENewObjectProc(my_dispose_handler); upp_draw_handler = NewWENewObjectProc(my_draw_handler); upp_click_handler = NewWENewObjectProc(my_click_handler);
upp_dispose_handler = NewWEDisposeObjectProc(my_dispose_handler); upp_draw_handler = NewWEDrawObjectProc(my_draw_handler); upp_click_handler = NewWEClickObjectProc(my_click_handler);
def outputCheckNewArg(self): Output("""if (itself == NULL) { Py_INCREF(Py_None); return Py_None; }""")
if ( selector == weNewHandler ) handler = upp_new_handler; else if ( selector == weDisposeHandler ) handler = upp_dispose_handler; else if ( selector == weDrawHandler ) handler = upp_draw_handler; else if ( selector == weClickHandler ) handler = upp_click_handler;
if ( selector == weNewHandler ) handler = (UniversalProcPtr)upp_new_handler; else if ( selector == weDisposeHandler ) handler = (UniversalProcPtr)upp_dispose_handler; else if ( selector == weDrawHandler ) handler = (UniversalProcPtr)upp_draw_handler; else if ( selector == weClickHandler ) handler = (UniversalProcPtr)up...
def outputCheckNewArg(self): Output("""if (itself == NULL) { Py_INCREF(Py_None); return Py_None; }""")
def makefile(self, mode):
def makefile(self, mode, bufsize=None): """Return a readable file-like object with data from socket. This method offers only partial support for the makefile interface of a real socket. It only supports modes 'r' and 'rb' and the bufsize argument is ignored. The returned object contains *all* of the file data """
def makefile(self, mode): # hopefully, never have to write if mode != 'r' and mode != 'rb': raise UnimplementedFileMode()
opt_name = string.translate(opt_name, longopt_xlate) val = getattr(self, opt_name)
if self.negative_opt.has_key(opt_name): opt_name = string.translate(self.negative_opt[opt_name], longopt_xlate) val = not getattr(self, opt_name) else: opt_name = string.translate(opt_name, longopt_xlate) val = getattr(self, opt_name)
def dump_dirs (self, msg): if DEBUG: from distutils.fancy_getopt import longopt_xlate print msg + ":" for opt in self.user_options: opt_name = opt[0] if opt_name[-1] == "=": opt_name = opt_name[0:-1] opt_name = string.translate(opt_name, longopt_xlate) val = getattr(self, opt_name) print " %s: %s" % (opt_name, val)
attempdirs = ['/usr/tmp', '/tmp', pwd]
attempdirs = ['/var/tmp', '/usr/tmp', '/tmp', pwd]
def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/usr/tmp', '/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') e...
(script, type) = self.tk.splitlist( self.tk.call('after', 'info', id))
data = self.tk.call('after', 'info', id) script = self.tk.splitlist(data)[0]
def after_cancel(self, id): """Cancel scheduling of function identified with ID.
@bigmemtest(minsize=_2G, memuse=8)
@bigmemtest(minsize=_2G, memuse=9)
def test_repr_large(self, size): return self.basic_test_repr(size)
@bigmemtest(minsize=_2G + 10, memuse=8)
@bigmemtest(minsize=_2G + 10, memuse=9)
def test_index(self, size): l = [1L, 2L, 3L, 4L, 5L] * (size // 5) self.assertEquals(l.index(1), 0) self.assertEquals(l.index(5, size - 5), size - 1) self.assertEquals(l.index(5, size - 5, size), size - 1) self.assertRaises(ValueError, l.index, 1, size - 4, size) self.assertRaises(ValueError, l.index, 6L)
except (ImportError, AttributeError): def _set_cloexec(fd): pass
def _set_cloexec(fd): flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) if flags >= 0: # flags read successfully, modify flags |= _fcntl.FD_CLOEXEC _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value == output and type(value) is type(output):
value = f(*args) self.assertEqual(output, value) self.assert_(type(output) is type(value))
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, repr(output)), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value == output and type(value) is type(output): # if the original i...
try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] if value is input: if verbose: print 'no' print '*',f, `input`, `output`, `value` return if value != output or type(value) is not type(output): if verbose: print 'no' print '*',f, `input`, `output`, `value` if e...
f = getattr(input, method) value = f(*args) self.assertEqual(output, value) self.assert_(input is not value) def test_capitalize(self): self.checkmethod('capitalize', u' hello ', u' hello ') self.checkmethod('capitalize', u'Hello ', u'Hello ') self.checkmethod('capitalize', u'hello ', u'Hello ') self.checkmethod('capi...
def __repr__(self): return 'usub(%r)' % unicode.__repr__(self)
return None codecs.register(search_function) self.assertRaises(TypeError, "hello".decode, "test.unicode1") self.assertRaises(TypeError, unicode, "hello", "test.unicode2") self.assertRaises(TypeError, u"hello".encode, "test.unicode1") self.assertRaises(TypeError, u"hello".encode, "test.unicode2") import imp self.assert...
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
else: pass verify('...%(foo)s...' % {'foo':u"abc"} == u'...abc...') verify('...%(foo)s...' % {'foo':"abc"} == '...abc...') verify('...%(foo)s...' % {u'foo':"abc"} == '...abc...') verify('...%(foo)s...' % {u'foo':u"abc"} == u'...abc...') verify('...%(foo)s...' % {u'foo':u"abc",'def':123} == u'...abc...') verify('......
out = BitBucket() print >>out, u'abc' print >>out, u'abc', u'def' print >>out, u'abc', 'def' print >>out, 'abc', u'def' print >>out, u'abc\n' print >>out, u'abc\n', print >>out, u'abc\n', print >>out, u'def\n' print >>out, u'def\n' def test_mul(self): self.checkmethod('__mul__', u'abc', u'', -1) self.checkmethod('__mu...
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
verify(inc(1) == 2)
verify(inc(1) == 11)
def adder(y): return global_nest_x + y
if value.sign == 1: self._sign = 0 else: self._sign = 1
self._sign = value.sign
def __new__(cls, value="0", context=None): """Create a decimal point instance.
diff = cmp(abs(op1), abs(op2))
def __add__(self, other, context=None): """Returns self + other.
if diff == 0:
if op1.int == op2.int:
def __add__(self, other, context=None): """Returns self + other.
if diff < 0:
if op1.int < op2.int:
def __add__(self, other, context=None): """Returns self + other.
if op1.sign == -1: result.sign = -1
if op1.sign == 1: result.sign = 1
def __add__(self, other, context=None): """Returns self + other.
result.sign = 1
result.sign = 0
def __add__(self, other, context=None): """Returns self + other.