rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
root.tk.call("font", "create", name, *font)
if exists: self.delete_font = False if self.name not in root.tk.call("font", "names"): raise Tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,) if font: print "font=%r" % font root.tk.call("font", "configure", self.name, *font) else: root.tk.call("font", "create", self.name, *font) self.delete_font = True
def __init__(self, root=None, font=None, name=None, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name root.tk.call("font", "create", name, *font) # backlinks! self._root = root self._split = root.tk.splitlist self._call = root.tk.call
self._call("font", "delete", self.name)
if self.delete_font: self._call("font", "delete", self.name)
def __del__(self): try: self._call("font", "delete", self.name) except (AttributeError, Tkinter.TclError): pass
for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS):
for base in (HKEY_CLASSES_ROOT, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, HKEY_USERS):
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
k = _RegOpenKeyEx(base,K)
k = RegOpenKeyEx(base,K)
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
p = _RegEnumKey(k,i)
p = RegEnumKey(k,i)
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
except _RegError:
except RegError:
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS):
for base in (HKEY_CLASSES_ROOT, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, HKEY_USERS):
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
k = _RegOpenKeyEx(base,K)
k = RegOpenKeyEx(base,K)
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
(p,v,t) = _RegEnumValue(k,i)
(p,v,t) = RegEnumValue(k,i)
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
except _RegError:
except RegError:
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6)
def mysetattr(self, name, value): if name == "spam": raise AttributeError return object.__setattr__(self, name, value)
for k in value.keys():
for k, v in value.items():
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
raise TypeError, "dictionary key must be string"
if unicode and type(k) is UnicodeType: k = k.encode(self.encoding) else: raise TypeError, "dictionary key must be string"
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
dump(value[k], write)
dump(v, write)
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
LE_MAGIC = 0x950412de BE_MAGIC = 0xde120495
LE_MAGIC = 0x950412deL BE_MAGIC = 0xde120495L
def install(self, unicode=0): import __builtin__ __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
MASK = 0xffffffff
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
magic = unpack('<i', buf[:4])[0] & MASK
magic = unpack('<I', buf[:4])[0]
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii'
version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20]) ii = '<II'
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii'
version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20]) ii = '>II'
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
msgcount &= MASK masteridx &= MASK transidx &= MASK
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
moff &= MASK mend = moff + (mlen & MASK)
mend = moff + mlen
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
toff &= MASK tend = toff + (tlen & MASK)
tend = toff + tlen
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
return struct.unpack('8', data)[0]
return struct.unpack('d', data)[0]
def unpack_double(self): # XXX i = self.pos self.pos = j = i+8 data = self.buf[i:j] if len(data) < 8: raise EOFError return struct.unpack('8', data)[0]
<SCRIPT LANGUAGE="JavaScript">
<script type="text/javascript">
def js_output(self, attrs=None): # Print javascript return """ <SCRIPT LANGUAGE="JavaScript"> <!-- begin hiding document.cookie = \"%s\" // end hiding --> </script> """ % ( self.OutputString(attrs), )
document.cookie = \"%s\"
document.cookie = \"%s\";
def js_output(self, attrs=None): # Print javascript return """ <SCRIPT LANGUAGE="JavaScript"> <!-- begin hiding document.cookie = \"%s\" // end hiding --> </script> """ % ( self.OutputString(attrs), )
self.headers = None return -1, line, self.headers
try: [ver, code] = string.split(line, None, 1) msg = "" except ValueError: self.headers = None return -1, line, self.headers
def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '200' if all goes well) - server response string corresponding to response code - any RFC822 headers in the response from the server
A IncrementalEncoder encodes an input in multiple steps. The input can be
An IncrementalEncoder encodes an input in multiple steps. The input can be
def decode(self, input, errors='strict'):
Creates a IncrementalEncoder instance.
Creates an IncrementalEncoder instance.
def __init__(self, errors='strict'): """ Creates a IncrementalEncoder instance.
n = ((n+3)/4)*4
n = ((n+3)//4)*4
def pack_fstring(self, n, s): if n < 0: raise ValueError, 'fstring size must be nonnegative' data = s[:n] n = ((n+3)/4)*4 data = data + (n - len(data)) * '\0' self.__buf.write(data)
j = i + (n+3)/4*4
j = i + (n+3)//4*4
def unpack_fstring(self, n): if n < 0: raise ValueError, 'fstring size must be nonnegative' i = self.__pos j = i + (n+3)/4*4 if j > len(self.__buf): raise EOFError self.__pos = j return self.__buf[i:i+n]
def __div__(self, other): return "B.__div__" def __rdiv__(self, other): return "B.__rdiv__" vereq(B(1) / 1, "B.__div__") vereq(1 / B(1), "B.__rdiv__")
def __floordiv__(self, other): return "B.__floordiv__" def __rfloordiv__(self, other): return "B.__rfloordiv__" vereq(B(1) // 1, "B.__floordiv__") vereq(1 // B(1), "B.__rfloordiv__")
def __div__(self, other): return "B.__div__"
def __div__(self, other): return "C.__div__" def __rdiv__(self, other): return "C.__rdiv__" vereq(C() / 1, "C.__div__") vereq(1 / C(), "C.__rdiv__")
def __floordiv__(self, other): return "C.__floordiv__" def __rfloordiv__(self, other): return "C.__rfloordiv__" vereq(C() // 1, "C.__floordiv__") vereq(1 // C(), "C.__rfloordiv__")
def __div__(self, other): return "C.__div__"
def __div__(self, other): return "D.__div__" def __rdiv__(self, other): return "D.__rdiv__" vereq(D() / C(), "D.__div__") vereq(C() / D(), "D.__rdiv__")
def __floordiv__(self, other): return "D.__floordiv__" def __rfloordiv__(self, other): return "D.__rfloordiv__" vereq(D() // C(), "D.__floordiv__") vereq(C() // D(), "D.__rfloordiv__")
def __div__(self, other): return "D.__div__"
vereq(E.__rdiv__, C.__rdiv__) vereq(E() / 1, "C.__div__") vereq(1 / E(), "C.__rdiv__") vereq(E() / C(), "C.__div__") vereq(C() / E(), "C.__div__")
vereq(E.__rfloordiv__, C.__rfloordiv__) vereq(E() // 1, "C.__floordiv__") vereq(1 // E(), "C.__rfloordiv__") vereq(E() // C(), "C.__floordiv__") vereq(C() // E(), "C.__floordiv__")
def __rdiv__(self, other): return "D.__rdiv__"
if url[:1] != '/': url = '/' + url
if url and url[:1] != '/': url = '/' + url
def urlunparse((scheme, netloc, url, params, query, fragment)): """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent).""" if netloc or (scheme in uses_netloc and url[:2] == '//'): if url[:1] != '/': url = '/' + url url = '//' + (netloc or '') + url if scheme: url = scheme + ':' + url if params: url = url + ';' + params if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url
return urlunparse((scheme, netloc, path, params, query, fragment))
return url
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
params, query or bquery, fragment))
params, query, fragment))
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
if segments[i] == '..' and segments[i-1]:
if (segments[i] == '..' and segments[i-1] not in ('', '..')):
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
if len(segments) == 2 and segments[1] == '..' and segments[0] == '':
if segments == ['', '..']:
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
try: what, tdelta, fileno, lineno = self._nextitem() except TypeError: self._reader.close() raise StopIteration()
what, tdelta, fileno, lineno = self._nextitem()
def next(self, index=0): while 1: try: what, tdelta, fileno, lineno = self._nextitem() except TypeError: # logreader().next() returns None at the end self._reader.close() raise StopIteration()
try: import sys orig = sys.getrefcount(__name__) socket.getnameinfo(__name__,0) except SystemError: if sys.getrefcount(__name__) <> orig: raise TestFailed,"socket.getnameinfo loses a reference"
import sys if not sys.platform.startswith('java'): try: orig = sys.getrefcount(__name__) socket.getnameinfo(__name__,0) except SystemError: if sys.getrefcount(__name__) <> orig: raise TestFailed,"socket.getnameinfo loses a reference"
def missing_ok(str): try: getattr(socket, str) except AttributeError: pass
has_cte = is_qp = 0
has_cte = is_qp = is_base64 = 0
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line) >= 0: must_quote_header = 1 if mv.match(line) >= 0: is_mime = 1 if cte.match(line) >= 0: has_cte = 1 if qp.match(line) >= 0: is_qp = 1 if mp.match(line) >= 0: multipart = '--' + mp.group(1) if he.match(line) >= 0: header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line) >= 0: has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) if chrset.match(line) >= 0: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset.group(2)) == 'us-ascii': line = chrset.group(1) + \ CHARSET + chrset.group(3) else: # change iso-8859-* into us-ascii line = chrset.group(1) + 'us-ascii' + chrset.group(3) if has_cte and cte.match(line) >= 0: line = 'Content-Transfer-Encoding: ' if must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': return if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
if must_quote_body:
if is_base64: line = line + 'base64\n' elif must_quote_body:
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line) >= 0: must_quote_header = 1 if mv.match(line) >= 0: is_mime = 1 if cte.match(line) >= 0: has_cte = 1 if qp.match(line) >= 0: is_qp = 1 if mp.match(line) >= 0: multipart = '--' + mp.group(1) if he.match(line) >= 0: header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line) >= 0: has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) if chrset.match(line) >= 0: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset.group(2)) == 'us-ascii': line = chrset.group(1) + \ CHARSET + chrset.group(3) else: # change iso-8859-* into us-ascii line = chrset.group(1) + 'us-ascii' + chrset.group(3) if has_cte and cte.match(line) >= 0: line = 'Content-Transfer-Encoding: ' if must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': return if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
self.compiler = new_compiler (plat=os.environ.get ('PLAT'), verbose=self.verbose,
self.compiler = new_compiler (verbose=self.verbose,
def run (self):
def __init__(self, fp):
seekable = 0 def __init__(self, fp, seekable=1):
def __init__(self, fp): self.fp = fp self.stack = [] # Grows down self.level = 0 self.last = 0 self.start = self.fp.tell() self.posstack = [] # Grows down
self.start = self.fp.tell() self.posstack = []
if seekable: self.seekable = 1 self.start = self.fp.tell() self.posstack = []
def __init__(self, fp): self.fp = fp self.stack = [] # Grows down self.level = 0 self.last = 0 self.start = self.fp.tell() self.posstack = [] # Grows down
self.lastpos = self.tell() - len(line)
if self.seekable: self.lastpos = self.tell() - len(line)
def readline(self): if self.level > 0: return '' line = self.fp.readline() if not line: self.level = len(self.stack) self.last = (self.level > 0) if self.last: err('*** Sudden EOF in MultiFile.readline()\n') return '' if line[:2] <> '--': return line n = len(line) k = n while k > 0 and line[k-1] in string.whitespace: k = k-1 mark = line[2:k] if mark[-2:] == '--': mark1 = mark[:-2] else: mark1 = None for i in range(len(self.stack)): sep = self.stack[i] if sep == mark: self.last = 0 break elif mark1 <> None and sep == mark1: self.last = 1 break else: return line # Get here after break out of loop self.lastpos = self.tell() - len(line) self.level = i+1 if self.level > 1: err('*** Missing endmarker in MultiFile.readline()\n') return ''
self.start = self.fp.tell()
if self.seekable: self.start = self.fp.tell()
def next(self): while self.readline(): pass if self.level > 1 or self.last: return 0 self.level = 0 self.last = 0 self.start = self.fp.tell() return 1
self.posstack.insert(0, self.start) self.start = self.fp.tell()
if self.seekable: self.posstack.insert(0, self.start) self.start = self.fp.tell()
def push(self, sep): if self.level > 0: raise Error, 'bad MultiFile.push() call' self.stack.insert(0, sep) self.posstack.insert(0, self.start) self.start = self.fp.tell()
socketDataProcessed = threading.Condition()
socketDataProcessed = threading.Event()
def handleLogRecord(self, record): logname = "logrecv.tcp." + record.name #If the end-of-messages sentinel is seen, tell the server to terminate if record.msg == FINISH_UP: self.server.abort = 1 record.msg = record.msg + " (via " + logname + ")" logger = logging.getLogger(logname) logger.handle(record)
socketDataProcessed.acquire() socketDataProcessed.notify() socketDataProcessed.release()
socketDataProcessed.set()
def serve_until_stopped(self): abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort #notify the main thread that we're about to exit socketDataProcessed.acquire() socketDataProcessed.notify() socketDataProcessed.release()
socketDataProcessed.acquire()
def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #The handler will only be added to the rootLogger for some of the tests hdlr = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) #Configure the logger for logrecv so events do not propagate beyond it. #The sockLogger output is buffered in memory until the end of the test, #and printed at the end. sockOut = cStringIO.StringIO() sockLogger = logging.getLogger("logrecv") sockLogger.setLevel(logging.DEBUG) sockhdlr = logging.StreamHandler(sockOut) sockhdlr.setFormatter(logging.Formatter( "%(name)s -> %(levelname)s: %(message)s")) sockLogger.addHandler(sockhdlr) sockLogger.propagate = 0 #Set up servers threads = [] tcpserver = LogRecordSocketReceiver() #sys.stdout.write("About to start TCP server...\n") threads.append(threading.Thread(target=runTCP, args=(tcpserver,))) for thread in threads: thread.start() try: banner("log_test0", "begin") rootLogger.addHandler(hdlr) test0() hdlr.close() rootLogger.removeHandler(hdlr) banner("log_test0", "end") banner("log_test1", "begin") test1() banner("log_test1", "end") banner("log_test2", "begin") test2() banner("log_test2", "end") banner("log_test3", "begin") test3() banner("log_test3", "end") finally: #wait for TCP receiver to terminate socketDataProcessed.acquire() socketDataProcessed.wait() socketDataProcessed.release() for thread in threads: thread.join() banner("logrecv output", "begin") sys.stdout.write(sockOut.getvalue()) sockOut.close() banner("logrecv output", "end") sys.stdout.flush()
socketDataProcessed.release()
def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #The handler will only be added to the rootLogger for some of the tests hdlr = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) #Configure the logger for logrecv so events do not propagate beyond it. #The sockLogger output is buffered in memory until the end of the test, #and printed at the end. sockOut = cStringIO.StringIO() sockLogger = logging.getLogger("logrecv") sockLogger.setLevel(logging.DEBUG) sockhdlr = logging.StreamHandler(sockOut) sockhdlr.setFormatter(logging.Formatter( "%(name)s -> %(levelname)s: %(message)s")) sockLogger.addHandler(sockhdlr) sockLogger.propagate = 0 #Set up servers threads = [] tcpserver = LogRecordSocketReceiver() #sys.stdout.write("About to start TCP server...\n") threads.append(threading.Thread(target=runTCP, args=(tcpserver,))) for thread in threads: thread.start() try: banner("log_test0", "begin") rootLogger.addHandler(hdlr) test0() hdlr.close() rootLogger.removeHandler(hdlr) banner("log_test0", "end") banner("log_test1", "begin") test1() banner("log_test1", "end") banner("log_test2", "begin") test2() banner("log_test2", "end") banner("log_test3", "begin") test3() banner("log_test3", "end") finally: #wait for TCP receiver to terminate socketDataProcessed.acquire() socketDataProcessed.wait() socketDataProcessed.release() for thread in threads: thread.join() banner("logrecv output", "begin") sys.stdout.write(sockOut.getvalue()) sockOut.close() banner("logrecv output", "end") sys.stdout.flush()
self.assertRaises(ValueError, u"%c".__mod__, (sys.maxunicode+1,))
self.assertRaises(OverflowError, u"%c".__mod__, (sys.maxunicode+1,))
def test_formatting(self): string_tests.MixinStrUnicodeUserStringTest.test_formatting(self) # Testing Unicode formatting strings... self.assertEqual(u"%s, %s" % (u"abc", "abc"), u'abc, abc') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, 2, 3), u'abc, abc, 1, 2.000000, 3.00') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, -2, 3), u'abc, abc, 1, -2.000000, 3.00') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.5), u'abc, abc, -1, -2.000000, 3.50') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.57), u'abc, abc, -1, -2.000000, 3.57') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 1003.57), u'abc, abc, -1, -2.000000, 1003.57') if not sys.platform.startswith('java'): self.assertEqual(u"%r, %r" % (u"abc", "abc"), u"u'abc', 'abc'") self.assertEqual(u"%(x)s, %(y)s" % {'x':u"abc", 'y':"def"}, u'abc, def') self.assertEqual(u"%(x)s, %(\xfc)s" % {'x':u"abc", u'\xfc':"def"}, u'abc, def')
raise error, "bogus escape"
raise error, "bogus escape (end of line)"
def __next(self): if self.index >= len(self.string): self.next = None return char = self.string[self.index] if char[0] == "\\": try: c = self.string[self.index + 1] except IndexError: raise error, "bogus escape" char = char + c self.index = self.index + len(char) self.next = char
"""Return tupel of decimal values for red, green, blue for
"""Return tuple of decimal values for red, green, blue for
def winfo_rgb(self, color): """Return tupel of decimal values for red, green, blue for COLOR in this widget.""" return self._getints( self.tk.call('winfo', 'rgb', self._w, color))
except:
except NameError:
def _init_categories(categories=categories): for k,v in globals().items(): if k[:3] == 'LC_': categories[k] = v
header = 'Authorization'
auth_header = 'Authorization'
def get_entity_digest(self, data, chal): # XXX not implemented yet return None
header = 'Proxy-Authorization'
auth_header = 'Proxy-Authorization'
def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] self.http_error_auth_reqed('www-authenticate', host, req, headers)
if path.startswith(dir) and path[len(dir)] == os.path.sep:
dir = os.path.normcase(dir) if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
def fullmodname(path): """Return a plausible module name for the path.""" # If the file 'path' is part of a package, then the filename isn't # enough to uniquely identify it. Try to do the right thing by # looking in sys.path for the longest matching prefix. We'll # assume that the rest is the package name. longest = "" for dir in sys.path: if path.startswith(dir) and path[len(dir)] == os.path.sep: if len(dir) > len(longest): longest = dir if longest: base = path[len(longest) + 1:] else: base = path base = base.replace(os.sep, ".") if os.altsep: base = base.replace(os.altsep, ".") filename, ext = os.path.splitext(base) return filename
FILE = open(self.file_path, 'wU')
FILE = open(self.file_path, 'w')
def create(self): """Create a .pth file with a comment, blank lines, an ``import <self.imported>``, a line with self.good_dirname, and a line with self.bad_dirname.
return os.path.join(prefix, "Mac", "Plugins")
return os.path.join(prefix, "Lib", "lib-dynload")
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """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-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = plat_specific and EXEC_PREFIX or PREFIX if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(prefix, "Lib") else: if sys.version < "2.2": return prefix else: return os.path.join(PREFIX, "Lib", "site-packages") elif os.name == "mac": if plat_specific: if standard_lib: return os.path.join(prefix, "Mac", "Plugins") else: raise DistutilsPlatformError( "OK, where DO site-specific extensions go on the Mac?") else: if standard_lib: return os.path.join(prefix, "Lib") else: raise DistutilsPlatformError( "OK, where DO site-specific modules go on the Mac?") else: raise DistutilsPlatformError( "I don't know where Python installs its library " "on platform '%s'" % os.name)
raise DistutilsPlatformError( "OK, where DO site-specific extensions go on the Mac?")
return os.path.join(prefix, "Lib", "site-packages")
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """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-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = plat_specific and EXEC_PREFIX or PREFIX if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(prefix, "Lib") else: if sys.version < "2.2": return prefix else: return os.path.join(PREFIX, "Lib", "site-packages") elif os.name == "mac": if plat_specific: if standard_lib: return os.path.join(prefix, "Mac", "Plugins") else: raise DistutilsPlatformError( "OK, where DO site-specific extensions go on the Mac?") else: if standard_lib: return os.path.join(prefix, "Lib") else: raise DistutilsPlatformError( "OK, where DO site-specific modules go on the Mac?") else: raise DistutilsPlatformError( "I don't know where Python installs its library " "on platform '%s'" % os.name)
raise DistutilsPlatformError( "OK, where DO site-specific modules go on the Mac?")
return os.path.join(prefix, "Lib", "site-packages")
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """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-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = plat_specific and EXEC_PREFIX or PREFIX if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(prefix, "Lib") else: if sys.version < "2.2": return prefix else: return os.path.join(PREFIX, "Lib", "site-packages") elif os.name == "mac": if plat_specific: if standard_lib: return os.path.join(prefix, "Mac", "Plugins") else: raise DistutilsPlatformError( "OK, where DO site-specific extensions go on the Mac?") else: if standard_lib: return os.path.join(prefix, "Lib") else: raise DistutilsPlatformError( "OK, where DO site-specific modules go on the Mac?") else: raise DistutilsPlatformError( "I don't know where Python installs its library " "on platform '%s'" % os.name)
path = os.path.join(host, path) if path[-1] == "/": path = path + "index.html"
if not path or path[-1] == "/": path = path + "index.html"
def savefilename(self, url): type, rest = urllib.splittype(url) host, path = urllib.splithost(rest) while path[:1] == "/": path = path[1:] user, host = urllib.splituser(host) host, port = urllib.splitnport(host) host = string.lower(host) path = os.path.join(host, path) if path[-1] == "/": path = path + "index.html" if os.sep != "/": path = string.join(string.split(path, "/"), os.sep) return path
l.append (fd, flags)
l.append ((fd, flags))
def poll2 (timeout=0.0): import poll # timeout is in milliseconds timeout = int(timeout*1000) if socket_map: fd_map = {} for s in socket_map.keys(): fd_map[s.fileno()] = s l = [] for fd, s in fd_map.items(): flags = 0 if s.readable(): flags = poll.POLLIN if s.writable(): flags = flags | poll.POLLOUT if flags: l.append (fd, flags) r = poll.poll (l, timeout) for fd, flags in r: s = fd_map[fd] try: if (flags & poll.POLLIN): s.handle_read_event() if (flags & poll.POLLOUT): s.handle_write_event() if (flags & poll.POLLERR): s.handle_expt_event() except: s.handle_error()
tbinfo.append (
tbinfo.append ((
def compact_traceback (): t,v,tb = sys.exc_info() tbinfo = [] while 1: tbinfo.append ( tb.tb_frame.f_code.co_filename, tb.tb_frame.f_code.co_name, str(tb.tb_lineno) ) tb = tb.tb_next if not tb: break # just to be safe del tb file, function, line = tbinfo[-1] info = '[' + string.join ( map ( lambda x: string.join (x, '|'), tbinfo ), '] [' ) + ']' return (file, function, line), t, v, info
)
))
def compact_traceback (): t,v,tb = sys.exc_info() tbinfo = [] while 1: tbinfo.append ( tb.tb_frame.f_code.co_filename, tb.tb_frame.f_code.co_name, str(tb.tb_lineno) ) tb = tb.tb_next if not tb: break # just to be safe del tb file, function, line = tbinfo[-1] info = '[' + string.join ( map ( lambda x: string.join (x, '|'), tbinfo ), '] [' ) + ']' return (file, function, line), t, v, info
'ext_modules': ('build_ext', 'modules'),
'ext_modules': ('build_ext', 'extensions'),
def setup (**attrs): """The gateway to the Distutils: do everything your setup script needs to do, in a highly flexible and user-driven way. Briefly: create a Distribution instance; parse the command-line, creating and customizing instances of the command class for each command found on the command-line; run each of those commands. The Distribution instance might be an instance of a class supplied via the 'distclass' keyword argument to 'setup'; if no such class is supplied, then the 'Distribution' class (also in this module) is instantiated. All other arguments to 'setup' (except for 'cmdclass') are used to set attributes of the Distribution instance. The 'cmdclass' argument, if supplied, is a dictionary mapping command names to command classes. Each command encountered on the command line will be turned into a command class, which is in turn instantiated; any class found in 'cmdclass' is used in place of the default, which is (for command 'foo_bar') class 'FooBar' in module 'distutils.command.foo_bar'. The command object must provide an 'options' attribute which is a list of option specifiers for 'distutils.fancy_getopt'. Any command-line options between the current and the next command are used to set attributes in the current command object. When the entire command-line has been successfully parsed, calls the 'run' method on each command object in turn. This method will be driven entirely by the Distribution object (which each command object has a reference to, thanks to its constructor), and the command-specific options that became attributes of each command object.""" # Determine the distribution class -- either caller-supplied or # our Distribution (see below). klass = attrs.get ('distclass') if klass: del attrs['distclass'] else: klass = Distribution # Create the Distribution instance, using the remaining arguments # (ie. everything except distclass) to initialize it dist = klass (attrs) # If we had a config file, this is where we would parse it: override # the client-supplied command options, but be overridden by the # command line. # Parse the command line; any command-line errors are the end-users # fault, so turn them into SystemExit to suppress tracebacks. try: dist.parse_command_line (sys.argv[1:]) except DistutilsArgError, msg: raise SystemExit, msg # And finally, run all the commands found on the command line. dist.run_commands ()
"command %s: no such option %s" % \
"command '%s': no such option '%s'" % \
def set_option (self, option, value): """Set the value of a single option for this command. Raise DistutilsOptionError if 'option' is not known."""
env_val = os.getenv(env_var)
env_val = sysconfig.get_config_var(env_var)
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
output.write(input.read())
return output.write(input.read())
def decode(input, output, encoding): """Decode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.decode(input, output) if encoding == 'quoted-printable': import quopri return quopri.decode(input, output) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.decode(input, output) if encoding in ('7bit', '8bit'): output.write(input.read()) if decodetab.has_key(encoding): pipethrough(input, decodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
output.write(input.read())
return output.write(input.read())
def encode(input, output, encoding): """Encode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): output.write(input.read()) if encodetab.has_key(encoding): pipethrough(input, encodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
FILE = file(test_support.TESTFN, 'w')
FILE = file(test_support.TESTFN, 'wb')
def setUp(self): """Setup of a temp file to use for testing""" self.text = "test_urllib: %s\n" % self.__class__.__name__ FILE = file(test_support.TESTFN, 'w') try: FILE.write(self.text) finally: FILE.close() self.pathname = test_support.TESTFN self.returned_obj = urllib.urlopen("file:%s" % self.pathname)
prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return prefix
s1 = min(m) s2 = max(m) n = min(len(s1), len(s2)) for i in xrange(n): if s1[i] != s2[i]: return s1[:i] return s1[:n]
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return prefix
inc_dir = get_python_inc(plat_specific=1)
if python_build: inc_dir = '.' else: inc_dir = get_python_inc(plat_specific=1)
def get_config_h_filename(): """Return full pathname of installed config.h file.""" inc_dir = get_python_inc(plat_specific=1) return os.path.join(inc_dir, "config.h")
if os.name == 'mac': def writable(self): return not self.accepting else: def writable(self): return True
def writable(self): return True
def readable(self): return True
typ, dat = self._simple_command('GETQUOTA', root)
typ, dat = self._simple_command('GETQUOTA', mailbox)
def getquotaroot(self, mailbox): """Get the list of quota roots for the named mailbox.
self.disallow_all = 0 self.allow_all = 0
self.disallow_all = False self.allow_all = False
def __init__(self, url=''): self.entries = [] self.default_entry = None self.disallow_all = 0 self.allow_all = 0 self.set_url(url) self.last_checked = 0
self.disallow_all = 1
self.disallow_all = True
def read(self): """Reads the robots.txt URL and feeds it to the parser.""" opener = URLopener() f = opener.open(self.url) lines = [] line = f.readline() while line: lines.append(line.strip()) line = f.readline() self.errcode = opener.errcode if self.errcode == 401 or self.errcode == 403: self.disallow_all = 1 _debug("disallow all") elif self.errcode >= 400: self.allow_all = 1 _debug("allow all") elif self.errcode == 200 and lines: _debug("parse lines") self.parse(lines)
self.allow_all = 1
self.allow_all = True
def read(self): """Reads the robots.txt URL and feeds it to the parser.""" opener = URLopener() f = opener.open(self.url) lines = [] line = f.readline() while line: lines.append(line.strip()) line = f.readline() self.errcode = opener.errcode if self.errcode == 401 or self.errcode == 403: self.disallow_all = 1 _debug("disallow all") elif self.errcode >= 400: self.allow_all = 1 _debug("allow all") elif self.errcode == 200 and lines: _debug("parse lines") self.parse(lines)
entry.rulelines.append(RuleLine(line[1], 0))
entry.rulelines.append(RuleLine(line[1], False))
def parse(self, lines): """parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.""" state = 0 linenumber = 0 entry = Entry()
entry.rulelines.append(RuleLine(line[1], 1))
entry.rulelines.append(RuleLine(line[1], True))
def parse(self, lines): """parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.""" state = 0 linenumber = 0 entry = Entry()
allowance = 1
allowance = True
def __init__(self, path, allowance): if path == '' and not allowance: # an empty value means allow all allowance = 1 self.path = urllib.quote(path) self.allowance = allowance
return 1
return True
def allowance(self, filename): """Preconditions: - our agent applies to this entry - filename is URL decoded""" for line in self.rulelines: _debug((filename, str(line), line.allowance)) if line.applies_to(filename): return line.allowance return 1
'$CC -Wl,-t -o /dev/null 2>&1 -l' + name
'$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name
def _findLib_gcc(name): expr = '[^\(\)\s]*lib%s\.[^\(\)\s]*' % name cmd = 'if type gcc &>/dev/null; then CC=gcc; else CC=cc; fi;' \ '$CC -Wl,-t -o /dev/null 2>&1 -l' + name try: fdout, outfile = tempfile.mkstemp() fd = os.popen(cmd) trace = fd.read() err = fd.close() finally: try: os.unlink(outfile) except OSError, e: if e.errno != errno.ENOENT: raise res = re.search(expr, trace) if not res: return None return res.group(0)
def index(path, archivo, output):
def index(path, indexpage, output):
def index(path, archivo, output): f = formatter.AbstractFormatter(AlmostNullWriter()) parser = IdxHlpHtmlParser(f) parser.path = path parser.ft = output fil = path + '/' + archivo parser.feed(open(fil).read()) parser.close()
fil = path + '/' + archivo parser.feed(open(fil).read())
f = open(path + '/' + indexpage) parser.feed(f.read())
def index(path, archivo, output): f = formatter.AbstractFormatter(AlmostNullWriter()) parser = IdxHlpHtmlParser(f) parser.path = path parser.ft = output fil = path + '/' + archivo parser.feed(open(fil).read()) parser.close()
def content(path, archivo, output):
f.close() def content(path, contentpage, output):
def index(path, archivo, output): f = formatter.AbstractFormatter(AlmostNullWriter()) parser = IdxHlpHtmlParser(f) parser.path = path parser.ft = output fil = path + '/' + archivo parser.feed(open(fil).read()) parser.close()
fil = path + '/' + archivo parser.feed(open(fil).read())
f = open(path + '/' + contentpage) parser.feed(f.read())
def content(path, archivo, output): f = formatter.AbstractFormatter(AlmostNullWriter()) parser = TocHlpHtmlParser(f) parser.path = path parser.ft = output fil = path + '/' + archivo parser.feed(open(fil).read()) parser.close()
print '\t', book[2] if book[4]: index(book[0], book[4], output)
print '\t', book.title, '-', book.indexpage if book.indexpage: index(book.directory, book.indexpage, output)
def do_index(library, output): output.write('<UL>\n') for book in library: print '\t', book[2] if book[4]: index(book[0], book[4], output) output.write('</UL>\n')
print '\t', book[2] output.write(object_sitemap % (book[0]+"/"+book[2], book[1])) if book[3]: content(book[0], book[3], output)
print '\t', book.title, '-', book.firstpage output.write(object_sitemap % (book.directory + "/" + book.firstpage, book.title)) if book.contentpage: content(book.directory, book.contentpage, output)
def do_content(library, version, output): output.write(contents_header % version) for book in library: print '\t', book[2] output.write(object_sitemap % (book[0]+"/"+book[2], book[1])) if book[3]: content(book[0], book[3], output) output.write(contents_footer)
directory = book[0]
directory = book.directory
def do_project(library, output, arch, version): output.write(project_template % locals()) for book in library: directory = book[0] path = directory + '\\%s\n' for page in os.listdir(directory): if page.endswith('.html') or page.endswith('.css'): output.write(path % page)
proxies[protocol] = '%s://%s' % (protocol, address)
type, address = splittype(address) if not type: address = '%s://%s' % (protocol, address) proxies[protocol] = address
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
doc = `doc`
doc = '"' + doc + '"'
def outputGetSetList(self): if self.getsetlist: for name, get, set, doc in self.getsetlist: if get: self.outputGetter(name, get) else: Output("#define %s_get_%s NULL", self.prefix, name) if set: self.outputSetter(name, set) else: Output("#define %s_set_%s NULL", self.prefix, name) Output("static PyGetSetDef %s_getsetlist[] = {", self.prefix) IndentLevel() for name, get, set, doc in self.getsetlist: if doc: doc = `doc` else: doc = "NULL" Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s}", name, self.prefix, name, self.prefix, name, doc) DedentLevel() Output("};") else: Output("#define %s_getsetlist NULL", self.prefix)
Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s}",
Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s},",
def outputGetSetList(self): if self.getsetlist: for name, get, set, doc in self.getsetlist: if get: self.outputGetter(name, get) else: Output("#define %s_get_%s NULL", self.prefix, name) if set: self.outputSetter(name, set) else: Output("#define %s_set_%s NULL", self.prefix, name) Output("static PyGetSetDef %s_getsetlist[] = {", self.prefix) IndentLevel() for name, get, set, doc in self.getsetlist: if doc: doc = `doc` else: doc = "NULL" Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s}", name, self.prefix, name, self.prefix, name, doc) DedentLevel() Output("};") else: Output("#define %s_getsetlist NULL", self.prefix)
Output("static int %s_get_%s(%s *self, PyObject *v, void *closure)",
Output("static int %s_set_%s(%s *self, PyObject *v, void *closure)",
def outputSetter(self, name, code): Output("static int %s_get_%s(%s *self, PyObject *v, void *closure)", self.prefix, name, self.objecttype) OutLbrace() Output(code) Output("return 0;") OutRbrace()
emit((av[0]-1)*2)
emit(av[0]-1)
def fixup(literal, flags=flags): return _sre.getlower(literal, flags)
self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1)
self.set_reuse_addr()
def __init__(self, localaddr, remoteaddr): self._localaddr = localaddr self._remoteaddr = remoteaddr asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # try to re-use a server port if possible self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1) self.bind(localaddr) self.listen(5) print >> DEBUGSTREAM, \ '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), localaddr, remoteaddr)
print """usage: basd64 [-d] [-e] [-u] [-t] [file|-]
print """usage: %s [-d|-e|-u|-t] [file|-]
def test(): """Small test program""" import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') except getopt.error, msg: sys.stdout = sys.stderr print msg print """usage: basd64 [-d] [-e] [-u] [-t] [file|-] -d, -u: decode -e: encode (default) -t: decode string 'Aladdin:open sesame'""" sys.exit(2) func = encode for o, a in opts: if o == '-e': func = encode if o == '-d': func = decode if o == '-u': func = decode if o == '-t': test1(); return if args and args[0] != '-': func(open(args[0], 'rb'), sys.stdout) else: func(sys.stdin, sys.stdout)