bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def test(args=[]): if not args: args = [ '/etc/passwd', 'file:/etc/passwd', 'file://localhost/etc/passwd', 'ftp://ftp.python.org/etc/passwd',
def test(args=[]): if not args: args = [ '/etc/passwd', 'file:/etc/passwd', 'file://localhost/etc/passwd', 'ftp://ftp.python.org/etc/passwd',
7,900
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) print (garbage, path) garbage, path = splithost(path or "") print (garbage, path) path, garbage = splitquery(path or "") print (path, garbage) path, garbage = splitattr(path or "") print (path, garbage) suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) garbage, path = splithost(path or "") path, garbage = splitquery(path or "") print (path, garbage) path, garbage = splitattr(path or "") print (path, garbage) suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
7,901
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) print (garbage, path) garbage, path = splithost(path or "") print (garbage, path) path, garbage = splitquery(path or "") print (path, garbage) path, garbage = splitattr(path or "") print (path, garbage) suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) garbage, path = splithost(path or "") path, garbage = splitquery(path or "") print (path, garbage) path, garbage = splitattr(path or "") print (path, garbage) suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
7,902
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) print (garbage, path) garbage, path = splithost(path or "") print (garbage, path) path, garbage = splitquery(path or "") print (path, garbage) path, garbage = splitattr(path or "") print (path, garbage) suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) print (garbage, path) garbage, path = splithost(path or "") print (garbage, path) path, garbage = splitquery(path or "") path, garbage = splitattr(path or "") suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
7,903
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) print (garbage, path) garbage, path = splithost(path or "") print (garbage, path) path, garbage = splitquery(path or "") print (path, garbage) path, garbage = splitattr(path or "") print (path, garbage) suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
def retrieve(self, url, filename=None): url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) print (garbage, path) garbage, path = splithost(path or "") print (garbage, path) path, garbage = splitquery(path or "") path, garbage = splitattr(path or "") suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) fp.close() tfp.close() del fp del tfp return result
7,904
def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False, exclude=False, single=False, randomize=False, fromfile=None, findleaks=False, use_resources=None, trace=False, coverdir='coverage', runleaks=False, huntrleaks=False, verbose2=False): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, use_resources, trace and coverdir) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:wM:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', ]) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-w', '--verbose2'): verbose2 = True elif o in ('-q', '--quiet'): quiet = True; verbose = 0 elif o in ('-g', '--generate'): generate = True elif o in ('-x', '--exclude'): exclude = True elif o in ('-s', '--single'): single = True elif o in ('-r', '--randomize'): randomize = True elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = True elif o in ('-L', '--runleaks'): runleaks = True elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-T', '--coverage'): trace = True elif o in ('-D', '--coverdir'): coverdir = os.path.join(os.getcwd(), a) elif o in ('-N', '--nocoverdir'): coverdir = None elif o in ('-R', '--huntrleaks'): huntrleaks = a.split(':') if len(huntrleaks) != 3: print a, huntrleaks usage(2, '-R takes three colon-separated arguments') if len(huntrleaks[0]) == 0: huntrleaks[0] = 5 else: huntrleaks[0] = int(huntrleaks[0]) if len(huntrleaks[1]) == 0: huntrleaks[1] = 4 else: huntrleaks[1] = int(huntrleaks[1]) if len(huntrleaks[2]) == 0: huntrleaks[2] = "reflog.txt" elif o in ('-M', '--memlimit'): test_support.set_memlimit(a) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = False else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) # XXX Temporary hack to force test_optparse to run immediately # XXX after test_file. This should go away as soon as we fix # XXX whatever it is that's causing that to fail. tests.remove("test_file") tests.insert(tests.index("test_optparse"), "test_file") if trace: import trace tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=False, count=True) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() if trace: # If we're tracing code coverage, then we don't exit with status # if on a false return value from main. tracer.runctx('runtest(test, generate, verbose, quiet, testdir)', globals=globals(), locals=vars()) else: try: ok = runtest(test, generate, verbose, quiet, testdir, huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C print break except: raise if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if verbose2 and bad: print "Re-running failed tests in verbose mode" for test in bad: print "Re-running test %r in verbose mode" % test sys.stdout.flush() try: test_support.verbose = 1 ok = runtest(test, generate, 1, quiet, testdir, huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C print break except: raise if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) if trace: r = tracer.results() r.write_results(show_missing=True, summary=True, coverdir=coverdir) if runleaks: os.system("leaks %d" % os.getpid()) sys.exit(len(bad) > 0)
def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False, exclude=False, single=False, randomize=False, fromfile=None, findleaks=False, use_resources=None, trace=False, coverdir='coverage', runleaks=False, huntrleaks=False, verbose2=False): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, use_resources, trace and coverdir) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:wM:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', ]) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-w', '--verbose2'): verbose2 = True elif o in ('-q', '--quiet'): quiet = True; verbose = 0 elif o in ('-g', '--generate'): generate = True elif o in ('-x', '--exclude'): exclude = True elif o in ('-s', '--single'): single = True elif o in ('-r', '--randomize'): randomize = True elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = True elif o in ('-L', '--runleaks'): runleaks = True elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-T', '--coverage'): trace = True elif o in ('-D', '--coverdir'): coverdir = os.path.join(os.getcwd(), a) elif o in ('-N', '--nocoverdir'): coverdir = None elif o in ('-R', '--huntrleaks'): huntrleaks = a.split(':') if len(huntrleaks) != 3: print a, huntrleaks usage(2, '-R takes three colon-separated arguments') if len(huntrleaks[0]) == 0: huntrleaks[0] = 5 else: huntrleaks[0] = int(huntrleaks[0]) if len(huntrleaks[1]) == 0: huntrleaks[1] = 4 else: huntrleaks[1] = int(huntrleaks[1]) if len(huntrleaks[2]) == 0: huntrleaks[2] = "reflog.txt" elif o in ('-M', '--memlimit'): test_support.set_memlimit(a) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = False else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) # XXX Temporary hack to force test_optparse to run immediately # XXX after test_file. This should go away as soon as we fix # XXX whatever it is that's causing that to fail. tests.remove("test_file") tests.insert(tests.index("test_optparse"), "test_file") if trace: import trace tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=False, count=True) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() if trace: # If we're tracing code coverage, then we don't exit with status # if on a false return value from main. tracer.runctx('runtest(test, generate, verbose, quiet, testdir)', globals=globals(), locals=vars()) else: try: ok = runtest(test, generate, verbose, quiet, testdir, huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C print break except: raise if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if verbose2 and bad: print "Re-running failed tests in verbose mode" for test in bad: print "Re-running test %r in verbose mode" % test sys.stdout.flush() try: test_support.verbose = 1 ok = runtest(test, generate, 1, quiet, testdir, huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C print break except: raise if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) if trace: r = tracer.results() r.write_results(show_missing=True, summary=True, coverdir=coverdir) if runleaks: os.system("leaks %d" % os.getpid()) sys.exit(len(bad) > 0)
7,905
def __init__(self, isjunk=None, a='', b=''): """Construct a SequenceMatcher.
def __init__(self, isjunk=None, a='', b=''): """Construct a SequenceMatcher.
7,906
def __init__(self, isjunk=None, a='', b=''): """Construct a SequenceMatcher.
def __init__(self, isjunk=None, a='', b=''): """Construct a SequenceMatcher.
7,907
def get_close_matches(word, possibilities, n=3, cutoff=0.6): """Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of strings). Optional arg n (default 3) is the maximum number of close matches to return. n must be > 0. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities that don't score at least that similar to word are ignored. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"]) ['apple', 'ape'] >>> import keyword >>> get_close_matches("wheel", keyword.kwlist) ['while'] >>> get_close_matches("apple", keyword.kwlist) [] >>> get_close_matches("accept", keyword.kwlist) ['except'] """ if not n > 0: raise ValueError("n must be > 0: %s" % `n`) if not 0.0 <= cutoff <= 1.0: raise ValueError("cutoff must be in [0.0, 1.0]: %s" % `cutoff`) result = [] s = SequenceMatcher() s.set_seq2(word) for x in possibilities: s.set_seq1(x) if s.real_quick_ratio() >= cutoff and \ s.quick_ratio() >= cutoff and \ s.ratio() >= cutoff: result.append((s.ratio(), x)) # Sort by score. result.sort() # Retain only the best n. result = result[-n:] # Move best-scorer to head of list. result.reverse() # Strip scores. return [x for score, x in result]
def get_close_matches(word, possibilities, n=3, cutoff=0.6): """Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of strings). Optional arg n (default 3) is the maximum number of close matches to return. n must be > 0. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities that don't score at least that similar to word are ignored. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"]) ['apple', 'ape'] >>> import keyword >>> get_close_matches("wheel", keyword.kwlist) ['while'] >>> get_close_matches("apple", keyword.kwlist) [] >>> get_close_matches("accept", keyword.kwlist) ['except'] """ if not n > 0: raise ValueError("n must be > 0: " + `n`) if not 0.0 <= cutoff <= 1.0: raise ValueError("cutoff must be in [0.0, 1.0]: %s" % `cutoff`) result = [] s = SequenceMatcher() s.set_seq2(word) for x in possibilities: s.set_seq1(x) if s.real_quick_ratio() >= cutoff and \ s.quick_ratio() >= cutoff and \ s.ratio() >= cutoff: result.append((s.ratio(), x)) # Sort by score. result.sort() # Retain only the best n. result = result[-n:] # Move best-scorer to head of list. result.reverse() # Strip scores. return [x for score, x in result]
7,908
def get_close_matches(word, possibilities, n=3, cutoff=0.6): """Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of strings). Optional arg n (default 3) is the maximum number of close matches to return. n must be > 0. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities that don't score at least that similar to word are ignored. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"]) ['apple', 'ape'] >>> import keyword >>> get_close_matches("wheel", keyword.kwlist) ['while'] >>> get_close_matches("apple", keyword.kwlist) [] >>> get_close_matches("accept", keyword.kwlist) ['except'] """ if not n > 0: raise ValueError("n must be > 0: %s" % `n`) if not 0.0 <= cutoff <= 1.0: raise ValueError("cutoff must be in [0.0, 1.0]: %s" % `cutoff`) result = [] s = SequenceMatcher() s.set_seq2(word) for x in possibilities: s.set_seq1(x) if s.real_quick_ratio() >= cutoff and \ s.quick_ratio() >= cutoff and \ s.ratio() >= cutoff: result.append((s.ratio(), x)) # Sort by score. result.sort() # Retain only the best n. result = result[-n:] # Move best-scorer to head of list. result.reverse() # Strip scores. return [x for score, x in result]
def get_close_matches(word, possibilities, n=3, cutoff=0.6): """Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of strings). Optional arg n (default 3) is the maximum number of close matches to return. n must be > 0. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities that don't score at least that similar to word are ignored. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"]) ['apple', 'ape'] >>> import keyword >>> get_close_matches("wheel", keyword.kwlist) ['while'] >>> get_close_matches("apple", keyword.kwlist) [] >>> get_close_matches("accept", keyword.kwlist) ['except'] """ if not n > 0: raise ValueError("n must be > 0: %s" % `n`) if not 0.0 <= cutoff <= 1.0: raise ValueError("cutoff must be in [0.0, 1.0]: " + `cutoff`) result = [] s = SequenceMatcher() s.set_seq2(word) for x in possibilities: s.set_seq1(x) if s.real_quick_ratio() >= cutoff and \ s.quick_ratio() >= cutoff and \ s.ratio() >= cutoff: result.append((s.ratio(), x)) # Sort by score. result.sort() # Retain only the best n. result = result[-n:] # Move best-scorer to head of list. result.reverse() # Strip scores. return [x for score, x in result]
7,909
def handle_read (self):
def handle_read (self):
7,910
def handle_read (self):
def handle_read (self):
7,911
def classmethods_in_c(): if verbose: print "Testing C-based class methods..." import xxsubtype as spam a = (1, 2, 3) d = {'abc': 123} x, a1, d1 = spam.spamlist.classmeth(*a, **d) veris(x, None) vereq((spam.spamlist,) + a, a1) vereq(d, d1) x, a1, d1 = spam.spamlist().classmeth(*a, **d) veris(x, None) vereq((spam.spamlist,) + a, a1) vereq(d, d1)
def classmethods_in_c(): if verbose: print "Testing C-based class methods..." import xxsubtype as spam a = (1, 2, 3) d = {'abc': 123} x, a1, d1 = spam.spamlist.classmeth(*a, **d) veris(x, spam.spamlist) vereq(a, a1) vereq(d, d1) x, a1, d1 = spam.spamlist().classmeth(*a, **d) veris(x, spam.spamlist) vereq(a, a1) vereq(d, d1)
7,912
def classmethods_in_c(): if verbose: print "Testing C-based class methods..." import xxsubtype as spam a = (1, 2, 3) d = {'abc': 123} x, a1, d1 = spam.spamlist.classmeth(*a, **d) veris(x, None) vereq((spam.spamlist,) + a, a1) vereq(d, d1) x, a1, d1 = spam.spamlist().classmeth(*a, **d) veris(x, None) vereq((spam.spamlist,) + a, a1) vereq(d, d1)
def classmethods_in_c(): if verbose: print "Testing C-based class methods..." import xxsubtype as spam a = (1, 2, 3) d = {'abc': 123} x, a1, d1 = spam.spamlist.classmeth(*a, **d) veris(x, spam.spamlist) vereq(a, a1) vereq(d, d1) x, a1, d1 = spam.spamlist().classmeth(*a, **d) veris(x, spam.spamlist) vereq(a, a1) vereq(d, d1)
7,913
def __init__(self, name=None, mode="r", fileobj=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ self.name = name
def __init__(self, name=None, mode="r", fileobj=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ self.name = name
7,914
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurence is assumed to be the most up-to-date version. """ self._check() if name not in self.membernames and not self._loaded: self._load() if name not in self.membernames: raise KeyError, "filename %r not found" % name return self._getmember(name)
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurence is assumed to be the most up-to-date version. """ tarinfo = self._getmember(name) if tarinfo is None: raise KeyError, "filename %r not found" % name return self._getmember(name)
7,915
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurence is assumed to be the most up-to-date version. """ self._check() if name not in self.membernames and not self._loaded: self._load() if name not in self.membernames: raise KeyError, "filename %r not found" % name return self._getmember(name)
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurence is assumed to be the most up-to-date version. """ self._check() if name not in self.membernames and not self._loaded: self._load() if name not in self.membernames: raise KeyError, "filename %r not found" % name return self._getmember(name)
7,916
def getnames(self): """Return the members of the archive as a list of their names. It has the same order as the list returned by getmembers(). """ self._check() if not self._loaded: self._load() return self.membernames
def getnames(self): """Return the members of the archive as a list of their names. It has the same order as the list returned by getmembers(). """ self._check() if not self._loaded: self._load() return self.membernames
7,917
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw")
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw")
7,918
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
7,919
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
7,920
def proc_sparse(self, tarinfo): """Analyze a GNU sparse header plus extra headers. """ buf = tarinfo.tobuf() sp = _ringbuffer() pos = 386 lastpos = 0L realpos = 0L # There are 4 possible sparse structs in the # first header. for i in xrange(4): try: offset = int(buf[pos:pos + 12], 8) numbytes = int(buf[pos + 12:pos + 24], 8) except ValueError: break if offset > lastpos: sp.append(_hole(lastpos, offset - lastpos)) sp.append(_data(offset, numbytes, realpos)) realpos += numbytes lastpos = offset + numbytes pos += 24
def proc_sparse(self, tarinfo): """Analyze a GNU sparse header plus extra headers. """ buf = tarinfo.tobuf() sp = _ringbuffer() pos = 386 lastpos = 0L realpos = 0L # There are 4 possible sparse structs in the # first header. for i in xrange(4): try: offset = int(buf[pos:pos + 12], 8) numbytes = int(buf[pos + 12:pos + 24], 8) except ValueError: break if offset > lastpos: sp.append(_hole(lastpos, offset - lastpos)) sp.append(_data(offset, numbytes, realpos)) realpos += numbytes lastpos = offset + numbytes pos += 24
7,921
def _getmember(self, name, tarinfo=None): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ if tarinfo is None: end = len(self.members) else: end = self.members.index(tarinfo)
def _getmember(self, name, tarinfo=None): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ if tarinfo is None: end = len(self.members) else: end = self.members.index(tarinfo)
7,922
def _getmember(self, name, tarinfo=None): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ if tarinfo is None: end = len(self.members) else: end = self.members.index(tarinfo)
def _getmember(self, name, tarinfo=None): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ if tarinfo is None: end = len(self.members) else: end = self.members.index(tarinfo)
7,923
def create_static_lib (self, objects, output_libname, output_dir=None, debug=0):
def create_static_lib (self, objects, output_libname, output_dir=None, debug=0):
7,924
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
7,925
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
7,926
def link_executable (self, objects, output_progname, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None): (objects, output_dir, libraries, library_dirs) = \ self._fix_link_args (objects, output_dir, takes_libs=1, libraries=libraries, library_dirs=library_dirs)
def link_executable (self, objects, output_progname, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None): (objects, output_dir, libraries, library_dirs) = \ self._fix_link_args (objects, output_dir, takes_libs=1, libraries=libraries, library_dirs=library_dirs)
7,927
def link_executable (self, objects, output_progname, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None): (objects, output_dir, libraries, library_dirs) = \ self._fix_link_args (objects, output_dir, takes_libs=1, libraries=libraries, library_dirs=library_dirs)
def link_executable (self, objects, output_progname, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None): (objects, output_dir, libraries, library_dirs) = \ self._fix_link_args (objects, output_dir, takes_libs=1, libraries=libraries, library_dirs=library_dirs)
7,928
>>> def f(x):
>>> def f(x):
7,929
def debug(self): r"""Run the test case without results and without catching exceptions
def debug(self): r"""Run the test case without results and without catching exceptions
7,930
def shortDescription(self): return "Doctest: " + self._dt_test.name
def shortDescription(self): return "Doctest: " + self._dt_test.name
7,931
def copy(src, dst, createpath=0, copydates=1, forcetype=None): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) ifp = open(srcfss.as_pathname(), 'rb') ofp = open(dstfss.as_pathname(), 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = openrf(srcfss.as_pathname(), '*rb') ofp = openrf(dstfss.as_pathname(), '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type = sf.Creator, sf.Type if forcetype != None: df.Type = forcetype df.Flags = (sf.Flags & (kIsStationary|kNameLocked|kHasBundle|kIsInvisible|kIsAlias)) dstfss.SetFInfo(df) if copydates: crdate, mddate, bkdate = srcfss.GetDates() dstfss.SetDates(crdate, mddate, bkdate) touched(dstfss)
def copy(src, dst, createpath=0, copydates=1, forcetype=None): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) ifp = open(srcfss.as_pathname(), 'rb') ofp = open(dstfss.as_pathname(), 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = openrf(srcfss.as_pathname(), '*rb') ofp = openrf(dstfss.as_pathname(), '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type = sf.Creator, sf.Type if forcetype != None: df.Type = forcetype df.Flags = (sf.Flags & (kIsStationary|kNameLocked|kHasBundle|kIsInvisible|kIsAlias)) dstfss.SetFInfo(df) if copydates: crdate, mddate, bkdate = srcfss.GetDates() dstfss.SetDates(crdate, mddate, bkdate) touched(dstfss)
7,932
def copy(src, dst, createpath=0, copydates=1, forcetype=None): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) ifp = open(srcfss.as_pathname(), 'rb') ofp = open(dstfss.as_pathname(), 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = openrf(srcfss.as_pathname(), '*rb') ofp = openrf(dstfss.as_pathname(), '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type = sf.Creator, sf.Type if forcetype != None: df.Type = forcetype df.Flags = (sf.Flags & (kIsStationary|kNameLocked|kHasBundle|kIsInvisible|kIsAlias)) dstfss.SetFInfo(df) if copydates: crdate, mddate, bkdate = srcfss.GetDates() dstfss.SetDates(crdate, mddate, bkdate) touched(dstfss)
def copy(src, dst, createpath=0, copydates=1, forcetype=None): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) ifp = open(src, 'rb') ofp = open(dst, 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = openrf(srcfss.as_pathname(), '*rb') ofp = openrf(dstfss.as_pathname(), '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type = sf.Creator, sf.Type if forcetype != None: df.Type = forcetype df.Flags = (sf.Flags & (kIsStationary|kNameLocked|kHasBundle|kIsInvisible|kIsAlias)) dstfss.SetFInfo(df) if copydates: crdate, mddate, bkdate = srcfss.GetDates() dstfss.SetDates(crdate, mddate, bkdate) touched(dstfss)
7,933
def copy(src, dst, createpath=0, copydates=1, forcetype=None): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) ifp = open(srcfss.as_pathname(), 'rb') ofp = open(dstfss.as_pathname(), 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = openrf(srcfss.as_pathname(), '*rb') ofp = openrf(dstfss.as_pathname(), '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type = sf.Creator, sf.Type if forcetype != None: df.Type = forcetype df.Flags = (sf.Flags & (kIsStationary|kNameLocked|kHasBundle|kIsInvisible|kIsAlias)) dstfss.SetFInfo(df) if copydates: crdate, mddate, bkdate = srcfss.GetDates() dstfss.SetDates(crdate, mddate, bkdate) touched(dstfss)
def copy(src, dst, createpath=0, copydates=1, forcetype=None): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) ifp = open(srcfss.as_pathname(), 'rb') ofp = open(dstfss.as_pathname(), 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = openrf(src, '*rb') ofp = openrf(dst, '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type = sf.Creator, sf.Type if forcetype != None: df.Type = forcetype df.Flags = (sf.Flags & (kIsStationary|kNameLocked|kHasBundle|kIsInvisible|kIsAlias)) dstfss.SetFInfo(df) if copydates: crdate, mddate, bkdate = srcfss.GetDates() dstfss.SetDates(crdate, mddate, bkdate) touched(dstfss)
7,934
typedef struct
typedef struct
7,935
def is_pure (self): return (self.has_pure_modules() and not self.has_ext_modules() and not self.has_c_libraries())
def is_pure (self): return (self.has_pure_modules() and not self.has_ext_modules() and not self.has_c_libraries())
7,936
def addpackers(self): self.packer = MountPacker().init() self.unpacker = MountUnpacker().init('')
def addpackers(self): self.packer = MountPacker().init() self.unpacker = MountUnpacker().init('')
7,937
def mkcred(self, proc): if proc not in (1, 3, 4): # not Mnt/Unmnt/Unmntall return rpc.AUTH_NULL, '' if self.cred == None: self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() return self.cred
def mkcred(self, proc): if proc not in (1, 3, 4): # not Mnt/Unmnt/Unmntall return rpc.AUTH_NULL, '' if self.cred == None: self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() return self.cred
7,938
def test_main(): run_unittest(TemporaryFileTests)
defrun_unittest(StatAttributeTests) test_main():run_unittest(StatAttributeTests) run_unittest(TemporaryFileTests)run_unittest(StatAttributeTests) run_unittest(StatAttributeTests)
7,939
def __init__ (self, attrs=None): """Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in 'attrs' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the 'command_obj' attribute to the empty dictionary; this will be filled in with real command objects by 'parse_command_line()'. """
def __init__ (self, attrs=None): """Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in 'attrs' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the 'command_obj' attribute to the empty dictionary; this will be filled in with real command objects by 'parse_command_line()'. """
7,940
def encode(self, input, final=False): return mbcs_encode(input,self.errors)[0]
def encode(self, input, final=False): return mbcs_encode(input,self.errors)[0]
7,941
def _buffer_decode(self, input, errors, final): return mbcs_decode(input,self.errors,final)
def _buffer_decode(self, input, errors, final): return mbcs_decode(input,self.errors,final)
7,942
def _buffer_decode(self, input, errors, final): return mbcs_decode(input,self.errors,final)
def _buffer_decode(self, input, errors, final): return mbcs_decode(input,self.errors,final)
7,943
def _buffer_decode(self, input, errors, final): return mbcs_decode(input,self.errors,final)
def _buffer_decode(self, input, errors, final): return mbcs_decode(input,self.errors,final)
7,944
def _GetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp fp.seek(-22, 2) # Start of end-of-archive record filesize = fp.tell() + 22 # Get file size endrec = fp.read(22) # Archive must not end with a comment! if endrec[0:4] != stringEndArchive or endrec[-2:] != "\000\000": raise BadZipfile, "File is not a zip file, or ends with a comment" endrec = struct.unpack(structEndArchive, endrec) if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory x = filesize - 22 - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[12]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[13]) x.comment = fp.read(centdir[14]) total = total + centdir[12] + centdir[13] + centdir[14] x.header_offset = centdir[18] + concat x.file_offset = x.header_offset + 30 + centdir[12] + centdir[13] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) fname = fp.read(fheader[10]) if fname != data.filename: raise RuntimeError, \ 'File name in directory "%s" and header "%s" differ.' % ( data.filename, fname)
def _GetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp fp.seek(-22, 2) # Start of end-of-archive record filesize = fp.tell() + 22 # Get file size endrec = fp.read(22) # Archive must not end with a comment! if endrec[0:4] != stringEndArchive or endrec[-2:] != "\000\000": raise BadZipfile, "File is not a zip file, or ends with a comment" endrec = struct.unpack(structEndArchive, endrec) if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory x = filesize - 22 - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[_CD_FILENAME_LENGTH]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[13]) x.comment = fp.read(centdir[14]) total = total + centdir[12] + centdir[13] + centdir[14] x.header_offset = centdir[18] + concat x.file_offset = x.header_offset + 30 + centdir[12] + centdir[13] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) fname = fp.read(fheader[10]) if fname != data.filename: raise RuntimeError, \ 'File name in directory "%s" and header "%s" differ.' % ( data.filename, fname)
7,945
def _GetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp fp.seek(-22, 2) # Start of end-of-archive record filesize = fp.tell() + 22 # Get file size endrec = fp.read(22) # Archive must not end with a comment! if endrec[0:4] != stringEndArchive or endrec[-2:] != "\000\000": raise BadZipfile, "File is not a zip file, or ends with a comment" endrec = struct.unpack(structEndArchive, endrec) if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory x = filesize - 22 - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[12]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[13]) x.comment = fp.read(centdir[14]) total = total + centdir[12] + centdir[13] + centdir[14] x.header_offset = centdir[18] + concat x.file_offset = x.header_offset + 30 + centdir[12] + centdir[13] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) fname = fp.read(fheader[10]) if fname != data.filename: raise RuntimeError, \ 'File name in directory "%s" and header "%s" differ.' % ( data.filename, fname)
def _GetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp fp.seek(-22, 2) # Start of end-of-archive record filesize = fp.tell() + 22 # Get file size endrec = fp.read(22) # Archive must not end with a comment! if endrec[0:4] != stringEndArchive or endrec[-2:] != "\000\000": raise BadZipfile, "File is not a zip file, or ends with a comment" endrec = struct.unpack(structEndArchive, endrec) if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory x = filesize - 22 - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[12]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH]) x.comment = fp.read(centdir[_CD_COMMENT_LENGTH]) total = (total + centdir[_CD_FILENAME_LENGTH] + centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]) x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET] + concat (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) fname = fp.read(fheader[10]) if fname != data.filename: raise RuntimeError, \ 'File name in directory "%s" and header "%s" differ.' % ( data.filename, fname)
7,946
def _GetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp fp.seek(-22, 2) # Start of end-of-archive record filesize = fp.tell() + 22 # Get file size endrec = fp.read(22) # Archive must not end with a comment! if endrec[0:4] != stringEndArchive or endrec[-2:] != "\000\000": raise BadZipfile, "File is not a zip file, or ends with a comment" endrec = struct.unpack(structEndArchive, endrec) if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory x = filesize - 22 - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[12]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[13]) x.comment = fp.read(centdir[14]) total = total + centdir[12] + centdir[13] + centdir[14] x.header_offset = centdir[18] + concat x.file_offset = x.header_offset + 30 + centdir[12] + centdir[13] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) fname = fp.read(fheader[10]) if fname != data.filename: raise RuntimeError, \ 'File name in directory "%s" and header "%s" differ.' % ( data.filename, fname)
def _GetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp fp.seek(-22, 2) # Start of end-of-archive record filesize = fp.tell() + 22 # Get file size endrec = fp.read(22) # Archive must not end with a comment! if endrec[0:4] != stringEndArchive or endrec[-2:] != "\000\000": raise BadZipfile, "File is not a zip file, or ends with a comment" endrec = struct.unpack(structEndArchive, endrec) if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory x = filesize - 22 - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[12]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[13]) x.comment = fp.read(centdir[14]) total = total + centdir[12] + centdir[13] + centdir[14] x.header_offset = centdir[18] + concat x.file_offset = x.header_offset + 30 + centdir[12] + centdir[13] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) data.file_offset = (data.header_offset + 30 + fheader[_FH_FILENAME_LENGTH] + fheader[_FH_EXTRA_FIELD_LENGTH]) fname = fp.read(fheader[_FH_FILENAME_LENGTH]) if fname != data.filename: raise RuntimeError, \ 'File name in directory "%s" and header "%s" differ.' % ( data.filename, fname)
7,947
def __cmp__(self, other): raise RuntimeError, "UserList.__cmp__() is obsolete"
def __cmp__(self, other): raise RuntimeError, "UserList.__cmp__() is obsolete"
7,948
def appendURL(self, url, included=0): """Append packages from the database with the given URL. Only the first database should specify included=0, so the global information (maintainer, description) get stored.""" if url in self._urllist: return self._urllist.append(url) fp = MyURLopener().open(url).fp dict = plistlib.Plist.fromFile(fp) # Test here for Pimp version, etc if not included: self._version = dict.get('Version', '0.1') if self._version != PIMP_VERSION: sys.stderr.write("Warning: database version %s does not match %s\n" % (self._version, PIMP_VERSION)) self._maintainer = dict.get('Maintainer', '') self._description = dict.get('Description', '') self._appendPackages(dict['Packages']) others = dict.get('Include', []) for url in others: self.appendURL(url, included=1)
def appendURL(self, url, included=0): """Append packages from the database with the given URL. Only the first database should specify included=0, so the global information (maintainer, description) get stored.""" if url in self._urllist: return self._urllist.append(url) fp = urllib2.urlopen(url).fp dict = plistlib.Plist.fromFile(fp) # Test here for Pimp version, etc if not included: self._version = dict.get('Version', '0.1') if self._version != PIMP_VERSION: sys.stderr.write("Warning: database version %s does not match %s\n" % (self._version, PIMP_VERSION)) self._maintainer = dict.get('Maintainer', '') self._description = dict.get('Description', '') self._appendPackages(dict['Packages']) others = dict.get('Include', []) for url in others: self.appendURL(url, included=1)
7,949
def _help(): print "Usage: pimp [-v] -s [package ...] List installed status" print " pimp [-v] -l [package ...] Show package information" print " pimp [-vf] -i package ... Install packages" print " pimp -d Dump database to stdout" print "Options:" print " -v Verbose" print " -f Force installation" sys.exit(1)
def _help(): print "Usage: pimp [-v] -s [package ...] List installed status" print " pimp [-v] -l [package ...] Show package information" print " pimp [-vf] -i package ... Install packages" print " pimp -d Dump database to stdout" print "Options:" print " -v Verbose" print " -f Force installation" sys.exit(1)
7,950
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
7,951
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
7,952
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
7,953
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
def basic(src): "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() L for s in L: "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 `cf.get('Foo Bar', 'foo', raw=1)` `cf.get('Spacey Bar', 'foo', raw=1)` `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): '__name__ "option" should not be exposed by the API!' else: '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
7,954
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() verify(L == ['Commented Bar', 'Foo Bar', 'Internationalized Stuff', 'Spacey Bar'], "unexpected list of section names") # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
7,955
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 verify(cf.get('Foo Bar', 'foo', raw=1) == 'bar') verify(cf.get('Spacey Bar', 'foo', raw=1) == 'bar') verify(cf.get('Commented Bar', 'foo', raw=1) == 'bar') if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
7,956
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` verify('__name__' not in cf.options("Foo Bar"), '__name__ "option" should not be exposed by the API!') # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
7,957
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: if not cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report existance of option") if cf.has_option('Foo Bar', 'foo'): raise TestFailed("remove_option() failed to remove option") if cf.remove_option('Foo Bar', 'foo'): raise TestFailed( "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
def basic(src): print print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() print L for s in L: print "%s: %s" % (s, cf.options(s)) # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 print `cf.get('Foo Bar', 'foo', raw=1)` print `cf.get('Spacey Bar', 'foo', raw=1)` print `cf.get('Commented Bar', 'foo', raw=1)` if '__name__' in cf.options("Foo Bar"): print '__name__ "option" should not be exposed by the API!' else: print '__name__ "option" properly hidden by the API.' # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: verify(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report existance of option") verify(not cf.has_option('Foo Bar', 'foo'), "remove_option() failed to remove option") verify(not cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
7,958
def interpolation(src): print print "Testing value interpolation..." cf = ConfigParser.ConfigParser({"getname": "%(__name__)s"}) sio = StringIO.StringIO(src) cf.readfp(sio) print `cf.get("Foo", "getname")` print `cf.get("Foo", "bar")` print `cf.get("Foo", "bar9")` print `cf.get("Foo", "bar10")` expect_get_error(cf, ConfigParser.InterpolationDepthError, "Foo", "bar11")
def interpolation(src): "Testing value interpolation..." cf = ConfigParser.ConfigParser({"getname": "%(__name__)s"}) sio = StringIO.StringIO(src) cf.readfp(sio) `cf.get("Foo", "getname")` `cf.get("Foo", "bar")` `cf.get("Foo", "bar9")` `cf.get("Foo", "bar10")` expect_get_error(cf, ConfigParser.InterpolationDepthError, "Foo", "bar11")
7,959
def interpolation(src): print print "Testing value interpolation..." cf = ConfigParser.ConfigParser({"getname": "%(__name__)s"}) sio = StringIO.StringIO(src) cf.readfp(sio) print `cf.get("Foo", "getname")` print `cf.get("Foo", "bar")` print `cf.get("Foo", "bar9")` print `cf.get("Foo", "bar10")` expect_get_error(cf, ConfigParser.InterpolationDepthError, "Foo", "bar11")
def interpolation(src): print print "Testing value interpolation..." cf = ConfigParser.ConfigParser({"getname": "%(__name__)s"}) sio = StringIO.StringIO(src) cf.readfp(sio) verify(cf.get("Foo", "getname") == "Foo") verify(cf.get("Foo", "bar") == "something with interpolation (1 step)") verify(cf.get("Foo", "bar9") == "something with lots of interpolation (9 steps)") verify(cf.get("Foo", "bar10") == "something with lots of interpolation (10 steps)") expect_get_error(cf, ConfigParser.InterpolationDepthError, "Foo", "bar11")
7,960
def parse_errors(): print print "Testing for parsing errors..." expect_parse_error(ConfigParser.ParsingError, """[Foo]\n extra-spaces: splat\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\n extra-spaces= splat\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\noption-without-value\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\n:value-without-option-name\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\n=value-without-option-name\n""") expect_parse_error(ConfigParser.MissingSectionHeaderError, """No Section!\n""")
def parse_errors(): print "Testing parse errors..." expect_parse_error(ConfigParser.ParsingError, """[Foo]\n extra-spaces: splat\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\n extra-spaces= splat\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\noption-without-value\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\n:value-without-option-name\n""") expect_parse_error(ConfigParser.ParsingError, """[Foo]\n=value-without-option-name\n""") expect_parse_error(ConfigParser.MissingSectionHeaderError, """No Section!\n""")
7,961
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
def query_errors(): "Testing query interface..." cf = ConfigParser.ConfigParser() cf.sections() "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: "Caught expected NoSectionError:", e else: "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: "Caught expected NoSectionError:", e else: "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
7,962
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() verify(cf.sections() == [], "new ConfigParser should have no defined sections") verify(not cf.has_section("Foo"), "new ConfigParser should have no acknowledged sections") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
7,963
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: pass else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: pass else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
7,964
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: raise TestFailed( "Failed to catch expected NoSectionError from options()") try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
7,965
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: pass else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: pass else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
7,966
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from set()" expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
def query_errors(): print print "Testing query interface..." cf = ConfigParser.ConfigParser() print cf.sections() print "Has section 'Foo'?", cf.has_section("Foo") try: cf.options("Foo") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: print "Failed to catch expected NoSectionError from options()" try: cf.set("foo", "bar", "value") except ConfigParser.NoSectionError, e: print "Caught expected NoSectionError:", e else: raise TestFailed("Failed to catch expected NoSectionError from set()") expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar") cf.add_section("foo") expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
7,967
def weird_errors(): print print "Testing miscellaneous error conditions..." cf = ConfigParser.ConfigParser() cf.add_section("Foo") try: cf.add_section("Foo") except ConfigParser.DuplicateSectionError, e: print "Caught expected DuplicateSectionError:", e else: print "Failed to catch expected DuplicateSectionError"
def weird_errors(): "Testing miscellaneous error conditions..." cf = ConfigParser.ConfigParser() cf.add_section("Foo") try: cf.add_section("Foo") except ConfigParser.DuplicateSectionError, e: "Caught expected DuplicateSectionError:", e else: "Failed to catch expected DuplicateSectionError"
7,968
def weird_errors(): print print "Testing miscellaneous error conditions..." cf = ConfigParser.ConfigParser() cf.add_section("Foo") try: cf.add_section("Foo") except ConfigParser.DuplicateSectionError, e: print "Caught expected DuplicateSectionError:", e else: print "Failed to catch expected DuplicateSectionError"
def weird_errors(): print print "Testing miscellaneous error conditions..." cf = ConfigParser.ConfigParser() cf.add_section("Foo") try: cf.add_section("Foo") except ConfigParser.DuplicateSectionError, e: pass else: print "Failed to catch expected DuplicateSectionError"
7,969
def weird_errors(): print print "Testing miscellaneous error conditions..." cf = ConfigParser.ConfigParser() cf.add_section("Foo") try: cf.add_section("Foo") except ConfigParser.DuplicateSectionError, e: print "Caught expected DuplicateSectionError:", e else: print "Failed to catch expected DuplicateSectionError"
def weird_errors(): print print "Testing miscellaneous error conditions..." cf = ConfigParser.ConfigParser() cf.add_section("Foo") try: cf.add_section("Foo") except ConfigParser.DuplicateSectionError, e: print "Caught expected DuplicateSectionError:", e else: raise TestFailed("Failed to catch expected DuplicateSectionError")
7,970
def expect_get_error(cf, exctype, section, option, raw=0): try: cf.get(section, option, raw=raw) except exctype, e: print "Caught expected", exctype.__name__, ":" print e else: print "Failed to catch expected", exctype.__name__
def expect_get_error(cf, exctype, section, option, raw=0): try: cf.get(section, option, raw=raw) except exctype, e: pass else: print "Failed to catch expected", exctype.__name__
7,971
def expect_get_error(cf, exctype, section, option, raw=0): try: cf.get(section, option, raw=raw) except exctype, e: print "Caught expected", exctype.__name__, ":" print e else: print "Failed to catch expected", exctype.__name__
def expect_get_error(cf, exctype, section, option, raw=0): try: cf.get(section, option, raw=raw) except exctype, e: print "Caught expected", exctype.__name__, ":" print e else: raise TestFailed("Failed to catch expected " + exctype.__name__)
7,972
def expect_parse_error(exctype, src): cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) try: cf.readfp(sio) except exctype, e: print "Caught expected exception:", e else: print "Failed to catch expected", exctype.__name__
def expect_parse_error(exctype, src): cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) try: cf.readfp(sio) except exctype, e: pass else: print "Failed to catch expected", exctype.__name__
7,973
def expect_parse_error(exctype, src): cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) try: cf.readfp(sio) except exctype, e: print "Caught expected exception:", e else: print "Failed to catch expected", exctype.__name__
def expect_parse_error(exctype, src): cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) try: cf.readfp(sio) except exctype, e: print "Caught expected exception:", e else: raise TestFailed("Failed to catch expected " + exctype.__name__)
7,974
def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)"""
def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)"""
7,975
def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)"""
def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)"""
7,976
def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)"""
def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)"""
7,977
def __init__(self): self.reset()
def __init__(self, verbose=0): self.verbose = verbose self.reset()
7,978
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if self.nomoretags: self.handle_data(rawdata[i:n]) i = n break j = incomplete.search(rawdata, i) if j < 0: j = n if i < j: self.handle_data(rawdata[i:j]) i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i) >= 0: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue k = self.parse_starttag(i) if k < 0: break i = i + k continue k = endtag.match(rawdata, i) if k >= 0: j = i+k self.parse_endtag(rawdata[i:j]) i = j self.literal = 0 continue if commentopen.match(rawdata, i) >= 0: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue k = self.parse_comment(i) if k < 0: break i = i+k continue k = special.match(rawdata, i) if k >= 0: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue i = i+k continue elif rawdata[i] == '&': k = charref.match(rawdata, i) if k >= 0: j = i+k self.handle_charref(rawdata[i+2:j-1]) i = j continue k = entityref.match(rawdata, i) if k >= 0: j = i+k self.handle_entityref(rawdata[i+1:j-1]) i = j continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else k = incomplete.match(rawdata, i) if k < 0: raise RuntimeError, 'no incomplete match ??' j = i+k if j == n: break # Really incomplete self.handle_data(rawdata[i:j]) i = j # end while if end and i < n: self.handle_data(rawdata[i:n]) i = n self.rawdata = rawdata[i:] # XXX if end: check for empty stack
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if self.nomoretags: self.handle_data(rawdata[i:n]) i = n break j = incomplete.search(rawdata, i) if j < 0: j = n if i < j: self.handle_data(rawdata[i:j]) i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i) >= 0: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue k = self.parse_starttag(i) if k < 0: break i = i + k continue k = endtag.match(rawdata, i) if k >= 0: j = i+k self.parse_endtag(rawdata[i:j]) i = j self.literal = 0 continue if commentopen.match(rawdata, i) >= 0: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue k = self.parse_comment(i) if k < 0: break i = i+k continue k = special.match(rawdata, i) if k >= 0: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue i = i+k continue elif rawdata[i] == '&': k = charref.match(rawdata, i) if k >= 0: j = i+k self.handle_charref(rawdata[i+2:j-1]) i = j continue k = entityref.match(rawdata, i) if k >= 0: j = i+k self.handle_entityref(rawdata[i+1:j-1]) i = j continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else k = incomplete.match(rawdata, i) if k < 0: raise RuntimeError, 'no incomplete match ??' j = i+k if j == n or rawdata[i:i+2] == '<!': break # Really incomplete self.handle_data(rawdata[i:j]) i = j # end while if end and i < n: self.handle_data(rawdata[i:n]) i = n self.rawdata = rawdata[i:] # XXX if end: check for empty stack
7,979
def report_unbalanced(self, tag): print '*** Unbalanced </' + tag + '>' print '*** Stack:', self.stack
def report_unbalanced(self, tag): print '*** Unbalanced </' + tag + '>' print '*** Stack:', self.stack
7,980
def handle_entityref(self, name): table = self.entitydefs name = string.lower(name) if table.has_key(name): self.handle_data(table[name]) else: self.unknown_entityref(name) return
def handle_entityref(self, name): table = self.entitydefs if table.has_key(name): self.handle_data(table[name]) else: self.unknown_entityref(name) return
7,981
def __init__(self, creator, eoln): self.rv = None self.eoln = eoln self.w = w = W.ModalDialog((260, 160), 'Save options') radiobuttons = [] w.label = W.TextBox((8, 8, 80, 18), "File creator:") w.ide_radio = W.RadioButton((8, 22, 160, 18), "This application", radiobuttons, self.ide_hit) w.interp_radio = W.RadioButton((8, 42, 160, 18), "MacPython Interpreter", radiobuttons, self.interp_hit) w.interpx_radio = W.RadioButton((8, 62, 160, 18), "OSX PythonW Interpreter", radiobuttons, self.interpx_hit) w.other_radio = W.RadioButton((8, 82, 50, 18), "Other:", radiobuttons) w.other_creator = W.EditText((62, 82, 40, 20), creator, self.otherselect) w.none_radio = W.RadioButton((8, 102, 160, 18), "None", radiobuttons, self.none_hit) w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit) w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit) w.setdefaultbutton(w.okbutton) if creator == 'Pyth': w.interp_radio.set(1) elif creator == W._signature: w.ide_radio.set(1) elif creator == 'PytX': w.interpx_radio.set(1) elif creator == '\0\0\0\0': w.none_radio.set(1) else: w.other_radio.set(1) w.eolnlabel = W.TextBox((168, 8, 80, 18), "Newline style:") radiobuttons = [] w.unix_radio = W.RadioButton((168, 22, 80, 18), "Unix", radiobuttons, self.unix_hit) w.mac_radio = W.RadioButton((168, 42, 80, 18), "Macintosh", radiobuttons, self.mac_hit) w.win_radio = W.RadioButton((168, 62, 80, 18), "Windows", radiobuttons, self.win_hit) if self.eoln == '\n': w.unix_radio.set(1) elif self.eoln == '\r\n': w.win_radio.set(1) else: w.mac_radio.set(1) w.bind("cmd.", w.cancelbutton.push) w.open()
def __init__(self, creator, eoln): self.rv = None self.eoln = eoln self.w = w = W.ModalDialog((260, 160), 'Save options') radiobuttons = [] w.label = W.TextBox((8, 8, 80, 18), "File creator:") w.ide_radio = W.RadioButton((8, 22, 160, 18), "PythonIDE", radiobuttons, self.ide_hit) w.interp_radio = W.RadioButton((8, 42, 160, 18), "MacPython-OS9 Interpreter", radiobuttons, self.interp_hit) w.interpx_radio = W.RadioButton((8, 62, 160, 18), "PythonLauncher", radiobuttons, self.interpx_hit) w.other_radio = W.RadioButton((8, 82, 50, 18), "Other:", radiobuttons) w.other_creator = W.EditText((62, 82, 40, 20), creator, self.otherselect) w.none_radio = W.RadioButton((8, 102, 160, 18), "None", radiobuttons, self.none_hit) w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit) w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit) w.setdefaultbutton(w.okbutton) if creator == 'Pyth': w.interp_radio.set(1) elif creator == W._signature: w.ide_radio.set(1) elif creator == 'PytX': w.interpx_radio.set(1) elif creator == '\0\0\0\0': w.none_radio.set(1) else: w.other_radio.set(1) w.eolnlabel = W.TextBox((168, 8, 80, 18), "Newline style:") radiobuttons = [] w.unix_radio = W.RadioButton((168, 22, 80, 18), "Unix", radiobuttons, self.unix_hit) w.mac_radio = W.RadioButton((168, 42, 80, 18), "Macintosh", radiobuttons, self.mac_hit) w.win_radio = W.RadioButton((168, 62, 80, 18), "Windows", radiobuttons, self.win_hit) if self.eoln == '\n': w.unix_radio.set(1) elif self.eoln == '\r\n': w.win_radio.set(1) else: w.mac_radio.set(1) w.bind("cmd.", w.cancelbutton.push) w.open()
7,982
def compile_command(source, filename="<input>", symbol="single"): r"""Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default) or "eval" Return value / exception raised: - Return a code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError if the command is a syntax error Approach: Compile three times: as is, with \n, and with \n\n appended. If it compiles as is, it's complete. If it compiles with one \n appended, we expect more. If it doesn't compile either way, we compare the error we get when compiling with \n or \n\n appended. If the errors are the same, the code is broken. But if the errors are different, we expect more. Not intuitive; not even guaranteed to hold in future releases; but this matches the compiler's behavior in Python 1.4 and 1.5. """ err = err1 = err2 = None code = code1 = code2 = None try: code = compile(source, filename, symbol) except SyntaxError, err: pass try: code1 = compile(source + "\n", filename, symbol) except SyntaxError, err1: pass try: code2 = compile(source + "\n\n", filename, symbol) except SyntaxError, err2: pass if code: return code if not code1 and err1 == err2: raise SyntaxError, err1
def compile_command(source, filename="<input>", symbol="single"): r"""Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default) or "eval" Return value / exception raised: - Return a code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError if the command is a syntax error Approach: Compile three times: as is, with \n, and with \n\n appended. If it compiles as is, it's complete. If it compiles with one \n appended, we expect more. If it doesn't compile either way, we compare the error we get when compiling with \n or \n\n appended. If the errors are the same, the code is broken. But if the errors are different, we expect more. Not intuitive; not even guaranteed to hold in future releases; but this matches the compiler's behavior in Python 1.4 and 1.5. """ err = err1 = err2 = None code = code1 = code2 = None try: code = compile(source, filename, symbol) except SyntaxError, err: pass try: code1 = compile(source + "\n", filename, symbol) except SyntaxError, err1: pass try: code2 = compile(source + "\n\n", filename, symbol) except SyntaxError, err2: pass if code: return code try: e1 = err1.__dict__ except AttributeError: e1 = err1 try: e2 = err2.__dict__ except AttributeError: e2 = err2 if not code1 and e1 == e2: raise SyntaxError, err1
7,983
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists (or if 'name' is the empty string, which means the current directory, which of course exists), then do nothing. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout. Return the list of directories actually created.""" global _path_created # Detect a common bug -- name is None if type(name) is not StringType: raise DistutilsInternalError, \ "mkpath: 'name' must be a string (got %r)" % (name,) # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath(name) created_dirs = [] if os.path.isdir(name) or name == '': return created_dirs if _path_created.get(os.path.abspath(name)): return created_dirs (head, tail) = os.path.split(name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir(head): #print "splitting '%s': " % head, (head, tail) = os.path.split(head) #print "to ('%s','%s')" % (head, tail) tails.insert(0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join(head, d) abs_head = os.path.abspath(head) if _path_created.get(abs_head): continue log.info("creating %s", head) if not dry_run: try: os.mkdir(head) created_dirs.append(head) except OSError, exc: raise DistutilsFileError, \ "could not create '%s': %s" % (head, exc[-1]) _path_created[abs_head] = 1 return created_dirs
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists (or if 'name' is the empty string, which means the current directory, which of course exists), then do nothing. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout. Return the list of directories actually created.""" global _path_created # Detect a common bug -- name is None if not isinstance(name, StringTypes): raise DistutilsInternalError, \ "mkpath: 'name' must be a string (got %r)" % (name,) # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath(name) created_dirs = [] if os.path.isdir(name) or name == '': return created_dirs if _path_created.get(os.path.abspath(name)): return created_dirs (head, tail) = os.path.split(name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir(head): #print "splitting '%s': " % head, (head, tail) = os.path.split(head) #print "to ('%s','%s')" % (head, tail) tails.insert(0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join(head, d) abs_head = os.path.abspath(head) if _path_created.get(abs_head): continue log.info("creating %s", head) if not dry_run: try: os.mkdir(head) created_dirs.append(head) except OSError, exc: raise DistutilsFileError, \ "could not create '%s': %s" % (head, exc[-1]) _path_created[abs_head] = 1 return created_dirs
7,984
def com_dictsetmaker(self, nodelist): # dictsetmaker: (test ':' test (',' test ':' value)* [',']) | (test (',' test)* [',']) items = [] if nodelist[2] != ':': # it's a set for i in range(1, len(nodelist), 2): items.append(self.com_node(nodelist[i])) return Set(items, lineno=items[0].lineno) else: # it's a dict for i in range(1, len(nodelist), 4): items.append((self.com_node(nodelist[i]), self.com_node(nodelist[i+2]))) return Dict(items, lineno=items[0][0].lineno)
def com_dictsetmaker(self, nodelist): # dictsetmaker: (test ':' test (',' test ':' value)* [',']) | (test (',' test)* [',']) items = [] if len(nodelist) == 1 or nodelist[1] != ':': # it's a set for i in range(1, len(nodelist), 2): items.append(self.com_node(nodelist[i])) return Set(items, lineno=items[0].lineno) else: # it's a dict for i in range(1, len(nodelist), 4): items.append((self.com_node(nodelist[i]), self.com_node(nodelist[i+2]))) return Dict(items, lineno=items[0][0].lineno)
7,985
def __init__(self, stream, errors='strict'):
def __init__(self, stream, errors='strict'):
7,986
def readline(self, size=None, keepends=True):
def readline(self, size=None, keepends=True):
7,987
def readline(self, size=None, keepends=True):
def readline(self, size=None, keepends=True):
7,988
def readline(self, size=None, keepends=True):
def readline(self, size=None, keepends=True):
7,989
def reset(self):
def reset(self):
7,990
def show_formats (): """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ from distutils.fancy_getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats=[] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() pretty_printer = FancyGetopt(formats) pretty_printer.print_help( "List of available source distribution formats:")
def show_formats (): """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ from distutils.fancy_getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats=[] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() pretty_printer = FancyGetopt(formats) pretty_printer.print_help( "List of available source distribution formats:")
7,991
def get_file_list (self): """Figure out the list of files to include in the source distribution, and put it in 'self.files'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """
def get_file_list (self): """Figure out the list of files to include in the source distribution, and put it in 'self.files'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """
7,992
def prune_file_list (self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: specifically, the build tree (typically "build") and the release tree itself (only an issue if we ran "sdist" previously with --keep-tree, or it aborted). """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.exclude_pattern (self.files, None, prefix=build.build_base) self.exclude_pattern (self.files, None, prefix=base_dir)
def prune_file_list (self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-tree, or it aborted) * any RCS or CVS directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.exclude_pattern (self.files, None, prefix=build.build_base) self.exclude_pattern (self.files, None, prefix=base_dir)
7,993
def prune_file_list (self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: specifically, the build tree (typically "build") and the release tree itself (only an issue if we ran "sdist" previously with --keep-tree, or it aborted). """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.exclude_pattern (self.files, None, prefix=build.build_base) self.exclude_pattern (self.files, None, prefix=base_dir)
def prune_file_list (self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: specifically, the build tree (typically "build") and the release tree itself (only an issue if we ran "sdist" previously with --keep-tree, or it aborted). """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.exclude_pattern (self.files, None, prefix=build.build_base) self.exclude_pattern (self.files, None, prefix=base_dir)
7,994
def select_pattern (self, files, pattern, anchor=1, prefix=None): """Select strings (presumably filenames) from 'files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix, colon, slash, and backslash on DOS/Windows, and colon on Mac OS.
def select_pattern (self, files, pattern, anchor=1, prefix=None): """Select strings (presumably filenames) from 'files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix, colon, slash, and backslash on DOS/Windows, and colon on Mac OS.
7,995
def exclude_pattern (self, files, pattern, anchor=1, prefix=None): """Remove strings (presumably filenames) from 'files' that match 'pattern'. 'pattern', 'anchor', 'and 'prefix' are the same as for 'select_pattern()', above. The list 'files' is modified in place. """ pattern_re = translate_pattern (pattern, anchor, prefix) self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern) for i in range (len(files)-1, -1, -1): if pattern_re.search (files[i]): self.debug_print(" removing " + files[i]) del files[i]
def exclude_pattern (self, files, pattern, anchor=1, prefix=None, is_regex=0): """Remove strings (presumably filenames) from 'files' that match 'pattern'. 'pattern', 'anchor', 'and 'prefix' are the same as for 'select_pattern()', above. The list 'files' is modified in place. """ pattern_re = translate_pattern (pattern, anchor, prefix) self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern) for i in range (len(files)-1, -1, -1): if pattern_re.search (files[i]): self.debug_print(" removing " + files[i]) del files[i]
7,996
def exclude_pattern (self, files, pattern, anchor=1, prefix=None): """Remove strings (presumably filenames) from 'files' that match 'pattern'. 'pattern', 'anchor', 'and 'prefix' are the same as for 'select_pattern()', above. The list 'files' is modified in place. """ pattern_re = translate_pattern (pattern, anchor, prefix) self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern) for i in range (len(files)-1, -1, -1): if pattern_re.search (files[i]): self.debug_print(" removing " + files[i]) del files[i]
def exclude_pattern (self, files, pattern, anchor=1, prefix=None): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'select_pattern()', above. The list 'files' is modified in place. """ pattern_re = translate_pattern (pattern, anchor, prefix, is_regex) self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern) for i in range (len(files)-1, -1, -1): if pattern_re.search (files[i]): self.debug_print(" removing " + files[i]) del files[i]
7,997
def findall (dir = os.curdir): """Find all files under 'dir' and return the list of full filenames (relative to 'dir'). """ list = [] stack = [dir] pop = stack.pop push = stack.append while stack: dir = pop() names = os.listdir (dir) for name in names: if dir != os.curdir: # avoid the dreaded "./" syndrome fullname = os.path.join (dir, name) else: fullname = name list.append (fullname) if os.path.isdir (fullname) and not os.path.islink(fullname): push (fullname) return list
def findall (dir = os.curdir): """Find all files under 'dir' and return the list of full filenames (relative to 'dir'). """ list = [] stack = [dir] pop = stack.pop push = stack.append while stack: dir = pop() names = os.listdir (dir) for name in names: if dir != os.curdir: # avoid the dreaded "./" syndrome fullname = os.path.join (dir, name) else: fullname = name stat = os.stat(fullname) mode = stat[ST_MODE] if S_ISREG(mode): list.append (fullname) elif S_ISDIR(mode) and not S_ISLNK(mode): push (fullname) return list
7,998
def setup(self, f, t): self.lineno = None self.stack = [] if t and t.tb_frame is f: t = t.tb_next while f and f is not self.botframe: self.stack.append((f, f.f_lineno)) f = f.f_back self.stack.reverse() self.curindex = max(0, len(self.stack) - 1) while t: self.stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if 0 <= self.curindex < len(self.stack): self.curframe = self.stack[self.curindex][0] else: self.curframe = None
def setup(self, f, t): self.lineno = None self.stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: self.stack.append((f, f.f_lineno)) f = f.f_back self.stack.reverse() self.curindex = max(0, len(self.stack) - 1) while t: self.stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if 0 <= self.curindex < len(self.stack): self.curframe = self.stack[self.curindex][0] else: self.curframe = None
7,999