rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
os.setuid(nobody) except os.error: pass os.dup2(self.rfile.fileno(), 0) os.dup2(self.wfile.fileno(), 1) print scriptfile, script, decoded_query os.execve(scriptfile, [script, decoded_query], env) except: self.server.handle_error(self.request, self.client_address) os._exit(127)
try: sys.argv = [scriptfile] if '=' not in decoded_query: sys.argv.append(decoded_query) sys.stdout = self.wfile sys.stdin = self.rfile execfile(scriptfile, {"__name__": "__main__"}) finally: sys.argv = save_argv sys.stdin = save_stdin sys.stdout = save_stdout sys.stderr = save_stderr except SystemExit, sts: self.log_e...
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = string.rfind(rest, '?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = string.find(rest, '/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.tran...
import pwd
try: import pwd except ImportError: return -1
def nobody_uid(): """Internal routine to get nobody's uid""" global nobody if nobody: return nobody import pwd try: nobody = pwd.getpwnam('nobody')[2] except KeyError: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) return nobody
pass
def __getitem__(self, index): return 2*tuple.__getitem__(self, index)
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unic...
pass
def __getitem__(self, index): return 2*str.__getitem__(self, index)
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unic...
tuple2: [(), (1,2,3)], str2: ["", "123"]
tuple2: {(): (), (1, 2, 3): (1, 2, 3)}, str2: {"": "", "123": "112233"}
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unic...
pass inputs[unicode2] = [unicode(), unicode("123")] for func in funcs: for (cls, inps) in inputs.iteritems(): for inp in inps: out = filter(func, cls(inp)) self.assertEqual(inp, out) self.assert_(not isinstance(out, cls))
def __getitem__(self, index): return 2*unicode.__getitem__(self, index) inputs[unicode2] = { unicode(): unicode(), unicode("123"): unicode("112233") } for (cls, inps) in inputs.iteritems(): for (inp, exp) in inps.iteritems(): self.assertEqual( filter(funcs[0], cls(inp)), filter(funcs[1], cls(inp)) ) for func in func...
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unic...
z = zipfile.ZipFile(zip_filename, "wb",
z = zipfile.ZipFile(zip_filename, "w",
def visit (z, dirname, names): for name in names: path = os.path.normpath(os.path.join(dirname, name)) if os.path.isfile(path): z.write(path, path)
Optional keyword arg "name" gives the name of the file; by default use the file's name.
Optional keyword arg "name" gives the name of the test; by default use the file's basename.
def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - ...
name = os.path.split(filename)[-1]
name = os.path.basename(filename)
def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - ...
package The name of a Python package. Text-file paths will be interpreted relative to the directory containing this package. The package may be supplied as a package object or as a dotted package name.
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test cas...
The name of a set-up function. This is called before running the
A set-up function. This is called before running the
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test cas...
The name of a tear-down function. This is called after running the
A tear-down function. This is called after running the
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test cas...
name = os.path.split(path)[-1]
name = os.path.basename(path)
def DocFileTest(path, module_relative=True, package=None, globs=None, **options): if globs is None: globs = {} if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path. if module_relative: package = _normalize_module(package) path = _mod...
The name of a set-up function. This is called before running the
A set-up function. This is called before running the
def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is...
The name of a tear-down function. This is called after running the
A tear-down function. This is called after running the
def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is...
__builtin__.credits = _Printer("credits", "Python development is led by BeOpen PythonLabs (www.pythonlabs.com).")
if sys.platform[:4] == 'java': __builtin__.credits = _Printer( "credits", "Jython is maintained by the Jython developers (www.jython.org).") else: __builtin__.credits = _Printer("credits", """\ Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands for supporting Python development. See www.python....
def __call__(self): self.__setup() prompt = 'Hit Return for more, or q (and Return) to quit: ' lineno = 0 while 1: try: for i in range(lineno, lineno + self.MAXLINES): print self.__lines[i] except IndexError: break else: lineno += self.MAXLINES key = None while key is None: key = raw_input(prompt) if key not in ('', 'q...
ctype = msg.get_content_type() main, sub = ctype.split('/')
main = msg.get_content_maintype() sub = msg.get_content_subtype()
def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_<maintype>_<subtype>(). If there's no handler for the # full MIME type, then dispatch to self._handle_<maintype>(). If # that's missing too, then dispatch to self._writeBody(). ctype = msg.get_content_type() # We...
dict = readmodule_ex(module, path)
dict = _readmodule(module, path)
def readmodule(module, path=[]): '''Backwards compatible interface. Call readmodule_ex() and then only keep Class objects from the resulting dictionary.''' dict = readmodule_ex(module, path) res = {} for key, value in dict.items(): if isinstance(value, Class): res[key] = value return res
def readmodule_ex(module, path=[], inpackage=None):
def readmodule_ex(module, path=[]):
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
return _readmodule(module, path) def _readmodule(module, path, inpackage=None): '''Do the hard work for readmodule[_ex].'''
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
parent = readmodule_ex(package, path, inpackage)
parent = _readmodule(package, path, inpackage)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
return readmodule_ex(submodule, parent['__path__'], package)
return _readmodule(submodule, parent['__path__'], package)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
classstack = []
stack = []
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
if token == 'def':
if tokentype == DEDENT:
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno)
if stack: cur_class = stack[-1][0] if isinstance(cur_class, Class): cur_class._addmethod(meth_name, lineno)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1]
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
dict[class_name] = cur_class classstack.append((cur_class, thisindent))
if not stack: dict[class_name] = cur_class stack.append((cur_class, thisindent))
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
readmodule_ex(mod, path)
_readmodule(mod, path)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
readmodule_ex(mod, path, inpackage)
_readmodule(mod, path, inpackage)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
readmodule_ex(mod)
_readmodule(mod, [])
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
d = readmodule_ex(mod, path, inpackage)
d = _readmodule(mod, path, inpackage)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
if n[0] != '_' and not n in dict:
if n[0] != '_':
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in ...
gui = GUI(Tkinter.Tk()) Tkinter.mainloop()
root = Tkinter.Tk() try: gui = GUI(root) root.mainloop() finally: root.destroy()
def hide(self, event=None): self.stop() self.collapse()
curses.pair_content(curses.COLOR_PAIRS)
curses.pair_content(curses.COLOR_PAIRS - 1)
def module_funcs(stdscr): "Test module-level functions" for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longn...
pp_opts = _gen_preprocess_options (self.macros + macros, self.include_dirs + includes)
pp_opts = gen_preprocess_options (self.macros + macros, self.include_dirs + includes)
def compile (self, sources, macros=None, includes=None):
return self.object_filenames (sources)
def compile (self, sources, macros=None, includes=None):
lib_opts = _gen_lib_options (self.libraries + libraries, self.library_dirs + library_dirs)
lib_opts = gen_lib_options (self.libraries + libraries, self.library_dirs + library_dirs, "-l%s", "-L%s")
def link_shared_object (self, objects, output_filename, libraries=None, library_dirs=None, build_info=None):
def _gen_preprocess_options (macros, includes): pp_opts = [] for macro in macros: if len (macro) == 1: pp_opts.append ("-U%s" % macro[0]) elif len (macro) == 2: if macro[1] is None: pp_opts.append ("-D%s" % macro[0]) else: pp_opts.append ("-D%s=%s" % macro) for dir in includes: pp_opts.append ("-I%s" ...
def _split_command (cmd): """Split a command string up into the progam to run (a string) and the list of arguments; return them as (cmd, arglist).""" args = string.split (cmd) return (args[0], args[1:])
cmd = sys.argv[0]
cmd = os.path.basename(sys.argv[0])
def stopped(): print 'pydoc server stopped'
self.passiveserver = 0
self.passiveserver = 1
def connect(self, host = '', port = 0): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port)''' if host: self.host = host if port: self.port = port self.passiveserver = 0 self.sock = socket.socket(socket.AF_INET, s...
self.compiler = new_compiler (compiler=self.compiler,
self.compiler = new_compiler ( compiler="msvc",
def run (self):
self.precompile_hook()
def build_extensions (self):
self.prelink_hook()
if self.compiler.compiler_type == 'msvc': self.msvc_prelink_hack(sources, ext, extra_args)
def build_extensions (self):
def precompile_hook (self): pass def prelink_hook (self):
def msvc_prelink_hack (self, sources, ext, extra_args):
def find_swig (self): """Return the name of the SWIG executable. On Unix, this is just "swig" -- it should be in the PATH. Tries a bit harder on Windows. """
if self.compiler.compiler_type == 'msvc': def_file = ext.export_symbol_file if def_file is None: source_dir = os.path.dirname (sources[0]) ext_base = (string.split (ext.name, '.'))[-1] def_file = os.path.join (source_dir, "%s.def" % ext_base) if not os.path.exists (def_file): def_file = None if def_file is not None: e...
def_file = ext.export_symbol_file if def_file is None: source_dir = os.path.dirname (sources[0]) ext_base = (string.split (ext.name, '.'))[-1] def_file = os.path.join (source_dir, "%s.def" % ext_base) if not os.path.exists (def_file): def_file = None if def_file is not None: extra_args.append ('/DEF:' + def_file) else...
def prelink_hook (self):
assert "invalid option tuple: %r" % (option,)
raise ValueError, "invalid option tuple: %r" % (option,)
def _grok_option_table (self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {}
verify(tuple(a).__class__ is tuple)
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__(L) return self._rev
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None):
def __init__(self, s, charset=None, maxlinelen=None, header_name=None):
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None): """Create a MIME-compliant header that can contain many languages.
The maximum line length can either be specified by maxlinelen, or you can pass in the name of the header field (e.g. "Subject") to let this class guess the best line length to use to prevent wrapping. The default maxlinelen is 76.
The maximum line length can be specified explicitly via maxlinelen. You can also pass None for maxlinelen and the name of a header field (e.g. "Subject") to let the constructor guess the best line length to use. The default maxlinelen is 76.
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None): """Create a MIME-compliant header that can contain many languages.
self._maxlinelen = maxlinelen if header_name is not None: self.guess_maxlinelen(header_name)
if maxlinelen is None: if header_name is None: self._maxlinelen = MAXLINELEN else: self.guess_maxlinelen(header_name) else: self._maxlinelen = maxlinelen
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None): """Create a MIME-compliant header that can contain many languages.
if charset.encoded_header_len(encoded) < self._maxlinelen:
elen = charset.encoded_header_len(encoded) if elen <= self._maxlinelen:
def _split(self, s, charset): # Split up a header safely for use with encode_chunks. BAW: this # appears to be a private convenience method. splittable = charset.to_splittable(s) encoded = charset.from_splittable(splittable) if charset.encoded_header_len(encoded) < self._maxlinelen: return [(encoded, charset)] else: ...
halfway = len(splittable) // 2
halfway = _intdiv2(len(splittable))
def _split(self, s, charset): # Split up a header safely for use with encode_chunks. BAW: this # appears to be a private convenience method. splittable = charset.to_splittable(s) encoded = charset.from_splittable(splittable) if charset.encoded_header_len(encoded) < self._maxlinelen: return [(encoded, charset)] else: ...
f="&xxx;" g='&
f="&xxx;" g='& i='x?a=b&c=d;' j='&amp;
def test_attr_values_entities(self): """Substitution of entities and charrefs in attribute values""" # SF bug #1452246 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; ' f="&xxx;" g='&#32;&#33;' h='&#500;' i='x?a=b&c=d;'>""", [("starttag", "a", [("b", "<"), ("c", "<>"), ("d", "&lt->"), ("e", "< "), ("f", "&...
("i", "x?a=b&c=d;"), ])])
("i", "x?a=b&c=d;"), ("j", "& ("k", "& ])])
def test_attr_values_entities(self): """Substitution of entities and charrefs in attribute values""" # SF bug #1452246 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; ' f="&xxx;" g='&#32;&#33;' h='&#500;' i='x?a=b&c=d;'>""", [("starttag", "a", [("b", "<"), ("c", "<>"), ("d", "&lt->"), ("e", "< "), ("f", "&...
if not self.untagged_responses.has_key('READ-WRITE') \
if self.untagged_responses.has_key('READ-ONLY') \
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
if self.untagged_responses.has_key('READ-WRITE') \ and self.untagged_responses.has_key('READ-ONLY'): del self.untagged_responses['READ-WRITE']
if self.untagged_responses.has_key('READ-ONLY') \ and not self.is_readonly:
def _command(self, name, *args):
def close(f):
def close(self):
def close(f): self.flush()
ok_builtin_modules = ('array', 'binascii', 'audioop', 'imageop', 'marshal', 'math', 'md5', 'parser', 'regex', 'rotor', 'select',
ok_builtin_modules = ('audioop', 'array', 'binascii', 'cmath', 'errno', 'imageop', 'marshal', 'math', 'md5', 'operator', 'parser', 'regex', 'rotor', 'select',
def reload(self, module, path=None): if path is None and hasattr(module, '__filename__'): head, tail = os.path.split(module.__filename__) path = [os.path.join(head, '')] return ihooks.ModuleImporter.reload(self, module, path)
def s_apply(self, func, *args, **kw):
def s_apply(self, func, args=(), kw=None):
def s_apply(self, func, *args, **kw):
r = apply(func, args, kw)
if kw: r = apply(func, args, kw) else: r = apply(func, args)
def s_apply(self, func, *args, **kw):
verify(cf.get('Long Line', 'foo', raw=1) == 'this line is much, much longer than my editor\nlikes it.') def write(src): print "Testing writing of files..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) output = StringIO.StringIO() cf.write(output) verify(output, """[DEFAULT] foo = anoth...
def basic(src): print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() verify(L == [r'Commented Bar', r'Foo Bar', r'Internationalized Stuff', r'Section\with$weird%characters[' '\t', r'Spacey Bar', ], "unexpected list of section names") ...
"http://www.unicode.org/Public/UNIDATA/" + TESTDATAFILE)
"http://www.unicode.org/Public/3.2-Update/" + TESTDATAFILE)
def test_main(): if skip_expected: raise TestSkipped(TESTDATAFILE + " not found, download from " + "http://www.unicode.org/Public/UNIDATA/" + TESTDATAFILE) part1_data = {} for line in open(TESTDATAFILE): if '#' in line: line = line.split('#')[0] line = line.strip() if not line: continue if line.startswith("@Part"): pa...
self._charset = 'iso-8859-1'
self._charset = None
def __init__(self, fp=None): self._info = {} self._charset = 'iso-8859-1' self._fallback = None if fp is not None: self._parse(fp)
if msg.find('\x00') >= 0: msgid1, msgid2 = msg.split('\x00') tmsg = tmsg.split('\x00') if self._coerce: msgid1 = unicode(msgid1, self._charset) tmsg = [unicode(x, self._charset) for x in tmsg] for i in range(len(tmsg)): catalog[(msgid1, i)] = tmsg[i] else: if self._coerce: msg = unicode(msg, self._charset) tmsg = unic...
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 = {} self.plural = lambda n: int(n != 1) # germanic plural by default buf ...
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 = {} self.plural = lambda n: int(n != 1) # germanic plural by default buf ...
k = match.end(0)
self.__starttag_text = rawdata[start_pos:match.end(1) + 1]
def parse_starttag(self, i): rawdata = self.rawdata if shorttagopen.match(rawdata, i): # SGML shorthand: <tag/data/ == <tag>data</tag> # XXX Can data contain &... (entity or char refs)? # XXX Can data contain < or > (tag characters)? # XXX Can there be whitespace before the first /? match = shorttag.match(rawdata, i) i...
import mimetools, StringIO headers = mimetools.Message(StringIO.StringIO( 'Content-Length: %d\n' % retrlen)) else: headers = noheaders()
headers += "Content-Length: %d\n" % retrlen headers = mimetools.Message(StringIO.StringIO(headers))
def open_ftp(self, url): """Use FTP protocol.""" host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote...
del self._current_context[-1]
self._current_context = self._ns_contexts[-1] del self._ns_contexts[-1]
def endPrefixMapping(self, prefix): del self._current_context[-1]
class XMLFilterBase:
class XMLFilterBase(xmlreader.XMLReader):
def processingInstruction(self, target, data): self._out.write('<?%s %s?>' % (target, data))
def ignorableWhitespace(self, chars, start, end): self._cont_handler.ignorableWhitespace(chars, start, end)
def ignorableWhitespace(self, chars): self._cont_handler.ignorableWhitespace(chars)
def ignorableWhitespace(self, chars, start, end): self._cont_handler.ignorableWhitespace(chars, start, end)
f(1, 2, 3, *UserList([4, 5])
f(1, 2, 3, *UserList([4, 5]))
def h(j=1, a=2, h=3): print j, a, h
if keys:
if random.random() < 0.2: mutate = 0 while 1: newkey = Horrid(random.randrange(100)) if newkey not in target: break target[newkey] = Horrid(random.randrange(100)) keys.append(newkey) mutate = 1 elif keys:
def maybe_mutate(): if not mutate: return if random.random() < 0.5: return if random.random() < 0.5: target, keys = dict1, dict1keys else: target, keys = dict2, dict2keys if keys: i = random.randrange(len(keys)) key = keys[i] del target[key] # CAUTION: don't use keys.remove(key) here. Or do <wink>. The # point is th...
vesion string using the format major.minor.build (or patchlevel).
version string using the format major.minor.build (or patchlevel).
def _norm_version(version,build=''): """ Normalize the version and build strings and return a single vesion string using the format major.minor.build (or patchlevel). """ l = string.split(version,'.') if build: l.append(build) try: ints = map(int,l) except ValueError: strings = l else: strings = map(str,ints) version ...
self.literal = 0
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i ...
if self.fp and not self._filePassed: self.fp.close() self.fp = None
self.close()
def __del__(self): """Call the "close()" method in case the user forgot.""" if self.fp and not self._filePassed: self.fp.close() self.fp = None
sys.stderr.write(py_exc.msg)
sys.stderr.write(py_exc.msg + '\n')
def compile(file, cfile=None, dfile=None, doraise=False): """Byte-compile one Python source file to Python bytecode. Arguments: file: source filename cfile: target filename; defaults to source with 'c' or 'o' appended ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo) dfile: purported filename; defaul...
all = self.db.guess_all_extensions('text/plain', strict=True) all.sort() eq(all, ['.bat', '.c', '.h', '.ksh', '.pl', '.txt'])
unless = self.failUnless all = Set(self.db.guess_all_extensions('text/plain', strict=True)) unless(all >= Set(['.bat', '.c', '.h', '.ksh', '.pl', '.txt']))
def test_guess_all_types(self): eq = self.assertEqual # First try strict all = self.db.guess_all_extensions('text/plain', strict=True) all.sort() eq(all, ['.bat', '.c', '.h', '.ksh', '.pl', '.txt']) # And now non-strict all = self.db.guess_all_extensions('image/jpg', strict=False) all.sort() eq(all, ['.jpg']) # And now...
'tk' + version )
lib_prefix + 'tk' + version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
'tcl' + version )
lib_prefix + 'tcl' + version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
if platform == 'cygwin': x11_inc = find_file('X11/Xlib.h', [], inc_dirs) if x11_inc is None: return
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
libs.append('tk'+version) libs.append('tcl'+version)
libs.append(lib_prefix + 'tk'+ version) libs.append(lib_prefix + 'tcl'+ version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
elif 'r' in how: l_type = FCNTL.F_WRLCK
elif 'r' in how: l_type = FCNTL.F_RDLCK
def lock(self, how, *args):
\s+\w+\s+\w+ \s+\d+ [^/]*
[^/]*
def test_getstatus(self): # This pattern should match 'ls -ld /.' on any posix # system, however perversely configured. pat = r'''d......... # It is a directory. \s+\d+ # It has some number of links. \s+\w+\s+\w+ # It has a user and group, which may # be named anything. \s+\d+ # It has a size. [^/]* ...
import _winreg from _winreg import HKEY_LOCAL_MACHINE try: pathname = _winreg.QueryValueEx(HKEY_LOCAL_MACHINE, \ "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, name)) fp = open(pathname, "rb") stuff = "", "rb", imp.C_EXTENSION return fp, pathname, stuff except _winreg.error: pass
result = _try_registry(name) if result: return result
def find_module(self, name, path): if name in self.excludes: self.msgout(3, "find_module -> Excluded") raise ImportError, name
self.stacksize = findDepth(self.insts)
def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 else: # arg takes 2 bytes pc = pc + 3...
def findDepth(self, insts):
def findDepth(self, insts, debug=0):
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self....
delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth
if debug: print i, delta = self.effect.get(opname, None) if delta is not None:
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self....
if depth > maxDepth: maxDepth = depth
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self....
if delta == 0:
if delta is None:
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self....
if depth < 0: depth = 0
if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self....
return lo + hi * 2
return -(lo + hi * 2)
def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return lo + hi * 2
return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)-1
def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)-1
def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)+2
return self.CALL_FUNCTION(argc)-2
def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)+2
self.file.write(delim + line)
self.file.write(odelim + line)
def read_lines_to_outerboundary(self):
displayname = linkname = name = cgi.escape(name)
displayname = linkname = name
def list_directory(self, path): """Helper to produce a directory listing (absent index.html).
f.write('<li><a href="%s">%s</a>\n' % (linkname, displayname))
f.write('<li><a href="%s">%s</a>\n' % (urllib.quote(linkname), cgi.escape(displayname)))
def list_directory(self, path): """Helper to produce a directory listing (absent index.html).
return id(self)
return hash(id(self))
def __hash__(self, *args): print "__hash__:", args return id(self)
>>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF |
>>> import doctest >>> old = doctest._unittest_reportflags >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doc...
>>> import doctest
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doc...