bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def search(self, charset, criteria): """Search mailbox for matching messages.
|
def search(self, charset, criteria): """Search mailbox for matching messages.
| 7,500
|
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
|
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
| 7,501
|
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
|
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
| 7,502
|
def status(self, mailbox, names): """Request named status conditions for mailbox.
|
def status(self, mailbox, names): """Request named status conditions for mailbox.
| 7,503
|
def store(self, message_set, command, flag_list): """Alters flag dispositions for messages in mailbox.
|
def store(self, message_set, command, flag_list): """Alters flag dispositions for messages in mailbox.
| 7,504
|
def uid(self, command, *args): """Execute "command arg ..." with messages identified by UID, rather than message number.
|
def uid(self, command, *args): """Execute "command arg ..." with messages identified by UID, rather than message number.
| 7,505
|
def _append_untagged(self, typ, dat):
|
def _append_untagged(self, typ, dat):
| 7,506
|
def _command(self, name, *args):
|
def _command(self, name, *args):
| 7,507
|
def _command(self, name, *args):
|
def _command(self, name, *args):
| 7,508
|
def _command(self, name, *args):
|
def _command(self, name, *args):
| 7,509
|
def _get_response(self):
|
def _get_response(self):
| 7,510
|
def _get_line(self):
|
def _get_line(self):
| 7,511
|
def _get_line(self):
|
def _get_line(self):
| 7,512
|
def _match(self, cre, s):
|
def _match(self, cre, s):
| 7,513
|
def _untagged_response(self, typ, name):
|
def _untagged_response(self, typ, name):
| 7,514
|
def _untagged_response(self, typ, name):
|
def _untagged_response(self, typ, name):
| 7,515
|
def _trunc(m, s): if len(s) <= m: return s return '%.*s..' % (m, s)
|
def _trunc(m, s): if len(s) <= m: return s return '%.*s..' % (m, s)
| 7,516
|
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
|
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) _mesg(' %s %s\n => %s %s' % (cmd, args, typ, dat)) return dat
| 7,517
|
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
|
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
| 7,518
|
def plus(*v): accu = 0 for i in v: accu = accu + i return accu
|
def plus(*v): accu = 0 for i in v: accu = accu + i return accu
| 7,519
|
def accept(self): working_sock, address = self.listening_sock.accept() if address[0] == '127.0.0.1': print>>sys.__stderr__, "Idle accepted connection from ", address SocketIO.__init__(self, working_sock) else: print>>sys.__stderr__, "Invalid host: ", address raise socket.error
|
def accept(self): working_sock, address = self.listening_sock.accept() if address[0] == '127.0.0.1': SocketIO.__init__(self, working_sock) else: print>>sys.__stderr__, "Invalid host: ", address raise socket.error
| 7,520
|
def accept(self): working_sock, address = self.listening_sock.accept() if address[0] == '127.0.0.1': print>>sys.__stderr__, "Idle accepted connection from ", address SocketIO.__init__(self, working_sock) else: print>>sys.__stderr__, "Invalid host: ", address raise socket.error
|
def accept(self): working_sock, address = self.listening_sock.accept() if address[0] == '127.0.0.1': print>>sys.__stderr__, "Idle accepted connection from ", address SocketIO.__init__(self, working_sock) else: print>>sys.__stderr__, "** Invalid host: ", address raise socket.error
| 7,521
|
def make_release_tree (self, base_dir, files):
|
def make_release_tree (self, base_dir, files):
| 7,522
|
def make_distribution (self):
|
def make_distribution (self):
| 7,523
|
def get_cookie(self):
|
def get_cookie(self):
| 7,524
|
def mime_encode(line, header): """Code a single line as quoted-printable. If header is set, quote some extra characters.""" if header: reg = mime_header_char else: reg = mime_char newline = '' pos = 0 if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = ('=%02x' % ord('F')).upper() pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ ('=%02x' % ord(res.group(0))).upper() pos = res.end(0) line = newline + line[pos:] newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
|
def mime_encode(line, header): """Code a single line as quoted-printable. If header is set, quote some extra characters.""" if header: reg = mime_header_char else: reg = mime_char newline = '' pos = 0 if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = ('=%02x' % ord('F')).upper() pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ ('=%02x' % ord(res.group(0))).upper() pos = res.end(0) line = newline + line[pos:] newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
| 7,525
|
def mime_encode_header(line): """Code a single header line as quoted-printable.""" newline = '' pos = 0 while 1: res = mime_header.search(line, pos) if res is None: break newline = '%s%s%s=?%s?Q?%s?=%s' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1), res.group(3)) pos = res.end(0) return newline + line[pos:]
|
def mime_encode_header(line): """Code a single header line as quoted-printable.""" newline = '' pos = 0 while 1: res = mime_header.search(line, pos) if res is None: break newline = '%s%s%s=?%s?Q?%s?=' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1), res.group(3)) pos = res.end(0) return newline + line[pos:]
| 7,526
|
def mime_encode_header(line): """Code a single header line as quoted-printable.""" newline = '' pos = 0 while 1: res = mime_header.search(line, pos) if res is None: break newline = '%s%s%s=?%s?Q?%s?=%s' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1), res.group(3)) pos = res.end(0) return newline + line[pos:]
|
def mime_encode_header(line): """Code a single header line as quoted-printable.""" newline = '' pos = 0 while 1: res = mime_header.search(line, pos) if res is None: break newline = '%s%s%s=?%s?Q?%s?=%s' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1)) pos = res.end(0) return newline + line[pos:]
| 7,527
|
def proxy_bypass(host): try: import _winreg import re except ImportError: # Std modules, so should be around - but you never know! return 0 try: internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0] proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0]) # ^^^^ Returned as Unicode but problems if not converted to ASCII except WindowsError: return 0 if not proxyEnable or not proxyOverride: return 0 # try to make a host list from name and IP address. host = [host] try: addr = socket.gethostbyname(host[0]) if addr != host: host.append(addr) except socket.error: pass # make a check value list from the registry entry: replace the # '<local>' string by the localhost entry and the corresponding # canonical entry. proxyOverride = proxyOverride.split(';') i = 0 while i < len(proxyOverride): if proxyOverride[i] == '<local>': proxyOverride[i:i+1] = ['localhost', '127.0.0.1', socket.gethostname(), socket.gethostbyname( socket.gethostname())] i += 1 # print proxyOverride # now check if we match one of the registry values. for test in proxyOverride: test = test.replace(".", r"\.") # mask dots test = test.replace("*", r".*") # change glob sequence test = test.replace("?", r".") # change glob char for val in host: # print "%s <--> %s" %( test, val ) if re.match(test, val, re.I): return 1 return 0
|
def proxy_bypass(host): try: import _winreg import re except ImportError: # Std modules, so should be around - but you never know! return 0 try: internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0] proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0]) # ^^^^ Returned as Unicode but problems if not converted to ASCII except WindowsError: return 0 if not proxyEnable or not proxyOverride: return 0 # try to make a host list from name and IP address. rawHost, port = splitport(host) host = [rawHost] try: addr = socket.gethostbyname(rawHost) if addr != rawHost: host.append(addr) except socket.error: pass # make a check value list from the registry entry: replace the # '<local>' string by the localhost entry and the corresponding # canonical entry. proxyOverride = proxyOverride.split(';') i = 0 while i < len(proxyOverride): if proxyOverride[i] == '<local>': proxyOverride[i:i+1] = ['localhost', '127.0.0.1', socket.gethostname(), socket.gethostbyname( socket.gethostname())] i += 1 # print proxyOverride # now check if we match one of the registry values. for test in proxyOverride: test = test.replace(".", r"\.") # mask dots test = test.replace("*", r".*") # change glob sequence test = test.replace("?", r".") # change glob char for val in host: # print "%s <--> %s" %( test, val ) if re.match(test, val, re.I): return 1 return 0
| 7,528
|
def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number. Will not accept a ZIP archive with an ending comment. """ try: fpin = open(filename, "rb") fpin.seek(-22, 2) # Seek to end-of-file record endrec = fpin.read() fpin.close() if endrec[0:4] == "PK\005\006" and endrec[-2:] == "\000\000": return 1 # file has correct magic number except: pass
|
def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number. Will not accept a ZIP archive with an ending comment. """ try: fpin = open(filename, "rb") fpin.seek(-22, 2) # Seek to end-of-file record endrec = fpin.read() fpin.close() if endrec[0:4] == "PK\005\006" and endrec[-2:] == "\000\000": return 1 # file has correct magic number except IOError: pass
| 7,529
|
def verisnot(a, b): if a is b: raise TestFailed, "%r is %r" % (a, b)
|
def verisnot(a, b): if a is b: raise TestFailed, "%r is %r" % (a, b)
| 7,530
|
def listclasses(self): dir, file = os.path.split(self.file) name, ext = os.path.splitext(file) if os.path.normcase(ext) != ".py": return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) except ImportError, msg: return [] items = [] self.classes = {} for key, cl in dict.items(): if cl.module == name: s = key if cl.super: supers = [] for sup in cl.super: if type(sup) is type(''): sname = sup else: sname = sup.name if sup.module != cl.module: sname = "%s.%s" % (sup.module, sname) supers.append(sname) s = s + "(%s)" % ", ".join(supers) items.append((cl.lineno, s)) self.classes[s] = cl items.sort() list = [] for item, s in items: list.append(s) return list
|
def listclasses(self): dir, file = os.path.split(self.file) name, ext = os.path.splitext(file) if os.path.normcase(ext) != ".py": return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) except ImportError, msg: return [] items = [] self.classes = {} for key, cl in dict.items(): if cl.module == name: s = key if hasattr(cl, "super") and cl.super: supers = [] for sup in cl.super: if type(sup) is type(''): sname = sup else: sname = sup.name if sup.module != cl.module: sname = "%s.%s" % (sup.module, sname) supers.append(sname) s = s + "(%s)" % ", ".join(supers) items.append((cl.lineno, s)) self.classes[s] = cl items.sort() list = [] for item, s in items: list.append(s) return list
| 7,531
|
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line try: opts, args = getopt.getopt(sys.argv[1:], 'deh:mo:p:P:qs:w') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Include', 'pythonrun.h')) # locations derived from options version = sys.version[:3] if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + binlib] # sanity check of directories and files for dir in [prefix, exec_prefix, binlib, incldir] + extensions: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that the script name ends in ".py" if args[0][-3:] != ".py": usage('the script name must have a .py suffix') # check that file arguments exist for arg in args: if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) if odir: frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) # Actual work starts here... # collect all modules of the program mf = modulefinder.ModuleFinder(path, debug) for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) mf.run_script(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules backup = frozen_c + '~' try: os.rename(frozen_c, backup) except os.error: backup = None outfp = open(frozen_c, 'w') try: makefreeze.makefreeze(outfp, dict, debug) if win and subsystem == 'windows': import winmakemakefile outfp.write(winmakemakefile.WINMAINTEMPLATE) finally: outfp.close() if backup: if cmp.cmp(backup, frozen_c): sys.stderr.write('%s not changed, not written\n' % frozen_c) os.rename(backup, frozen_c) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), [frozenmain_c, frozen_c], target) finally: outfp.close() return # generate config.c and Makefile builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) addfiles = [] if unknown: addfiles, addmods = \ checkextensions.checkextensions(unknown, extensions) for mod in addmods: unknown.remove(mod) builtins = builtins + addmods if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) builtins.sort() infp = open(config_c_in) backup = config_c + '~' try: os.rename(config_c, backup) except os.error: backup = None outfp = open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() if backup: if cmp.cmp(backup, config_c): sys.stderr.write('%s not changed, not written\n' % config_c) os.rename(backup, config_c) cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] backup = makefile + '~' try: os.rename(makefile, backup) except os.error: backup = None outfp = open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() if backup: if not cmp.cmp(backup, makefile): print 'previous Makefile saved as', backup else: sys.stderr.write('%s not changed, not written\n' % makefile) os.rename(backup, makefile) # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
|
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line try: opts, args = getopt.getopt(sys.argv[1:], 'deh:mo:p:P:qs:w') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Include', 'pythonrun.h')) # locations derived from options version = sys.version[:3] if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + binlib] # sanity check of directories and files for dir in [prefix, exec_prefix, binlib, incldir] + extensions: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that the script name ends in ".py" if args[0][-3:] != ".py": usage('the script name must have a .py suffix') # check that file arguments exist for arg in args: if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) if odir: frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) # Actual work starts here... # collect all modules of the program mf = modulefinder.ModuleFinder(path, debug) for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) mf.run_script(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules backup = frozen_c + '~' try: os.rename(frozen_c, backup) except os.error: backup = None outfp = open(frozen_c, 'w') try: makefreeze.makefreeze(outfp, dict, debug) if win and subsystem == 'windows': import winmakemakefile outfp.write(winmakemakefile.WINMAINTEMPLATE) finally: outfp.close() if backup: if cmp.cmp(backup, frozen_c): sys.stderr.write('%s not changed, not written\n' % frozen_c) os.rename(backup, frozen_c) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), [frozenmain_c, frozen_c], target) finally: outfp.close() return # generate config.c and Makefile builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) addfiles = [] if unknown: addfiles, addmods = \ checkextensions.checkextensions(unknown, extensions) for mod in addmods: unknown.remove(mod) builtins = builtins + addmods if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) builtins.sort() infp = open(config_c_in) backup = config_c + '~' try: os.rename(config_c, backup) except os.error: backup = None outfp = open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() if backup: if cmp.cmp(backup, config_c): sys.stderr.write('%s not changed, not written\n' % config_c) os.rename(backup, config_c) cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] backup = makefile + '~' try: os.rename(makefile, backup) except os.error: backup = None outfp = open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() if backup: if not cmp.cmp(backup, makefile): print 'previous Makefile saved as', backup else: sys.stderr.write('%s not changed, not written\n' % makefile) os.rename(backup, makefile) # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
| 7,532
|
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line try: opts, args = getopt.getopt(sys.argv[1:], 'deh:mo:p:P:qs:w') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Include', 'pythonrun.h')) # locations derived from options version = sys.version[:3] if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + binlib] # sanity check of directories and files for dir in [prefix, exec_prefix, binlib, incldir] + extensions: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that the script name ends in ".py" if args[0][-3:] != ".py": usage('the script name must have a .py suffix') # check that file arguments exist for arg in args: if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) if odir: frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) # Actual work starts here... # collect all modules of the program mf = modulefinder.ModuleFinder(path, debug) for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) mf.run_script(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules backup = frozen_c + '~' try: os.rename(frozen_c, backup) except os.error: backup = None outfp = open(frozen_c, 'w') try: makefreeze.makefreeze(outfp, dict, debug) if win and subsystem == 'windows': import winmakemakefile outfp.write(winmakemakefile.WINMAINTEMPLATE) finally: outfp.close() if backup: if cmp.cmp(backup, frozen_c): sys.stderr.write('%s not changed, not written\n' % frozen_c) os.rename(backup, frozen_c) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), [frozenmain_c, frozen_c], target) finally: outfp.close() return # generate config.c and Makefile builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) addfiles = [] if unknown: addfiles, addmods = \ checkextensions.checkextensions(unknown, extensions) for mod in addmods: unknown.remove(mod) builtins = builtins + addmods if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) builtins.sort() infp = open(config_c_in) backup = config_c + '~' try: os.rename(config_c, backup) except os.error: backup = None outfp = open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() if backup: if cmp.cmp(backup, config_c): sys.stderr.write('%s not changed, not written\n' % config_c) os.rename(backup, config_c) cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] backup = makefile + '~' try: os.rename(makefile, backup) except os.error: backup = None outfp = open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() if backup: if not cmp.cmp(backup, makefile): print 'previous Makefile saved as', backup else: sys.stderr.write('%s not changed, not written\n' % makefile) os.rename(backup, makefile) # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
|
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line try: opts, args = getopt.getopt(sys.argv[1:], 'deh:mo:p:P:qs:w') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Include', 'pythonrun.h')) # locations derived from options version = sys.version[:3] if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + binlib] # sanity check of directories and files for dir in [prefix, exec_prefix, binlib, incldir] + extensions: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that the script name ends in ".py"# check that file arguments exist for arg in args: if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) if odir: frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) # Actual work starts here... # collect all modules of the program mf = modulefinder.ModuleFinder(path, debug) for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) mf.run_script(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules backup = frozen_c + '~' try: os.rename(frozen_c, backup) except os.error: backup = None outfp = open(frozen_c, 'w') try: makefreeze.makefreeze(outfp, dict, debug) if win and subsystem == 'windows': import winmakemakefile outfp.write(winmakemakefile.WINMAINTEMPLATE) finally: outfp.close() if backup: if cmp.cmp(backup, frozen_c): sys.stderr.write('%s not changed, not written\n' % frozen_c) os.rename(backup, frozen_c) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), [frozenmain_c, frozen_c], target) finally: outfp.close() return # generate config.c and Makefile builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) addfiles = [] if unknown: addfiles, addmods = \ checkextensions.checkextensions(unknown, extensions) for mod in addmods: unknown.remove(mod) builtins = builtins + addmods if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) builtins.sort() infp = open(config_c_in) backup = config_c + '~' try: os.rename(config_c, backup) except os.error: backup = None outfp = open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() if backup: if cmp.cmp(backup, config_c): sys.stderr.write('%s not changed, not written\n' % config_c) os.rename(backup, config_c) cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] backup = makefile + '~' try: os.rename(makefile, backup) except os.error: backup = None outfp = open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() if backup: if not cmp.cmp(backup, makefile): print 'previous Makefile saved as', backup else: sys.stderr.write('%s not changed, not written\n' % makefile) os.rename(backup, makefile) # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
| 7,533
|
def encodestring(s): """Encode a string.""" import StringIO f = StringIO.StringIO(s) g = StringIO.StringIO() encode(f, g) return g.getvalue()
|
def encodestring(s): """Encode a string.""" pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return "".join(pieces)
| 7,534
|
def decodestring(s): """Decode a string.""" import StringIO f = StringIO.StringIO(s) g = StringIO.StringIO() decode(f, g) return g.getvalue()
|
def decodestring(s): """Decode a string.""" return binascii.a2b_base64(s)
| 7,535
|
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument. Arguments: qs: URL-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value inicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ name_value_pairs = string.splitfields(qs, '&') dict = {} for name_value in name_value_pairs: nv = string.splitfields(name_value, '=') if len(nv) != 2: if strict_parsing: raise ValueError, "bad query field: %s" % `name_value` continue name = urllib.unquote(string.replace(nv[0], '+', ' ')) value = urllib.unquote(string.replace(nv[1], '+', ' ')) if len(value) or keep_blank_values: if dict.has_key (name): dict[name].append(value) else: dict[name] = [value] return dict
|
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument. Arguments: qs: URL-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value inicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ name_value_pairs = string.splitfields(qs, '&') r=[] for name_value in name_value_pairs: nv = string.splitfields(name_value, '=') if len(nv) != 2: if strict_parsing: raise ValueError, "bad query field: %s" % `name_value` continue name = urllib.unquote(string.replace(nv[0], '+', ' ')) value = urllib.unquote(string.replace(nv[1], '+', ' ')) if len(value) or keep_blank_values: if dict.has_key (name): dict[name].append(value) else: dict[name] = [value] return dict
| 7,536
|
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument. Arguments: qs: URL-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value inicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ name_value_pairs = string.splitfields(qs, '&') dict = {} for name_value in name_value_pairs: nv = string.splitfields(name_value, '=') if len(nv) != 2: if strict_parsing: raise ValueError, "bad query field: %s" % `name_value` continue name = urllib.unquote(string.replace(nv[0], '+', ' ')) value = urllib.unquote(string.replace(nv[1], '+', ' ')) if len(value) or keep_blank_values: if dict.has_key (name): dict[name].append(value) else: dict[name] = [value] return dict
|
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument. Arguments: qs: URL-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value inicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ name_value_pairs = string.splitfields(qs, '&') dict = {} for name_value in name_value_pairs: nv = string.splitfields(name_value, '=') if len(nv) != 2: if strict_parsing: raise ValueError, "bad query field: %s" % `name_value` continue name = urllib.unquote(string.replace(nv[0], '+', ' ')) value = urllib.unquote(string.replace(nv[1], '+', ' ')) r.append(name, value) return r
| 7,537
|
def read_urlencoded(self): """Internal: read data in query string format.""" qs = self.fp.read(self.length) dict = parse_qs(qs, self.keep_blank_values, self.strict_parsing) self.list = [] for key, valuelist in dict.items(): for value in valuelist: self.list.append(MiniFieldStorage(key, value)) self.skip_lines()
|
def read_urlencoded(self): """Internal: read data in query string format.""" qs = self.fp.read(self.length) self.list = list = [] for key, value in parse_qsl(qs, self.keep_blank_values, self.strict_parsing): list.append(MiniFieldStorage(key, value)) self.skip_lines()
| 7,538
|
def post(self, f): resp = self.shortcmd('POST') # Raises error_??? if posting is not allowed if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line == '.': line = '..' self.putline(line) self.putline('.') return self.getresp()
|
def post(self, f): resp = self.shortcmd('POST') # Raises error_??? if posting is not allowed if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.' + line self.putline(line) self.putline('.') return self.getresp()
| 7,539
|
def ihave(self, id, f): resp = self.shortcmd('IHAVE ' + id) # Raises error_??? if the server already has it if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line == '.': line = '..' self.putline(line) self.putline('.') return self.getresp()
|
def ihave(self, id, f): resp = self.shortcmd('IHAVE ' + id) # Raises error_??? if the server already has it if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.' + line self.putline(line) self.putline('.') return self.getresp()
| 7,540
|
def do_show(self):
|
def do_show(self):
| 7,541
|
def do_all(self):
|
def do_all(self):
| 7,542
|
def do_roulette(self):
|
def do_roulette(self):
| 7,543
|
def do_recent(self):
|
def do_recent(self):
| 7,544
|
def do_query(self):
|
def do_query(self):
| 7,545
|
def do_edit(self):
|
def do_edit(self):
| 7,546
|
def do_review(self):
|
def do_review(self):
| 7,547
|
def checkin(self):
|
def checkin(self):
| 7,548
|
def showedit(self, name, title, text):
|
def showedit(self, name, title, text):
| 7,549
|
def showedit(self, name, title, text):
|
def showedit(self, name, title, text):
| 7,550
|
def read(self, name):
|
def read(self, name):
| 7,551
|
def show(self, name, title, text, edit=0):
|
def show(self, name, title, text, edit=0):
| 7,552
|
def testAttributes(self): # test that exception attributes are happy
|
def testAttributes(self): # test that exception attributes are happy
| 7,553
|
def testAttributes(self): # test that exception attributes are happy
|
def testAttributes(self): # test that exception attributes are happy
| 7,554
|
def testAttributes(self): # test that exception attributes are happy
|
def testAttributes(self): # test that exception attributes are happy
| 7,555
|
def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if type(klass) != types.ClassType: raise TypeError, "setLoggerClass is expecting a class" if not issubclass(klass, Logger): raise TypeError, "logger not derived from logging.Logger: " + \ klass.__name__ global _loggerClass _loggerClass = klass
|
def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError, "logger not derived from logging.Logger: " + \ klass.__name__ global _loggerClass _loggerClass = klass
| 7,556
|
def test_both(): "Test mmap module on Unix systems and Windows" # Create an mmap'ed file f = open('foo', 'w+') # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages' assert string.find(m, 'foo') == PAGESIZE print ' Length of file:', len(m) / float(PAGESIZE), 'pages' assert len(m) == 2*PAGESIZE print ' Contents of byte 0:', repr(m[0]) assert m[0] == '\0' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '\0\0\0' # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3]='bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) assert m[0] == '3' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '3\0\0' print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7] assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0' m.flush() # Test doing a regular expression match in an mmap'ed file match=re.search('[A-Za-z]+', m) if match == None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length assert start == PAGESIZE assert end == PAGESIZE + 6 # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' assert m.tell() == 0 m.seek(42,1) print ' Seek to 42nd byte' assert m.tell() == 42 m.seek(0,2) print ' Seek to last byte' assert m.tell() == len(m) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' # Try resizing map print ' Attempting resize()' try: m.resize( 512 ) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported pass m.close() os.unlink("foo") print ' Test passed'
|
def test_both(): "Test mmap module on Unix systems and Windows" # Create an mmap'ed file f = open('foo', 'w+') # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages' assert string.find(m, 'foo') == PAGESIZE print ' Length of file:', len(m) / float(PAGESIZE), 'pages' assert len(m) == 2*PAGESIZE print ' Contents of byte 0:', repr(m[0]) assert m[0] == '\0' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '\0\0\0' # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3]='bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) assert m[0] == '3' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '3\0\0' print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7] assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0' m.flush() # Test doing a regular expression match in an mmap'ed file match=re.search('[A-Za-z]+', m) if match == None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length assert start == PAGESIZE assert end == PAGESIZE + 6 # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' assert m.tell() == 0 m.seek(42,1) print ' Seek to 42nd byte' assert m.tell() == 42 m.seek(0,2) print ' Seek to last byte' assert m.tell() == len(m) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' # Try resizing map print ' Attempting resize()' try: m.resize( 512 ) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported pass m.close() os.unlink("foo") print ' Test passed'
| 7,557
|
def test_both(): "Test mmap module on Unix systems and Windows" # Create an mmap'ed file f = open('foo', 'w+') # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages' assert string.find(m, 'foo') == PAGESIZE print ' Length of file:', len(m) / float(PAGESIZE), 'pages' assert len(m) == 2*PAGESIZE print ' Contents of byte 0:', repr(m[0]) assert m[0] == '\0' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '\0\0\0' # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3]='bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) assert m[0] == '3' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '3\0\0' print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7] assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0' m.flush() # Test doing a regular expression match in an mmap'ed file match=re.search('[A-Za-z]+', m) if match == None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length assert start == PAGESIZE assert end == PAGESIZE + 6 # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' assert m.tell() == 0 m.seek(42,1) print ' Seek to 42nd byte' assert m.tell() == 42 m.seek(0,2) print ' Seek to last byte' assert m.tell() == len(m) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' # Try resizing map print ' Attempting resize()' try: m.resize( 512 ) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported pass m.close() os.unlink("foo") print ' Test passed'
|
def test_both(): "Test mmap module on Unix systems and Windows" # Create an mmap'ed file f = open('foo', 'w+') # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages' assert string.find(m, 'foo') == PAGESIZE print ' Length of file:', len(m) / float(PAGESIZE), 'pages' assert len(m) == 2*PAGESIZE print ' Contents of byte 0:', repr(m[0]) assert m[0] == '\0' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '\0\0\0' # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3]='bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) assert m[0] == '3' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '3\0\0' print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7] assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0' m.flush() # Test doing a regular expression match in an mmap'ed file match=re.search('[A-Za-z]+', m) if match == None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length assert start == PAGESIZE assert end == PAGESIZE + 6 # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' assert m.tell() == 0 m.seek(42,1) print ' Seek to 42nd byte' assert m.tell() == 42 m.seek(0,2) print ' Seek to last byte' assert m.tell() == len(m) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' # Try resizing map print ' Attempting resize()' try: m.resize( 512 ) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported pass m.close() os.unlink("foo") print ' Test passed'
| 7,558
|
def test_both(): "Test mmap module on Unix systems and Windows" # Create an mmap'ed file f = open('foo', 'w+') # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages' assert string.find(m, 'foo') == PAGESIZE print ' Length of file:', len(m) / float(PAGESIZE), 'pages' assert len(m) == 2*PAGESIZE print ' Contents of byte 0:', repr(m[0]) assert m[0] == '\0' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '\0\0\0' # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3]='bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) assert m[0] == '3' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '3\0\0' print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7] assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0' m.flush() # Test doing a regular expression match in an mmap'ed file match=re.search('[A-Za-z]+', m) if match == None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length assert start == PAGESIZE assert end == PAGESIZE + 6 # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' assert m.tell() == 0 m.seek(42,1) print ' Seek to 42nd byte' assert m.tell() == 42 m.seek(0,2) print ' Seek to last byte' assert m.tell() == len(m) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' # Try resizing map print ' Attempting resize()' try: m.resize( 512 ) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported pass m.close() os.unlink("foo") print ' Test passed'
|
def test_both(): "Test mmap module on Unix systems and Windows" # Create an mmap'ed file f = open('foo', 'w+') # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages' assert string.find(m, 'foo') == PAGESIZE print ' Length of file:', len(m) / float(PAGESIZE), 'pages' assert len(m) == 2*PAGESIZE print ' Contents of byte 0:', repr(m[0]) assert m[0] == '\0' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '\0\0\0' # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3]='bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) assert m[0] == '3' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '3\0\0' print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7] assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0' m.flush() # Test doing a regular expression match in an mmap'ed file match=re.search('[A-Za-z]+', m) if match == None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length assert start == PAGESIZE assert end == PAGESIZE + 6 # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' assert m.tell() == 0 m.seek(42,1) print ' Seek to 42nd byte' assert m.tell() == 42 m.seek(0,2) print ' Seek to last byte' assert m.tell() == len(m) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' # Try resizing map print ' Attempting resize()' try: m.resize( 512 ) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported pass m.close() os.unlink("foo") print ' Test passed'
| 7,559
|
def test_rmtree_errors(self): # filename is guaranteed not to exist filename = tempfile.mktemp() self.assertRaises(OSError, shutil.rmtree, filename)
|
def test_rmtree_errors(self): # filename is guaranteed not to exist filename = tempfile.mktemp() self.assertRaises(OSError, shutil.rmtree, filename)
| 7,560
|
def gettempprefix(): global template if template == None: if os.name == 'posix': template = '@' + `os.getpid()` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template
|
def gettempprefix(): global template, _pid if os.name == 'posix' and _pid and _pid != os.getpid(): template = None if template is None: if os.name == 'posix': template = '@' + `os.getpid()` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template
| 7,561
|
def gettempprefix(): global template if template == None: if os.name == 'posix': template = '@' + `os.getpid()` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template
|
def gettempprefix(): global template if template == None: if os.name == 'posix': _pid = os.getpid() template = '@' + `_pid` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template
| 7,562
|
def listclasses(self): dir, file = os.path.split(self.file) name, ext = os.path.splitext(file) if os.path.normcase(ext) != ".py": return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) except ImportError, msg: return [] items = [] self.classes = {} for key, cl in dict.items(): if cl.module == name: s = key if cl.super: supers = [] for sup in cl.super: if type(sup) is type(''): sname = sup else: sname = sup.name if sup.module != cl.module: sname = "%s.%s" % (sup.module, sname) supers.append(sname) s = s + "(%s)" % ", ".join(supers) items.append((cl.lineno, s)) self.classes[s] = cl items.sort() list = [] for item, s in items: list.append(s) return list
|
def listclasses(self): dir, file = os.path.split(self.file) name, ext = os.path.splitext(file) if os.path.normcase(ext) != ".py": return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) except ImportError, msg: return [] items = [] self.classes = {} for key, cl in dict.items(): if cl.module == name: s = key if hasattr(cl, 'super') and cl.super: supers = [] for sup in cl.super: if type(sup) is type(''): sname = sup else: sname = sup.name if sup.module != cl.module: sname = "%s.%s" % (sup.module, sname) supers.append(sname) s = s + "(%s)" % ", ".join(supers) items.append((cl.lineno, s)) self.classes[s] = cl items.sort() list = [] for item, s in items: list.append(s) return list
| 7,563
|
def __init__(self, password_mgr=None): if password_mgr is None: password_mgr = HTTPPasswordMgr() self.passwd = password_mgr self.add_password = self.passwd.add_password self.__current_realm = None # if __current_realm is not None, then the server must have # refused our name/password and is asking for authorization # again. must be careful to set it to None on successful # return.
|
def __init__(self, password_mgr=None): if password_mgr is None: password_mgr = HTTPPasswordMgr() self.passwd = password_mgr self.add_password = self.passwd.add_password self.__current_realm = None # if __current_realm is not None, then the server must have # refused our name/password and is asking for authorization # again. must be careful to set it to None on successful # return.
| 7,564
|
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None
|
def retry_http_basic_auth(self, host, req, realm): user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None
| 7,565
|
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None
|
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = 'Basic %s' % base64.encodestring(raw).strip() if req.headers.get(self.auth_header, None) == auth: return None req.add_header(self.auth_header, auth) return self.parent.open(req) else: return None
| 7,566
|
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None
|
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None
| 7,567
|
def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] return self.http_error_auth_reqed('www-authenticate', host, req, headers)
|
def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] return self.http_error_auth_reqed('www-authenticate', host, req, headers)
| 7,568
|
def __init__(self, passwd=None): if passwd is None: passwd = HTTPPasswordMgr() self.passwd = passwd self.add_password = self.passwd.add_password self.__current_realm = None
|
def __init__(self, passwd=None): if passwd is None: passwd = HTTPPasswordMgr() self.passwd = passwd self.add_password = self.passwd.add_password self.__current_realm = None
| 7,569
|
def http_error_auth_reqed(self, authreq, host, req, headers): authreq = headers.get(self.header, None) if authreq: kind = authreq.split()[0] if kind == 'Digest': return self.retry_http_digest_auth(req, authreq)
|
def http_error_auth_reqed(self, authreq, host, req, headers): authreq = headers.get(self.auth_header, None) if authreq: kind = authreq.split()[0] if kind == 'Digest': return self.retry_http_digest_auth(req, authreq)
| 7,570
|
def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: req.add_header(self.header, 'Digest %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp
|
def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: auth_val = 'Digest %s' % auth if req.headers.get(self.auth_header, None) == auth_val: return None req.add_header(self.auth_header, auth_val) resp = self.parent.open(req) self.__current_realm = None return resp
| 7,571
|
def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: req.add_header(self.header, 'Digest %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp
|
def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: req.add_header(self.header, 'Digest %s' % auth) resp = self.parent.open(req) return resp
| 7,572
|
def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] algorithm = chal.get('algorithm', 'MD5') # mod_digest doesn't send an opaque, even though it isn't # supposed to be optional opaque = chal.get('opaque', None) except KeyError: return None
|
def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] algorithm = chal.get('algorithm', 'MD5') # mod_digest doesn't send an opaque, even though it isn't # supposed to be optional opaque = chal.get('opaque', None) except KeyError: return None
| 7,573
|
def copyfile(self, source, outputfile): """Copy all data between two file objects.
|
def copyfile(self, source, outputfile): """Copy all data between two file objects.
| 7,574
|
def bpprint(self): if self.temporary: disp = 'del ' else: disp = 'keep ' if self.enabled: disp = disp + 'yes' else: disp = disp + 'no ' print '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) if self.cond: print '\tstop only if %s' % (self.cond,) if self.ignore: print '\tignore next %d hits' % (self.ignore) if (self.hits): if (self.hits > 1): ss = 's' else: ss = '' print ('\tbreakpoint already hit %d time%s' % (self.hits, ss))
|
def bpprint(self): if self.temporary: disp = 'del ' else: disp = 'keep ' if self.enabled: disp = disp + 'yes ' else: disp = disp + 'no ' print '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) if self.cond: print '\tstop only if %s' % (self.cond,) if self.ignore: print '\tignore next %d hits' % (self.ignore) if (self.hits): if (self.hits > 1): ss = 's' else: ss = '' print ('\tbreakpoint already hit %d time%s' % (self.hits, ss))
| 7,575
|
def test_one(n): global mutate, dict1, dict2, dict1keys, dict2keys # Fill the dicts without mutating them. mutate = 0 dict1keys = fill_dict(dict1, range(n), n) dict2keys = fill_dict(dict2, range(n), n) # Enable mutation, then compare the dicts so long as they have the # same size. mutate = 1 if verbose: print "trying w/ lengths", len(dict1), len(dict2), while dict1 and len(dict1) == len(dict2): if verbose: print ".", c = cmp(dict1, dict2) if verbose: print
|
def test_one(n): global mutate, dict1, dict2, dict1keys, dict2keys # Fill the dicts without mutating them. mutate = 0 dict1keys = fill_dict(dict1, range(n), n) dict2keys = fill_dict(dict2, range(n), n) # Enable mutation, then compare the dicts so long as they have the # same size. mutate = 1 if verbose: print "trying w/ lengths", len(dict1), len(dict2), while dict1 and len(dict1) == len(dict2): if verbose: print ".", if random.random() < 0.5: c = cmp(dict1, dict2) else: c = dict1 == dict2 if verbose: print
| 7,576
|
def __init__(self, flist=None, filename=None, key=None, root=None): self.flist = flist root = root or flist.root self.root = root if flist: self.vars = flist.vars self.menubar = Menu(root) self.top = top = self.Toplevel(root, menu=self.menubar) self.vbar = vbar = Scrollbar(top, name='vbar') self.text = text = Text(top, name='text', padx=5, background="white", wrap="none")
|
def __init__(self, flist=None, filename=None, key=None, root=None): self.flist = flist root = root or flist.root self.root = root if flist: self.vars = flist.vars self.menubar = Menu(root) self.top = top = self.Toplevel(root, menu=self.menubar) self.vbar = vbar = Scrollbar(top, name='vbar') self.text = text = Text(top, name='text', padx=5, background="white", wrap="none")
| 7,577
|
def postwindowsmenu(self): # Only called when Windows menu exists # XXX Actually, this Just-In-Time updating interferes # XXX badly with the tear-off feature. It would be better # XXX to update all Windows menus whenever the list of windows # XXX changes. menu = self.menudict['windows'] end = menu.index("end") if end is None: end = -1 if end > self.wmenu_end: menu.delete(self.wmenu_end+1, end) import WindowList WindowList.add_windows_to_menu(menu)
|
def postwindowsmenu(self): # Only called when Windows menu exists # XXX Actually, this Just-In-Time updating interferes # XXX badly with the tear-off feature. It would be better # XXX to update all Windows menus whenever the list of windows # XXX changes. menu = self.menudict['windows'] end = menu.index("end") if end is None: end = -1 if end > self.wmenu_end: menu.delete(self.wmenu_end+1, end) WindowList.add_windows_to_menu(menu)
| 7,578
|
def __init__(self, master=None, cnf={}, **kw): if kw: cnf = _cnfmerge((cnf, kw)) fcnf = {} for k in cnf.keys(): if type(k) == ClassType or k == 'name': fcnf[k] = cnf[k] del cnf[k] self.frame = apply(Frame, (master,), fcnf) self.vbar = Scrollbar(self.frame, name='vbar') self.vbar.pack(side=RIGHT, fill=Y) cnf['name'] = 'text' apply(Text.__init__, (self, self.frame), cnf) self.pack(side=LEFT, fill=BOTH, expand=1) self['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.yview
|
def __init__(self, master=None, cnf={}, **kw): if kw: cnf = _cnfmerge((cnf, kw)) fcnf = {} for k in cnf.keys(): if type(k) == ClassType or k == 'name': fcnf[k] = cnf[k] del cnf[k] self.frame = apply(Frame, (master,), fcnf) self.vbar = Scrollbar(self.frame, name='vbar') self.vbar.pack(side=RIGHT, fill=Y) cnf['name'] = 'text' apply(Text.__init__, (self, self.frame), cnf) self.pack(side=LEFT, fill=BOTH, expand=1) self['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.yview
| 7,579
|
def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything rfc822.parseaddr can handle.""" m=None try: m=rfc822.parseaddr(addr)[1] except AttributeError: pass if not m: #something weird here.. punt -ddm return addr else: return "<%s>" % m
|
def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything rfc822.parseaddr can handle. """ m=None try: m=rfc822.parseaddr(addr)[1] except AttributeError: pass if not m: #something weird here.. punt -ddm return addr else: return "<%s>" % m
| 7,580
|
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line.""" return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
|
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
| 7,581
|
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line.""" return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
|
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line.""" return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
| 7,582
|
def __init__(self, host = '', port = 0): """Initialize a new instance.
|
def __init__(self, host = '', port = 0): """Initialize a new instance.
| 7,583
|
def set_debuglevel(self, debuglevel): """Set the debug output level.
|
def set_debuglevel(self, debuglevel): """Set the debug output level.
| 7,584
|
def connect(self, host='localhost', port = 0): """Connect to a host on a given port.
|
def connect(self, host='localhost', port = 0): """Connect to a host on a given port.
| 7,585
|
def putcmd(self, cmd, args=""): """Send a command to the server. """ str = '%s %s%s' % (cmd, args, CRLF) self.send(str)
|
def putcmd(self, cmd, args=""): """Send a command to the server.""" str = '%s %s%s' % (cmd, args, CRLF) self.send(str)
| 7,586
|
def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (note : multiline responses converted to a single, multiline string) """ resp=[] self.file = self.sock.makefile('rb') while 1: line = self.file.readline() if self.debuglevel > 0: print 'reply:', `line` resp.append(string.strip(line[4:])) code=line[:3] #check if multiline resp if line[3:4]!="-": break try: errcode = string.atoi(code) except(ValueError): errcode = -1
|
def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (multiline responses are converted to a single, multiline string). """ resp=[] self.file = self.sock.makefile('rb') while 1: line = self.file.readline() if self.debuglevel > 0: print 'reply:', `line` resp.append(string.strip(line[4:])) code=line[:3] #check if multiline resp if line[3:4]!="-": break try: errcode = string.atoi(code) except(ValueError): errcode = -1
| 7,587
|
def docmd(self, cmd, args=""): """ Send a command, and return its response code """ self.putcmd(cmd,args) (code,msg)=self.getreply() return code
|
def docmd(self, cmd, args=""): """Send a command, and return its response code.""" self.putcmd(cmd,args) (code,msg)=self.getreply() return code
| 7,588
|
def docmd(self, cmd, args=""): """ Send a command, and return its response code """ self.putcmd(cmd,args) (code,msg)=self.getreply() return code
|
def docmd(self, cmd, args=""): """ Send a command, and return its response code """ self.putcmd(cmd,args) (code,msg)=self.getreply() return code
| 7,589
|
def helo(self, name=''): """ SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("helo",name) (code,msg)=self.getreply() self.helo_resp=msg return code
|
def helo(self, name=''): """SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host. """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("helo",name) (code,msg)=self.getreply() self.helo_resp=msg return code
| 7,590
|
def helo(self, name=''): """ SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("helo",name) (code,msg)=self.getreply() self.helo_resp=msg return code
|
def helo(self, name=''): """ SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("helo",name) (code,msg)=self.getreply() self.helo_resp=msg return code
| 7,591
|
def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("ehlo",name) (code,msg)=self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exception if # that happens -ddm if code == -1 and len(msg) == 0: raise SMTPServerDisconnected self.ehlo_resp=msg if code<>250: return code self.does_esmtp=1 #parse the ehlo responce -ddm resp=string.split(self.ehlo_resp,'\n') del resp[0] for each in resp: m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each) if m: feature=string.lower(m.group("feature")) params=string.strip(m.string[m.end("feature"):]) self.esmtp_features[feature]=params return code
|
def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("ehlo",name) (code,msg)=self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exception if # that happens -ddm if code == -1 and len(msg) == 0: raise SMTPServerDisconnected self.ehlo_resp=msg if code<>250: return code self.does_esmtp=1 #parse the ehlo responce -ddm resp=string.split(self.ehlo_resp,'\n') del resp[0] for each in resp: m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each) if m: feature=string.lower(m.group("feature")) params=string.strip(m.string[m.end("feature"):]) self.esmtp_features[feature]=params return code
| 7,592
|
def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("ehlo",name) (code,msg)=self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exception if # that happens -ddm if code == -1 and len(msg) == 0: raise SMTPServerDisconnected self.ehlo_resp=msg if code<>250: return code self.does_esmtp=1 #parse the ehlo responce -ddm resp=string.split(self.ehlo_resp,'\n') del resp[0] for each in resp: m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each) if m: feature=string.lower(m.group("feature")) params=string.strip(m.string[m.end("feature"):]) self.esmtp_features[feature]=params return code
|
def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("ehlo",name) (code,msg)=self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exception if # that happens -ddm if code == -1 and len(msg) == 0: raise SMTPServerDisconnected self.ehlo_resp=msg if code<>250: return code self.does_esmtp=1 #parse the ehlo responce -ddm resp=string.split(self.ehlo_resp,'\n') del resp[0] for each in resp: m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each) if m: feature=string.lower(m.group("feature")) params=string.strip(m.string[m.end("feature"):]) self.esmtp_features[feature]=params return code
| 7,593
|
def help(self, args=''): """SMTP 'help' command. Returns help text from server.""" self.putcmd("help", args) (code,msg)=self.getreply() return msg
|
def help(self, args=''): """SMTP 'help' command. Returns help text from server.""" self.putcmd("help", args) (code,msg)=self.getreply() return msg
| 7,594
|
def rset(self): """SMTP 'rset' command. Resets session.""" code=self.docmd("rset") return code
|
def rset(self): """SMTP 'rset' command -- resets session.""" code=self.docmd("rset") return code
| 7,595
|
def noop(self): """SMTP 'noop' command. Doesn't do anything :>""" code=self.docmd("noop") return code
|
def noop(self): """SMTP 'noop' command -- doesn't do anything :>""" code=self.docmd("noop") return code
| 7,596
|
def mail(self,sender,options=[]): """SMTP 'mail' command. Begins mail xfer session.""" optionlist = '' if options and self.does_esmtp: optionlist = string.join(options, ' ') self.putcmd("mail", "FROM:%s %s" % (quoteaddr(sender) ,optionlist)) return self.getreply()
|
def mail(self,sender,options=[]): """SMTP 'mail' command -- begins mail xfer session.""" optionlist = '' if options and self.does_esmtp: optionlist = string.join(options, ' ') self.putcmd("mail", "FROM:%s %s" % (quoteaddr(sender) ,optionlist)) return self.getreply()
| 7,597
|
def rcpt(self,recip,options=[]): """SMTP 'rcpt' command. Indicates 1 recipient for this mail.""" optionlist = '' if options and self.does_esmtp: optionlist = string.join(options, ' ') self.putcmd("rcpt","TO:%s %s" % (quoteaddr(recip),optionlist)) return self.getreply()
|
def rcpt(self,recip,options=[]): """SMTP 'rcpt' command -- indicates 1 recipient for this mail.""" optionlist = '' if options and self.does_esmtp: optionlist = string.join(options, ' ') self.putcmd("rcpt","TO:%s %s" % (quoteaddr(recip),optionlist)) return self.getreply()
| 7,598
|
def data(self,msg): """SMTP 'DATA' command. Sends message data to server. Automatically quotes lines beginning with a period per rfc821. """ self.putcmd("data") (code,repl)=self.getreply() if self.debuglevel >0 : print "data:", (code,repl) if code <> 354: return -1 else: self.send(quotedata(msg)) self.send("%s.%s" % (CRLF, CRLF)) (code,msg)=self.getreply() if self.debuglevel >0 : print "data:", (code,msg) return code
|
def data(self,msg): """SMTP 'DATA' command -- sends message data to server. Automatically quotes lines beginning with a period per rfc821. """ self.putcmd("data") (code,repl)=self.getreply() if self.debuglevel >0 : print "data:", (code,repl) if code <> 354: return -1 else: self.send(quotedata(msg)) self.send("%s.%s" % (CRLF, CRLF)) (code,msg)=self.getreply() if self.debuglevel >0 : print "data:", (code,msg) return code
| 7,599
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.