rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
return -1 self.handle_data("&") i = self.updatepos(i, i + 1) | break elif (i + 1) < n: self.handle_data("&") i = self.updatepos(i, i + 1) else: break | def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < ... |
def parse_comment(self, i): | def parse_comment(self, i, report=1): | def parse_comment(self, i): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j |
j = match.start() self.handle_comment(rawdata[i+4: j]) | if report: j = match.start() self.handle_comment(rawdata[i+4: j]) | def parse_comment(self, i): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j |
self.handle_decl(rawdata[i+2:j]) | data = rawdata[i+2:j] if decltype == "doctype": self.handle_decl(data) else: self.unknown_decl(data) | def parse_declaration(self, i): # This is some sort of declaration; in "HTML as # deployed," this should only be the document type # declaration ("<!DOCTYPE html...>"). rawdata = self.rawdata j = i + 2 assert rawdata[i:j] == "<!", "unexpected call to parse_declaration" if rawdata[j:j+1] in ("-", ""): # Start of comment... |
window.do_activate(modifiers & 1, event) | window.do_activate(message & 1, event) | def do_suspendresume(self, event): (what, message, when, where, modifiers) = event wid = FrontWindow() if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_activate(modifiers & 1, event) |
if (sld.lower() in ( "co", "ac", "com", "edu", "org", "net", "gov", "mil", "int") and len(tld) == 2): | if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: | def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request... |
return addinfo(fp, headers) | return addinfourl(fp, headers, self.openedurl) | def open_http(self, url): import httplib if type(url) is type(""): host, selector = splithost(url) user_passwd, host = splituser(host) else: host, selector = url urltype, rest = splittype(selector) if string.lower(urltype) == 'http': realhost, rest = splithost(rest) user_passwd, realhost = splituser(realhost) if user_p... |
return addinfo(fp, noheaders()) | return addinfourl(fp, noheaders(), self.openedurl) | def open_gopher(self, url): import gopherlib host, selector = splithost(url) if not host: raise IOError, ('gopher error', 'no host given') type, selector = splitgophertype(selector) selector, query = splitquery(selector) selector = unquote(selector) if query: query = unquote(query) fp = gopherlib.send_query(selector, q... |
if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) | if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) | def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(url2pathname(file), 'r'), noheaders()) raise... |
return addinfo(open(url2pathname(file), 'r'), noheaders()) | return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) | def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(url2pathname(file), 'r'), noheaders()) raise... |
return addinfo(self.ftpcache[key].retrfile(file, type), noheaders()) | return addinfourl(self.ftpcache[key].retrfile(file, type), noheaders(), self.openedurl) | def open_ftp(self, url): host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT path... |
return addinfo(fp, headers) | return addinfourl(fp, headers, self.openedurl) | def http_error_default(self, url, fp, errcode, errmsg, headers): return addinfo(fp, headers) |
print '%s.%s%s =? %s... ' % (repr(input), method, args, output), | print '%s.%s%s =? %s... ' % (repr(input), method, args, repr(output)), | def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, output), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output: if verbose: print 'no' print '*',f, `input`, `output`, `v... |
if value != output: | if value != output or type(value) is not type(output): | def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, output), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output: if verbose: print 'no' print '*',f, `input`, `output`, `v... |
def __init__(self): self.seq = 'wxyz' | def __init__(self, seq): self.seq = seq | def __init__(self): self.seq = 'wxyz' |
test('join', u' ', u'w x y z', Sequence()) | test('join', u' ', u'w x y z', Sequence('wxyz')) | def __getitem__(self, i): return self.seq[i] |
class BadSeq(Sequence): def __init__(self): self.seq = [7, u'hello', 123L] test('join', u' ', TypeError, BadSeq()) | test('join', u' ', TypeError, Sequence([7, u'hello', 123L])) test('join', ' ', u'a b c d', [u'a', u'b', u'c', u'd']) test('join', ' ', u'a b c d', ['a', 'b', u'c', u'd']) test('join', '', u'abcd', (u'a', u'b', u'c', u'd')) test('join', ' ', u'w x y z', Sequence(u'wxyz')) test('join', ' ', TypeError, 7) | def __getitem__(self, i): return self.seq[i] |
self.assert_(len(read) == 1024, "Error performing sendall.") read = filter(lambda x: x == 'f', read) self.assert_(len(read) == 1024, "Error performing sendall.") | msg += read self.assertEqual(msg, 'f' * 2048) | def testSendAll(self): # Testing sendall() with a 2048 byte string over TCP while 1: read = self.cli_conn.recv(1024) if not read: break self.assert_(len(read) == 1024, "Error performing sendall.") read = filter(lambda x: x == 'f', read) self.assert_(len(read) == 1024, "Error performing sendall.") |
return filename | components = string.split(filename, ':') for i in range(1, len(components)): if components[i] == '..': components[i] = '' return string.join(components, ':') | def _filename_to_abs(self, filename): # Some filenames seem to be unix-like. Convert to Mac names. |
def writexml(self, writer): writer.write("<" + self.tagName) | def writexml(self, writer, indent="", addindent="", newl=""): writer.write(indent+"<" + self.tagName) | def writexml(self, writer): writer.write("<" + self.tagName) |
writer.write(">") | writer.write(">%s"%(newl)) | def writexml(self, writer): writer.write("<" + self.tagName) |
node.writexml(writer) writer.write("</%s>" % self.tagName) else: writer.write("/>") | node.writexml(writer,indent+addindent,addindent,newl) writer.write("%s</%s>%s" % (indent,self.tagName,newl)) else: writer.write("/>%s"%(newl)) | def writexml(self, writer): writer.write("<" + self.tagName) |
def writexml(self, writer): writer.write("<!--%s-->" % self.data) | def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s<!--%s-->%s" % (indent,self.data,newl)) | def writexml(self, writer): writer.write("<!--%s-->" % self.data) |
def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data)) | def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl)) | def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data)) |
def writexml(self, writer): _write_data(writer, self.data) | def writexml(self, writer, indent="", addindent="", newl=""): _write_data(writer, "%s%s%s"%(indent, self.data, newl)) | def writexml(self, writer): _write_data(writer, self.data) |
def writexml(self, writer): | def writexml(self, writer, indent="", addindent="", newl=""): | def writexml(self, writer): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer) |
node.writexml(writer) | node.writexml(writer, indent, addindent, newl) | def writexml(self, writer): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer) |
stats = os.stat(localname) | try: stats = os.stat(localname) except OSError, e: raise IOError(e.errno, e.strerror, e.filename) | def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, rfc822, StringIO host, file = splithost(url) localname = url2pathname(file) stats = os.stat(localname) size = stats.st_size modified = rfc822.formatdate(stats.st_mtime) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(Str... |
if sys.platform in ['unixware7']: testit('atan2(0, 1)', math.atan2(0, 1), math.pi) else: testit('atan2(0, 1)', math.atan2(0, 1), 0) | testit('atan2(0, 1)', math.atan2(0, 1), 0) | def testit(name, value, expected): if abs(value-expected) > eps: raise TestFailed, '%s returned %f, expected %f'%\ (name, value, expected) |
self.bytebuffer = "" | self.buffer = "" | def reset(self): IncrementalDecoder.reset(self) self.bytebuffer = "" |
suite.addTest(unittest.makeSuite(BasicUDPTest)) | if sys.platform != 'mac': suite.addTest(unittest.makeSuite(BasicUDPTest)) | def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(GeneralModuleTests)) suite.addTest(unittest.makeSuite(BasicTCPTest)) suite.addTest(unittest.makeSuite(BasicUDPTest)) suite.addTest(unittest.makeSuite(NonBlockingTCPTests)) suite.addTest(unittest.makeSuite(FileObjectClassTestCase)) suite.addT... |
This is the normal interface: it return a stripped | This is the normal interface: it returns a stripped | def getheader(self, name, default=None): """Get the header value for a name. This is the normal interface: it return a stripped version of the header value for a given header name, or None if it doesn't exist. This uses the dictionary version which finds the *last* such header. """ try: return self.dict[string.lower(... |
vereq(iter(T()).next(), '0!!!') | vereq(iter(T((1,2))).next(), 1) | def __getitem__(self, key): return str(key) + '!!!' |
vereq(iter(L()).next(), '0!!!') | vereq(iter(L([1,2])).next(), 1) | def __getitem__(self, key): return str(key) + '!!!' |
self.sock.send(data) | bytes = len(data) while bytes > 0: sent = self.sock.send(data) if sent == bytes: break data = data[sent:] bytes = bytes - sent | def send(self, data): """Send data to remote.""" self.sock.send(data) |
if '\n' in text: if string.find(text, '\r\n') >= 0: self._eoln = '\r\n' else: self._eoln = '\n' text = string.replace(text, self._eoln, '\r') change = 0 else: change = 0 self._eoln = '\r' | def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" ... | |
if change > 0: self.editgroup.editor.textchanged() | def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" ... | |
print dir(tas) | print fixdir(dir(tas)) | def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdo... |
print dir(subpar) | print fixdir(dir(subpar)) | def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdo... |
print dir(subsubsub) | print fixdir(dir(subsubsub)) | def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdo... |
if _os.name == "nt": | if _os.name in ("nt", "ce"): | def wstring_at(ptr, size=0): """wstring_at(addr[, size]) -> string |
result = -2147221231 | def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object. | |
ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) | ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*']) | def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object. |
pass | return -2147221231 | def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object. |
result = ctcom.DllGetClassObject(rclsid, riid, ppv) if result == -2147221231: try: ccom = __import__("comtypes.server", globals(), locals(), ['*']) except ImportError: pass else: result = ccom.DllGetClassObject(rclsid, riid, ppv) return result | return ccom.DllGetClassObject(rclsid, riid, ppv) | def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object. |
result = 0 | def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK ... | |
ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) | ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*']) | def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK ... |
pass else: result = ctcom.DllCanUnloadNow() if result != 0: return result try: ccom = __import__("comtypes.server", globals(), locals(), ['*']) except ImportError: return result try: return ccom.DllCanUnloadNow() except AttributeError: pass return result | return 0 return ccom.DllCanUnloadNow() | def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK ... |
pat = r'''-..x..x..x | pat = r'''[l-]..x..x..x | def test_getstatus(self): # This pattern should match 'ls -ld /bin/ls' on any posix # system, however perversely configured. pat = r'''-..x..x..x # It is executable. \s+\d+ # It has some number of links. \s+\w+\s+\w+ # It has a user and group, which may # be named anything. [^/]* # Skip the date. /bi... |
def test(fn = 'f:just samples:just.aif'): | def test(): | def test(fn = 'f:just samples:just.aif'): import aifc af = aifc.open(fn, 'r') print af.getparams() p = Play_Audio_mac() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) p.setnchannels(af.getnchannels()) BUFSIZ = 10000 while 1: data = af.readframes(BUFSIZ) if not data: break p.writeframes(data) p.wait()... |
print "Breakpoint in", filename, "at", lineno | def set_break(self, filename, lineno, temporary=0, cond = None): filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) if not self.breaks.has_key(filename): self.breaks[filename] = [... | |
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step) | def genrange(*a): """Function to implement 'range' as a generator""" start, stop, step = handleargs(a) value = start while value < stop: yield value value += step | def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step) |
Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. | def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step) | |
class Range: | """ | def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step) |
def __init__(self, start, stop, step): if step == 0: raise ValueError, 'range() called with zero step' self.start = start self.stop = stop self.step = step self.len = max(0, int((self.stop - self.start) / self.step)) | def __init__(self, *a): """ Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the range""" self.start, self.stop, self.step = handleargs(a) self.len = max(0, (self.stop - self.start) // self.step) | def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step) |
if 0 <= i < self.len: | if 0 <= i <= self.len: | def __getitem__(self, i): if 0 <= i < self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range' |
def get_python_inc(plat_specific=0): | def get_python_inc(plat_specific=0, prefix=None): | def get_python_inc(plat_specific=0): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ pr... |
prefix = (plat_specific and EXEC_PREFIX or PREFIX) | if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX) | def get_python_inc(plat_specific=0): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ pr... |
def get_python_lib(plat_specific=0, standard_lib=0): | def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): | def get_python_lib(plat_specific=0, standard_lib=0): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shar... |
prefix = (plat_specific and EXEC_PREFIX or PREFIX) | if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX) | def get_python_lib(plat_specific=0, standard_lib=0): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shar... |
_safechars = string.letters + string.digits + '!@%_-+=:,./' | _safechars = string.ascii_letters + string.digits + '!@%_-+=:,./' | def makepipeline(infile, steps, outfile): # Build a list with for each command: # [input filename or '', command string, kind, output filename or ''] list = [] for cmd, kind in steps: list.append(['', cmd, kind, '']) # # Make sure there is at least one step # if not list: list.append(['', 'cat', '--', '']) # # Take ca... |
self.flag = 0 | self.flags[flag] = 0 | def clear_flags(self): """Reset all flags to zero""" for flag in self.flags: self.flag = 0 |
format = ' %' + directive | format = '%' + directive strf_output = time.strftime(format, tt) | def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed... |
time.strptime(time.strftime(format, tt), format) | time.strptime(strf_output, format) | def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed... |
self.fail('conversion specifier: %r failed.' % format) | self.fail("conversion specifier %r failed with '%s' input." % (format, strf_output)) | def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed... |
elif compiler[:3] == "gcc" or compiler[:3] == "g++": return "-Wl,-R" + dir | elif sys.platform[:5] == "hp-ux": return "+s -L" + dir elif compiler[:3] == "gcc" or compiler[:3] == "g++": return "-Wl,-R" + dir | def runtime_library_dir_option(self, dir): # XXX Hackish, at the very least. See Python bug #445902: # http://sourceforge.net/tracker/index.php # ?func=detail&aid=445902&group_id=5470&atid=105470 # Linkers on different platforms need different options to # specify that directories need to be added to the list of # d... |
wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI:PythonCGISlave.py") | wrapper = "PythonCGISlave.py" if not os.path.exists("PythonCGISlave.py"): wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI", wrapper) | def buildcgiapplet(): buildtools.DEBUG=1 # Find the template # (there's no point in proceeding if we can't find it) template = buildtools.findtemplate() wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI:PythonCGISlave.py") # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok =... |
def makeconfig(infp, outfp, modules): | def makeconfig(infp, outfp, modules, with_ifdef=0): | def makeconfig(infp, outfp, modules): m1 = regex.compile('-- ADDMODULE MARKER 1 --') m2 = regex.compile('-- ADDMODULE MARKER 2 --') while 1: line = infp.readline() if not line: break outfp.write(line) if m1 and m1.search(line) >= 0: m1 = None for mod in modules: if mod in never: continue outfp.write('extern void init%s... |
return pos, (val) | return (pos, len(val)) | def _setval(self, pos, val): f = _open(self._datfile, 'rb+') f.seek(pos) f.write(val) f.close() return pos, (val) |
raise socket.error, err | raise socket.error, (err, errorcode[err]) | def connect(self, address): self.connected = False err = self.socket.connect_ex(address) # XXX Should interpret Winsock return values if err in (EINPROGRESS, EALREADY, EWOULDBLOCK): return if err in (0, EISCONN): self.addr = address self.connected = True self.handle_connect() else: raise socket.error, err |
raise socket.error, why | raise | def accept(self): # XXX can return either an address pair or None try: conn, addr = self.socket.accept() return conn, addr except socket.error, why: if why[0] == EWOULDBLOCK: pass else: raise socket.error, why |
raise socket.error, why | raise | def send(self, data): try: result = self.socket.send(data) return result except socket.error, why: if why[0] == EWOULDBLOCK: return 0 else: raise socket.error, why return 0 |
raise socket.error, why | raise | def recv(self, buffer_size): try: data = self.socket.recv(buffer_size) if not data: # a closed connection is indicated by signaling # a read condition, and having recv() return 0. self.handle_close() return '' else: return data except socket.error, why: # winsock sometimes throws ENOTCONN if why[0] in [ECONNRESET, ENOT... |
sectname = "formatter_%s" % form | sectname = "formatter_%s" % string.strip(form) | def _create_formatters(cp): """Create and return formatters""" flist = cp.get("formatters", "keys") if not len(flist): return {} flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: ... |
sectname = "handler_%s" % hand | sectname = "handler_%s" % string.strip(hand) | def _install_handlers(cp, formatters): """Install and return handlers""" hlist = cp.get("handlers", "keys") if not len(hlist): return {} hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.... |
log.addHandler(handlers[hand]) | log.addHandler(handlers[string.strip(hand)]) | def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level... |
logger.addHandler(handlers[hand]) | logger.addHandler(handlers[string.strip(hand)]) | def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level... |
if module not in save_modules: | if module not in save_modules and module.startswith("test."): | def main(tests=None, testdir=None): """Execute a test suite. This also parses command-line options and modifies its behaviour 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 w... |
OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() | if self.returntype.__class__ != OSErrType: OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() | def checkit(self): OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX |
class ResFunction(ResMixIn, FunctionGenerator): pass class ResMethod(ResMixIn, MethodGenerator): pass | class ResFunction(ResMixIn, OSErrFunctionGenerator): pass class ResMethod(ResMixIn, OSErrMethodGenerator): pass | def checkit(self): OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX |
self._link(body, headers, include_dirs, libraries, library_dirs, lang) | src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) | def try_run (self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise. """ from distutils.ccompiler import CompileError, LinkError self._check_compiler(... |
specialsre = re.compile(r'[][\()<>@,:;".]') escapesre = re.compile(r'[][\()"]') | specialsre = re.compile(r'[][\\()<>@,:;".]') escapesre = re.compile(r'[][\\()"]') | def _qdecode(s): import quopri as _quopri |
posix.chmod(tempname, statbuf[ST_MODE] & 0x7777) | posix.chmod(tempname, statbuf[ST_MODE] & 07777) | def fix(filename): |
self._output = open(self._filename, "w") | try: perm = os.fstat(self._file.fileno())[stat.ST_MODE] except: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: os.chmod(self._filename, perm) except: pass | def readline(self): if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = 1 else: if self... |
for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: | for pattern in [' at 0x[0-9a-f]{6,}(>+)$', ' at [0-9A-F]{8,}(>+)$']: | def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '>', text) return text |
return re.sub(pattern, '>', text) | return re.sub(pattern, '\\1', text) | def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '>', text) return text |
suffix, name = '', None if type(thing) is type(''): try: object = locate(thing, forceload) except ErrorDuringImport, value: print value return if not object: print 'no Python documentation found for %s' % repr(thing) return parts = split(thing, '.') if len(parts) > 1: suffix = ' in ' + join(parts[:-1], '.') name = part... | try: object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ pager(title % desc + '\n\n' + text.document(object, name)) except (Impor... | def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" suffix, name = '', None if type(thing) is type(''): try: object = locate(thing, forceload) except ErrorDuringImport, value: print value return if not object: print 'no Python ... |
object = locate(key, forceload) except ErrorDuringImport, value: | object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) file = open(name + '.html', 'w') file.write(page) file.close() print 'wrote', name + '.html' except (ImportError, ErrorDuringImport), value: | def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object = locate(key, forceload) except ErrorDuringImport, value: print value else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page... |
else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key) | def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object = locate(key, forceload) except ErrorDuringImport, value: print value else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page... | |
return type(x) is types.StringType and find(x, os.sep) >= 0 | return isinstance(x, str) and find(x, os.sep) >= 0 | def ispath(x): return type(x) is types.StringType and find(x, os.sep) >= 0 |
_mesg('untagged responses dump:%s%s' % (t, j(l, t))) | _mesg('untagged responses dump:%s%s' % (t, t.join(l))) | def _dump_ur(dict): # Dump untagged responses (in `dict'). l = dict.items() if not l: return t = '\n\t\t' l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l) _mesg('untagged responses dump:%s%s' % (t, j(l, t))) |
def capwords(str, pat): | def capwords(str, pat='[^a-zA-Z0-9_]+'): | def capwords(str, pat): import string words = split(str, pat, 1) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "") |
words = split(str, pat, 1) | words = splitx(str, pat) | def capwords(str, pat): import string words = split(str, pat, 1) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "") |
if value < 0: value = value + 0x100000000L | def write32u(output, value): if value < 0: value = value + 0x100000000L output.write(struct.pack("<L", value)) | |
isize = read32(self.fileobj) if crc32%0x100000000L != self.crc%0x100000000L: | isize = U32(read32(self.fileobj)) if U32(crc32) != U32(self.crc): | def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = read32(s... |
write32(self.fileobj, self.size) | write32u(self.fileobj, self.size) | def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) write32(self.fileobj, self.crc) write32(self.fileobj, self.size) self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None |
for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') | for i in range(count // 1024): self.write(1024 * '\0') self.write((count % 1024) * '\0') | def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive s... |
for i in range(count/1024): self.read(1024) | for i in range(count // 1024): self.read(1024) | def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive s... |
tz_name= time.tzname[0] | tz_name = time.tzname[0] if tz_name.lower() in ("UTC", "GMT"): return | def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name= time.tzname[0] try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = ... |
self.failUnlessEqual(tz_value, -1) | self.failUnlessEqual(tz_value, -1, "%s lead to a timezone value of %s instead of -1 when " "time.daylight set to %s and passing in %s" % (time.tzname, tz_value, time.daylight, tz_name)) | def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name= time.tzname[0] try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.