rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
name = basename(in_file) | name = os.path.basename(in_file) | def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): if name == None: name = basename(in_file) if mode == None: try: mode = os.path.stat(in_file)[0] except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name == None: name = '-' if mode == None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n') |
mode = os.path.stat(in_file)[0] | mode = os.stat(in_file)[0] | def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): if name == None: name = basename(in_file) if mode == None: try: mode = os.path.stat(in_file)[0] except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name == None: name = '-' if mode == None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n') |
_apply = apply | def join(words, sep = ' '): """join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurences of sep. The default separator is a single space. (joinfields and join are synonymous) """ return sep.join(words) |
|
return _apply(s.index, args) | return s.index(*args) | def index(s, *args): """index(s, sub [,start [,end]]) -> int Like find but raises ValueError when the substring is not found. """ return _apply(s.index, args) |
return _apply(s.rindex, args) | return s.rindex(*args) | def rindex(s, *args): """rindex(s, sub [,start [,end]]) -> int Like rfind but raises ValueError when the substring is not found. """ return _apply(s.rindex, args) |
return _apply(s.count, args) | return s.count(*args) | def count(s, *args): """count(s, sub[, start[,end]]) -> int Return the number of occurrences of substring sub in string s[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return _apply(s.count, args) |
return _apply(s.find, args) | return s.find(*args) | def find(s, *args): """find(s, sub [,start [,end]]) -> in Return the lowest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return _apply(s.find, args) |
return _apply(s.rfind, args) | return s.rfind(*args) | def rfind(s, *args): """rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return _apply(s.rfind, args) |
n = width - len(s) if n <= 0: return s return s + ' '*n | return s.ljust(width) | def ljust(s, width): """ljust(s, width) -> string Return a left-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. """ n = width - len(s) if n <= 0: return s return s + ' '*n |
n = width - len(s) if n <= 0: return s return ' '*n + s | return s.rjust(width) | def rjust(s, width): """rjust(s, width) -> string Return a right-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. """ n = width - len(s) if n <= 0: return s return ' '*n + s |
n = width - len(s) if n <= 0: return s half = n/2 if n%2 and width%2: half = half+1 return ' '*half + s + ' '*(n-half) | return s.center(width) | def center(s, width): """center(s, width) -> string Return a center version of s, in a field of the specified width. padded with spaces as needed. The string is never truncated. """ n = width - len(s) if n <= 0: return s half = n/2 if n%2 and width%2: # This ensures that center(center(s, i), j) = center(s, j) half = half+1 return ' '*half + s + ' '*(n-half) |
res = line = '' for c in s: if c == '\t': c = ' '*(tabsize - len(line) % tabsize) line = line + c if c == '\n': res = res + line line = '' return res + line | return s.expandtabs(tabsize) | def expandtabs(s, tabsize=8): """expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8). """ res = line = '' for c in s: if c == '\t': c = ' '*(tabsize - len(line) % tabsize) line = line + c if c == '\n': res = res + line line = '' return res + line |
try: ''.upper except AttributeError: from stringold import * | def replace(s, old, new, maxsplit=-1): """replace (str, old, new[, maxsplit]) -> string Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxsplit is given, only the first maxsplit occurrences are replaced. """ return s.replace(old, new, maxsplit) |
|
parts = split(path, '.') | parts = [part for part in split(path, '.') if part] | def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" parts = split(path, '.') module, n = None, 0 while n < len(parts): nextmodule = safeimport(join(parts[:n+1], '.'), forceload) if nextmodule: module, n = nextmodule, n + 1 else: break if module: object = module for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object else: import __builtin__ if hasattr(__builtin__, path): return getattr(__builtin__, path) |
Keywords are width, height, startx and starty | Keywords are width, height, startx and starty: | def setup(**geometry): """ Sets the size and position of the main window. Keywords are width, height, startx and starty width: either a size in pixels or a fraction of the screen. Default is 50% of screen. height: either the height in pixels or a fraction of the screen. Default is 75% of screen. Setting either width or height to None before drawing will force use of default geometry as in older versions of turtle.py startx: starting position in pixels from the left edge of the screen. Default is to center window. Setting startx to None is the default and centers window horizontally on screen. starty: starting position in pixels from the top edge of the screen. Default is to center window. Setting starty to None is the default and centers window vertically on screen. Examples: >>> setup (width=200, height=200, startx=0, starty=0) sets window to 200x200 pixels, in upper left of screen >>> setup(width=.75, height=0.5, startx=None, starty=None) sets window to 75% of screen by 50% of screen and centers >>> setup(width=None) forces use of default geometry as in older versions of turtle.py """ global _width, _height, _startx, _starty width = geometry.get('width',_width) if width >= 0 or width == None: _width = width else: raise ValueError, "width can not be less than 0" height = geometry.get('height',_height) if height >= 0 or height == None: _height = height else: raise ValueError, "height can not be less than 0" startx = geometry.get('startx', _startx) if startx >= 0 or startx == None: _startx = _startx else: raise ValueError, "startx can not be less than 0" starty = geometry.get('starty', _starty) if starty >= 0 or starty == None: _starty = starty else: raise ValueError, "startx can not be less than 0" if _root and _width and _height: if 0 < _width <= 1: _width = _root.winfo_screenwidth() * +width if 0 < _height <= 1: _height = _root.winfo_screenheight() * _height # center window on screen if _startx is None: _startx = (_root.winfo_screenwidth() - _width) / 2 if _starty is None: _starty = (_root.winfo_screenheight() - _height) / 2 _root.geometry("%dx%d+%d+%d" % (_width, _height, _startx, _starty)) |
""" set the window title. | """Set the window title. | def title(title): """ set the window title. By default this is set to 'Turtle Graphics' Example: >>> title("My Window") """ global _title _title = title |
raise ErrorDuringImport(filename, sys.exc_info()) | raise ErrorDuringImport(path, sys.exc_info()) | def locate(path): """Locate an object by name (or dotted path), importing as necessary.""" if not path: # special case: imp.find_module('') strangely succeeds return None if type(path) is not types.StringType: return path parts = split(path, '.') n = len(parts) while n > 0: path = join(parts[:n], '.') try: module = freshimport(path) except: # Did the error occur before or after the module was found? (exc, value, tb) = info = sys.exc_info() if sys.modules.has_key(path): # An error occured while executing the imported module. raise ErrorDuringImport(sys.modules[path].__file__, info) elif exc is SyntaxError: # A SyntaxError occurred before we could execute the module. raise ErrorDuringImport(value.filename, info) elif exc is ImportError and \ split(lower(str(value)))[:2] == ['no', 'module']: # The module was not found. n = n - 1 continue else: # Some other error occurred before executing the module. raise ErrorDuringImport(filename, sys.exc_info()) try: x = module for p in parts[n:]: x = getattr(x, p) return x except AttributeError: n = n - 1 continue if hasattr(__builtins__, path): return getattr(__builtins__, path) return None |
return (action, pattern, dir, dir_pattern) | return (action, patterns, dir, dir_pattern) | def _parse_template_line (self, line): words = string.split (line) action = words[0] |
chunk = Chunk().init(self._file) | try: chunk = Chunk().init(self._file) except EOFError: if formlength == 8: print 'Warning: FORM chunk size too large' formlength = 0 break raise EOFError | def initfp(self, file): self._file = file self._version = 0 self._decomp = None self._markers = [] self._soundpos = 0 form = self._file.read(4) if form != 'FORM': raise Error, 'file does not start with FORM id' formlength = _read_long(self._file) if formlength <= 0: raise Error, 'invalid FORM chunk data size' formdata = self._file.read(4) formlength = formlength - 4 if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while formlength > 0: self._ssnd_seek_needed = 1 chunk = Chunk().init(self._file) formlength = formlength - 8 - chunk.chunksize if chunk.chunksize & 1: formlength = formlength - 1 if chunk.chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunk.chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunk.chunkname == 'FVER': self._version = _read_long(chunk) elif chunk.chunkname == 'MARK': self._readmark(chunk) elif chunk.chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname if formlength > 0: chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error, 'COMM chunk and/or SSND chunk missing' if self._aifc and self._decomp: params = [CL.ORIGINAL_FORMAT, 0, \ CL.BITS_PER_COMPONENT, 0, \ CL.FRAME_RATE, self._framerate] if self._nchannels == AL.MONO: params[1] = CL.MONO else: params[1] = CL.STEREO_INTERLEAVED if self._sampwidth == AL.SAMPLE_8: params[3] = 8 elif self._sampwidth == AL.SAMPLE_16: params[3] = 16 else: params[3] = 24 self._decomp.SetParams(params) return self |
from distutils.ccompiler import new_compiler from distutils.sysconfig import customize_compiler | def build_extensions(self): from distutils.ccompiler import new_compiler from distutils.sysconfig import customize_compiler |
|
compiler = os.environ.get('CC') linker_so = os.environ.get('LDSHARED') args = {} if compiler is not None: args['compiler_so'] = compiler if linker_so is not None: args['linker_so'] = linker_so + ' -shared' self.compiler.set_executables(**args) | def build_extensions(self): from distutils.ccompiler import new_compiler from distutils.sysconfig import customize_compiler |
|
xid = self.unpack_uint(xid) | xid = self.unpack_uint() | def unpack_callheader(self): xid = self.unpack_uint(xid) temp = self.unpack_enum() if temp <> CALL: raise BadRPCFormat, 'no CALL but %r' % (temp,) temp = self.unpack_uint() if temp <> RPCVERSION: raise BadRPCVerspion, 'bad RPC version %r' % (temp,) prog = self.unpack_uint() vers = self.unpack_uint() proc = self.unpack_uint() cred = self.unpack_auth() verf = self.unpack_auth() return xid, prog, vers, proc, cred, verf # Caller must add procedure-specific part of call |
if temp <> CALL: | if temp != CALL: | def unpack_callheader(self): xid = self.unpack_uint(xid) temp = self.unpack_enum() if temp <> CALL: raise BadRPCFormat, 'no CALL but %r' % (temp,) temp = self.unpack_uint() if temp <> RPCVERSION: raise BadRPCVerspion, 'bad RPC version %r' % (temp,) prog = self.unpack_uint() vers = self.unpack_uint() proc = self.unpack_uint() cred = self.unpack_auth() verf = self.unpack_auth() return xid, prog, vers, proc, cred, verf # Caller must add procedure-specific part of call |
if temp <> RPCVERSION: raise BadRPCVerspion, 'bad RPC version %r' % (temp,) | if temp != RPCVERSION: raise BadRPCVersion, 'bad RPC version %r' % (temp,) | def unpack_callheader(self): xid = self.unpack_uint(xid) temp = self.unpack_enum() if temp <> CALL: raise BadRPCFormat, 'no CALL but %r' % (temp,) temp = self.unpack_uint() if temp <> RPCVERSION: raise BadRPCVerspion, 'bad RPC version %r' % (temp,) prog = self.unpack_uint() vers = self.unpack_uint() proc = self.unpack_uint() cred = self.unpack_auth() verf = self.unpack_auth() return xid, prog, vers, proc, cred, verf # Caller must add procedure-specific part of call |
if mtype <> REPLY: | if mtype != REPLY: | def unpack_replyheader(self): xid = self.unpack_uint() mtype = self.unpack_enum() if mtype <> REPLY: raise RuntimeError, 'no REPLY but %r' % (mtype,) stat = self.unpack_enum() if stat == MSG_DENIED: stat = self.unpack_enum() if stat == RPC_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),) if stat == AUTH_ERROR: stat = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: AUTH_ERROR: %r' % (stat,) raise RuntimeError, 'MSG_DENIED: %r' % (stat,) if stat <> MSG_ACCEPTED: raise RuntimeError, \ 'Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,) verf = self.unpack_auth() stat = self.unpack_enum() if stat == PROG_UNAVAIL: raise RuntimeError, 'call failed: PROG_UNAVAIL' if stat == PROG_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'call failed: PROG_MISMATCH: %r' % ((low, high),) if stat == PROC_UNAVAIL: raise RuntimeError, 'call failed: PROC_UNAVAIL' if stat == GARBAGE_ARGS: raise RuntimeError, 'call failed: GARBAGE_ARGS' if stat <> SUCCESS: raise RuntimeError, 'call failed: %r' % (stat,) return xid, verf # Caller must get procedure-specific part of reply |
if stat <> MSG_ACCEPTED: | if stat != MSG_ACCEPTED: | def unpack_replyheader(self): xid = self.unpack_uint() mtype = self.unpack_enum() if mtype <> REPLY: raise RuntimeError, 'no REPLY but %r' % (mtype,) stat = self.unpack_enum() if stat == MSG_DENIED: stat = self.unpack_enum() if stat == RPC_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),) if stat == AUTH_ERROR: stat = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: AUTH_ERROR: %r' % (stat,) raise RuntimeError, 'MSG_DENIED: %r' % (stat,) if stat <> MSG_ACCEPTED: raise RuntimeError, \ 'Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,) verf = self.unpack_auth() stat = self.unpack_enum() if stat == PROG_UNAVAIL: raise RuntimeError, 'call failed: PROG_UNAVAIL' if stat == PROG_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'call failed: PROG_MISMATCH: %r' % ((low, high),) if stat == PROC_UNAVAIL: raise RuntimeError, 'call failed: PROC_UNAVAIL' if stat == GARBAGE_ARGS: raise RuntimeError, 'call failed: GARBAGE_ARGS' if stat <> SUCCESS: raise RuntimeError, 'call failed: %r' % (stat,) return xid, verf # Caller must get procedure-specific part of reply |
if stat <> SUCCESS: | if stat != SUCCESS: | def unpack_replyheader(self): xid = self.unpack_uint() mtype = self.unpack_enum() if mtype <> REPLY: raise RuntimeError, 'no REPLY but %r' % (mtype,) stat = self.unpack_enum() if stat == MSG_DENIED: stat = self.unpack_enum() if stat == RPC_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),) if stat == AUTH_ERROR: stat = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: AUTH_ERROR: %r' % (stat,) raise RuntimeError, 'MSG_DENIED: %r' % (stat,) if stat <> MSG_ACCEPTED: raise RuntimeError, \ 'Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,) verf = self.unpack_auth() stat = self.unpack_enum() if stat == PROG_UNAVAIL: raise RuntimeError, 'call failed: PROG_UNAVAIL' if stat == PROG_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'call failed: PROG_MISMATCH: %r' % ((low, high),) if stat == PROC_UNAVAIL: raise RuntimeError, 'call failed: PROC_UNAVAIL' if stat == GARBAGE_ARGS: raise RuntimeError, 'call failed: GARBAGE_ARGS' if stat <> SUCCESS: raise RuntimeError, 'call failed: %r' % (stat,) return xid, verf # Caller must get procedure-specific part of reply |
if errno <> 114: | if errno != 114: | def bindresvport(sock, host): global last_resv_port_tried FIRST, LAST = 600, 1024 # Range of ports to try if last_resv_port_tried == None: import os last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST) for i in range(last_resv_port_tried, LAST) + \ range(FIRST, last_resv_port_tried): last_resv_port_tried = i try: sock.bind((host, i)) return last_resv_port_tried except socket.error, (errno, msg): if errno <> 114: raise socket.error, (errno, msg) raise RuntimeError, 'can\'t assign reserved port' |
if xid <> self.lastxid: | if xid != self.lastxid: | def do_call(self): call = self.packer.get_buf() sendrecord(self.sock, call) reply = recvrecord(self.sock) u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() if xid <> self.lastxid: # Can't really happen since this is TCP... raise RuntimeError, 'wrong xid in reply %r instead of %r' % ( xid, self.lastxid) |
if xid <> self.lastxid: | if xid != self.lastxid: | def do_call(self): call = self.packer.get_buf() self.sock.send(call) try: from select import select except ImportError: print 'WARNING: select not found, RPC may hang' select = None BUFSIZE = 8192 # Max UDP buffer size timeout = 1 count = 5 while 1: r, w, x = [self.sock], [], [] if select: r, w, x = select(r, w, x, timeout) if self.sock not in r: count = count - 1 if count < 0: raise RuntimeError, 'timeout' if timeout < 25: timeout = timeout *2 |
if xid <> self.lastxid: | if xid != self.lastxid: | def dummy(): pass |
if temp <> CALL: | if temp != CALL: | def handle(self, call): # Don't use unpack_header but parse the header piecewise # XXX I have no idea if I am using the right error responses! self.unpacker.reset(call) self.packer.reset() xid = self.unpacker.unpack_uint() self.packer.pack_uint(xid) temp = self.unpacker.unpack_enum() if temp <> CALL: return None # Not worthy of a reply self.packer.pack_uint(REPLY) temp = self.unpacker.unpack_uint() if temp <> RPCVERSION: self.packer.pack_uint(MSG_DENIED) self.packer.pack_uint(RPC_MISMATCH) self.packer.pack_uint(RPCVERSION) self.packer.pack_uint(RPCVERSION) return self.packer.get_buf() self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) prog = self.unpacker.unpack_uint() if prog <> self.prog: self.packer.pack_uint(PROG_UNAVAIL) return self.packer.get_buf() vers = self.unpacker.unpack_uint() if vers <> self.vers: self.packer.pack_uint(PROG_MISMATCH) self.packer.pack_uint(self.vers) self.packer.pack_uint(self.vers) return self.packer.get_buf() proc = self.unpacker.unpack_uint() methname = 'handle_' + repr(proc) try: meth = getattr(self, methname) except AttributeError: self.packer.pack_uint(PROC_UNAVAIL) return self.packer.get_buf() cred = self.unpacker.unpack_auth() verf = self.unpacker.unpack_auth() try: meth() # Unpack args, call turn_around(), pack reply except (EOFError, GarbageArgs): # Too few or too many arguments self.packer.reset() self.packer.pack_uint(xid) self.packer.pack_uint(REPLY) self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) self.packer.pack_uint(GARBAGE_ARGS) return self.packer.get_buf() |
if temp <> RPCVERSION: | if temp != RPCVERSION: | def handle(self, call): # Don't use unpack_header but parse the header piecewise # XXX I have no idea if I am using the right error responses! self.unpacker.reset(call) self.packer.reset() xid = self.unpacker.unpack_uint() self.packer.pack_uint(xid) temp = self.unpacker.unpack_enum() if temp <> CALL: return None # Not worthy of a reply self.packer.pack_uint(REPLY) temp = self.unpacker.unpack_uint() if temp <> RPCVERSION: self.packer.pack_uint(MSG_DENIED) self.packer.pack_uint(RPC_MISMATCH) self.packer.pack_uint(RPCVERSION) self.packer.pack_uint(RPCVERSION) return self.packer.get_buf() self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) prog = self.unpacker.unpack_uint() if prog <> self.prog: self.packer.pack_uint(PROG_UNAVAIL) return self.packer.get_buf() vers = self.unpacker.unpack_uint() if vers <> self.vers: self.packer.pack_uint(PROG_MISMATCH) self.packer.pack_uint(self.vers) self.packer.pack_uint(self.vers) return self.packer.get_buf() proc = self.unpacker.unpack_uint() methname = 'handle_' + repr(proc) try: meth = getattr(self, methname) except AttributeError: self.packer.pack_uint(PROC_UNAVAIL) return self.packer.get_buf() cred = self.unpacker.unpack_auth() verf = self.unpacker.unpack_auth() try: meth() # Unpack args, call turn_around(), pack reply except (EOFError, GarbageArgs): # Too few or too many arguments self.packer.reset() self.packer.pack_uint(xid) self.packer.pack_uint(REPLY) self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) self.packer.pack_uint(GARBAGE_ARGS) return self.packer.get_buf() |
if prog <> self.prog: | if prog != self.prog: | def handle(self, call): # Don't use unpack_header but parse the header piecewise # XXX I have no idea if I am using the right error responses! self.unpacker.reset(call) self.packer.reset() xid = self.unpacker.unpack_uint() self.packer.pack_uint(xid) temp = self.unpacker.unpack_enum() if temp <> CALL: return None # Not worthy of a reply self.packer.pack_uint(REPLY) temp = self.unpacker.unpack_uint() if temp <> RPCVERSION: self.packer.pack_uint(MSG_DENIED) self.packer.pack_uint(RPC_MISMATCH) self.packer.pack_uint(RPCVERSION) self.packer.pack_uint(RPCVERSION) return self.packer.get_buf() self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) prog = self.unpacker.unpack_uint() if prog <> self.prog: self.packer.pack_uint(PROG_UNAVAIL) return self.packer.get_buf() vers = self.unpacker.unpack_uint() if vers <> self.vers: self.packer.pack_uint(PROG_MISMATCH) self.packer.pack_uint(self.vers) self.packer.pack_uint(self.vers) return self.packer.get_buf() proc = self.unpacker.unpack_uint() methname = 'handle_' + repr(proc) try: meth = getattr(self, methname) except AttributeError: self.packer.pack_uint(PROC_UNAVAIL) return self.packer.get_buf() cred = self.unpacker.unpack_auth() verf = self.unpacker.unpack_auth() try: meth() # Unpack args, call turn_around(), pack reply except (EOFError, GarbageArgs): # Too few or too many arguments self.packer.reset() self.packer.pack_uint(xid) self.packer.pack_uint(REPLY) self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) self.packer.pack_uint(GARBAGE_ARGS) return self.packer.get_buf() |
if vers <> self.vers: | if vers != self.vers: | def handle(self, call): # Don't use unpack_header but parse the header piecewise # XXX I have no idea if I am using the right error responses! self.unpacker.reset(call) self.packer.reset() xid = self.unpacker.unpack_uint() self.packer.pack_uint(xid) temp = self.unpacker.unpack_enum() if temp <> CALL: return None # Not worthy of a reply self.packer.pack_uint(REPLY) temp = self.unpacker.unpack_uint() if temp <> RPCVERSION: self.packer.pack_uint(MSG_DENIED) self.packer.pack_uint(RPC_MISMATCH) self.packer.pack_uint(RPCVERSION) self.packer.pack_uint(RPCVERSION) return self.packer.get_buf() self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) prog = self.unpacker.unpack_uint() if prog <> self.prog: self.packer.pack_uint(PROG_UNAVAIL) return self.packer.get_buf() vers = self.unpacker.unpack_uint() if vers <> self.vers: self.packer.pack_uint(PROG_MISMATCH) self.packer.pack_uint(self.vers) self.packer.pack_uint(self.vers) return self.packer.get_buf() proc = self.unpacker.unpack_uint() methname = 'handle_' + repr(proc) try: meth = getattr(self, methname) except AttributeError: self.packer.pack_uint(PROC_UNAVAIL) return self.packer.get_buf() cred = self.unpacker.unpack_auth() verf = self.unpacker.unpack_auth() try: meth() # Unpack args, call turn_around(), pack reply except (EOFError, GarbageArgs): # Too few or too many arguments self.packer.reset() self.packer.pack_uint(xid) self.packer.pack_uint(REPLY) self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) self.packer.pack_uint(GARBAGE_ARGS) return self.packer.get_buf() |
if reply <> None: | if reply != None: | def session(self): call, host_port = self.sock.recvfrom(8192) reply = self.handle(call) if reply <> None: self.sock.sendto(reply, host_port) |
self._bounds = Qd.OffsetRect(self._possize(width, height), pl, pt) | self._bounds = Qd.OffsetRect(_intRect(self._possize(width, height)), pl, pt) | def _calcbounds(self): # calculate absolute bounds relative to the window origin from our # abstract _possize attribute, which is either a 4-tuple or a callable object oldbounds = self._bounds pl, pt, pr, pb = self._parent._bounds if callable(self._possize): # _possize is callable, let it figure it out by itself: it should return # the bounds relative to our parent widget. width = pr - pl height = pb - pt self._bounds = Qd.OffsetRect(self._possize(width, height), pl, pt) else: # _possize must be a 4-tuple. This is where the algorithm by Peter Kriens and # Petr van Blokland kicks in. (*** Parts of this algorithm are applied for # patents by Ericsson, Sweden ***) l, t, r, b = self._possize # depending on the values of l(eft), t(op), r(right) and b(ottom), # they mean different things: if l < -1: # l is less than -1, this mean it measures from the *right* of it's parent l = pr + l else: # l is -1 or greater, this mean it measures from the *left* of it's parent l = pl + l if t < -1: # t is less than -1, this mean it measures from the *bottom* of it's parent t = pb + t else: # t is -1 or greater, this mean it measures from the *top* of it's parent t = pt + t if r > 1: # r is greater than 1, this means r is the *width* of the widget r = l + r else: # r is less than 1, this means it measures from the *right* of it's parent r = pr + r if b > 1: # b is greater than 1, this means b is the *height* of the widget b = t + b else: # b is less than 1, this means it measures from the *bottom* of it's parent b = pb + b self._bounds = (l, t, r, b) if oldbounds and oldbounds <> self._bounds: self.adjust(oldbounds) for w in self._widgets: w._calcbounds() |
Qd.PaintRect(rect) | Qd.PaintRect(_intRect(rect)) | def click(self, point, modifiers): # what a mess... orgmouse = point[self._direction] halfgutter = self._gutter / 2 l, t, r, b = self._bounds if self._direction: begin, end = t, b else: begin, end = l, r i = self.findgutter(orgmouse, begin, end) if i is None: return pos = orgpos = begin + (end - begin) * self._gutters[i] # init pos too, for fast click on border, bug done by Petr minpos = self._panesizes[i][0] maxpos = self._panesizes[i+1][1] minpos = begin + (end - begin) * minpos + 64 maxpos = begin + (end - begin) * maxpos - 64 if minpos > orgpos and maxpos < orgpos: return #SetCursor("fist") self.SetPort() if self._direction: rect = l, orgpos - 1, r, orgpos else: rect = orgpos - 1, t, orgpos, b # track mouse --- XXX move to separate method? Qd.PenMode(QuickDraw.srcXor) Qd.PenPat(Qd.GetQDGlobalsGray()) Qd.PaintRect(rect) lastpos = None while Evt.Button(): pos = orgpos - orgmouse + Evt.GetMouse()[self._direction] pos = max(pos, minpos) pos = min(pos, maxpos) if pos == lastpos: continue Qd.PenPat(Qd.GetQDGlobalsGray()) Qd.PaintRect(rect) if self._direction: rect = l, pos - 1, r, pos else: rect = pos - 1, t, pos, b Qd.PenPat(Qd.GetQDGlobalsGray()) Qd.PaintRect(rect) lastpos = pos self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) Evt.WaitNextEvent(0, 3) Qd.PaintRect(rect) Qd.PenNormal() SetCursor("watch") newpos = (pos - begin) / float(end - begin) self._gutters[i] = newpos self._panesizes[i] = self._panesizes[i][0], newpos self._panesizes[i+1] = newpos, self._panesizes[i+1][1] self.makepanebounds() self.installbounds() self._calcbounds() |
_8bit = re.compile(r"[\200-\377]") def escape8bit(s): if _8bit.search(s) is not None: out = [] for c in s: o = ord(c) if o >= 128: out.append("\\" + hex(o)[1:]) else: out.append(c) s = "".join(out) return s | def initpatterns(self): Scanner.initpatterns(self) self.head_pat = "^EXTERN_API(_C)?" self.type_pat = "EXTERN_API(_C)?" + \ "[ \t\n]*\([ \t\n]*" + \ "(?P<type>[a-zA-Z0-9_* \t]*[a-zA-Z0-9_*])" + \ "[ \t\n]*\)[ \t\n]*" self.whole_pat = self.type_pat + self.name_pat + self.args_pat self.sym_pat = "^[ \t]*(?P<name>[a-zA-Z0-9_]+)[ \t]*=" + \ "[ \t]*(?P<defn>[-0-9_a-zA-Z'\"\(][^\t\n,;}]*),?" |
|
fss = alias.Resolve()[0] pathname = fss.as_pathname() | fsr = alias.FSResolveAlias(None)[0] pathname = fsr.as_pathname() | def open_file(self, _object=None, **args): for alias in _object: fss = alias.Resolve()[0] pathname = fss.as_pathname() sys.argv.append(pathname) self._quit() |
return section in self.sections() | return section in self.__sections | def has_section(self, section): """Indicate whether the named section is present in the configuration. |
sectdict = self.__sections[section].copy() | d.update(self.__sections[section]) | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
if section == DEFAULTSECT: sectdict = {} else: | if section != DEFAULTSECT: | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
d = self.__defaults.copy() d.update(sectdict) | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
|
rawval = d[option] | value = d[option] | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
return rawval | return value return self._interpolate(section, option, value, d) def _interpolate(self, section, option, rawval, vars): | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
value = rawval depth = 0 while depth < 10: depth = depth + 1 if value.find("%(") >= 0: | value = rawval depth = MAX_INTERPOLATION_DEPTH while depth: depth -= 1 if value.find("%(") != -1: | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
value = value % d | value = value % vars | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
if value.find("%(") >= 0: | if value.find("%(") != -1: | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
states = {'1': 1, 'yes': 1, 'true': 1, 'on': 1, '0': 0, 'no': 0, 'false': 0, 'off': 0} | def getboolean(self, section, option): states = {'1': 1, 'yes': 1, 'true': 1, 'on': 1, '0': 0, 'no': 0, 'false': 0, 'off': 0} v = self.get(section, option) if not v.lower() in states: raise ValueError, 'Not a boolean: %s' % v return states[v.lower()] |
|
if not v.lower() in states: | if v.lower() not in self._boolean_states: | def getboolean(self, section, option): states = {'1': 1, 'yes': 1, 'true': 1, 'on': 1, '0': 0, 'no': 0, 'false': 0, 'off': 0} v = self.get(section, option) if not v.lower() in states: raise ValueError, 'Not a boolean: %s' % v return states[v.lower()] |
return states[v.lower()] | return self._boolean_states[v.lower()] | def getboolean(self, section, option): states = {'1': 1, 'yes': 1, 'true': 1, 'on': 1, '0': 0, 'no': 0, 'false': 0, 'off': 0} v = self.get(section, option) if not v.lower() in states: raise ValueError, 'Not a boolean: %s' % v return states[v.lower()] |
if not section or section == "DEFAULT": | if not section or section == DEFAULTSECT: option = self.optionxform(option) | def has_option(self, section, option): """Check for the existence of a given option in a given section.""" if not section or section == "DEFAULT": return option in self.__defaults elif not self.has_section(section): return 0 else: option = self.optionxform(option) return option in self.__sections[section] |
elif not self.has_section(section): | elif section not in self.__sections: | def has_option(self, section, option): """Check for the existence of a given option in a given section.""" if not section or section == "DEFAULT": return option in self.__defaults elif not self.has_section(section): return 0 else: option = self.optionxform(option) return option in self.__sections[section] |
return option in self.__sections[section] | return (option in self.__sections[section] or option in self.__defaults) | def has_option(self, section, option): """Check for the existence of a given option in a given section.""" if not section or section == "DEFAULT": return option in self.__defaults elif not self.has_section(section): return 0 else: option = self.optionxform(option) return option in self.__sections[section] |
if not section or section == "DEFAULT": | if not section or section == DEFAULTSECT: | def set(self, section, option, value): """Set an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) option = self.optionxform(option) sectdict[option] = value |
option = self.optionxform(option) sectdict[option] = value | sectdict[self.optionxform(option)] = value | def set(self, section, option, value): """Set an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) option = self.optionxform(option) sectdict[option] = value |
fp.write("[DEFAULT]\n") | fp.write("[%s]\n" % DEFAULTSECT) | def write(self, fp): """Write an .ini-format representation of the configuration state.""" if self.__defaults: fp.write("[DEFAULT]\n") for (key, value) in self.__defaults.items(): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self.sections(): fp.write("[" + section + "]\n") sectdict = self.__sections[section] for (key, value) in sectdict.items(): if key == "__name__": continue fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") |
for section in self.sections(): fp.write("[" + section + "]\n") sectdict = self.__sections[section] for (key, value) in sectdict.items(): if key == "__name__": continue fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) | for section in self.__sections: fp.write("[%s]\n" % section) for (key, value) in self.__sections[section].items(): if key != "__name__": fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) | def write(self, fp): """Write an .ini-format representation of the configuration state.""" if self.__defaults: fp.write("[DEFAULT]\n") for (key, value) in self.__defaults.items(): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self.sections(): fp.write("[" + section + "]\n") sectdict = self.__sections[section] for (key, value) in sectdict.items(): if key == "__name__": continue fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") |
if not section or section == "DEFAULT": | if not section or section == DEFAULTSECT: | def remove_option(self, section, option): """Remove an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) option = self.optionxform(option) existed = option in sectdict if existed: del sectdict[option] return existed |
if section in self.__sections: | existed = section in self.__sections if existed: | def remove_section(self, section): """Remove a file section.""" if section in self.__sections: del self.__sections[section] return True else: return False |
return True else: return False | return existed | def remove_section(self, section): """Remove a file section.""" if section in self.__sections: del self.__sections[section] return True else: return False |
r'(?P<option>[]\-[\w_.*,(){}]+)' r'[ \t]*(?P<vi>[:=])[ \t]*' | r'(?P<option>[^:=\s]+)' r'\s*(?P<vi>[:=])\s*' | def remove_section(self, section): """Remove a file section.""" if section in self.__sections: del self.__sections[section] return True else: return False |
if line.split()[0].lower() == 'rem' \ and line[0] in "rR": | if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR": | def __read(self, fp, fpname): """Parse a sectioned setup file. |
if line[0] in ' \t' and cursect is not None and optname: | if line[0].isspace() and cursect is not None and optname: | def __read(self, fp, fpname): """Parse a sectioned setup file. |
k = self.optionxform(optname) cursect[k] = "%s\n%s" % (cursect[k], value) | cursect[optname] = "%s\n%s" % (cursect[optname], value) | def __read(self, fp, fpname): """Parse a sectioned setup file. |
if pos and optval[pos-1].isspace(): | if pos != -1 and optval[pos-1].isspace(): | def __read(self, fp, fpname): """Parse a sectioned setup file. |
cursect[self.optionxform(optname)] = optval | optname = self.optionxform(optname) cursect[optname] = optval | def __read(self, fp, fpname): """Parse a sectioned setup file. |
"verify we can open a file known to be a hash v2 file" | def test_open_existing_hash(self): "verify we can open a file known to be a hash v2 file" db = bsddb185.hashopen(findfile("185test.db")) self.assertEqual(db["1"], "1") db.close() |
|
"verify that whichdb correctly sniffs the known hash v2 file" | def test_whichdb(self): "verify that whichdb correctly sniffs the known hash v2 file" self.assertEqual(whichdb.whichdb(findfile("185test.db")), "bsddb185") |
|
"verify that anydbm.open does *not* create a bsddb185 file" | def test_anydbm_create(self): "verify that anydbm.open does *not* create a bsddb185 file" tmpdir = tempfile.mkdtemp() try: try: dbfile = os.path.join(tmpdir, "foo.db") anydbm.open(dbfile, "c").close() ftype = whichdb.whichdb(findfile("foo.db")) self.assertNotEqual(ftype, "bsddb185") finally: os.unlink(dbfile) finally: os.rmdir(tmpdir) |
|
anydbm.open(dbfile, "c").close() ftype = whichdb.whichdb(findfile("foo.db")) | anydbm.open(os.path.splitext(dbfile)[0], "c").close() ftype = whichdb.whichdb(dbfile) | def test_anydbm_create(self): "verify that anydbm.open does *not* create a bsddb185 file" tmpdir = tempfile.mkdtemp() try: try: dbfile = os.path.join(tmpdir, "foo.db") anydbm.open(dbfile, "c").close() ftype = whichdb.whichdb(findfile("foo.db")) self.assertNotEqual(ftype, "bsddb185") finally: os.unlink(dbfile) finally: os.rmdir(tmpdir) |
"""execv(file, args, env) | """execvpe(file, args, env) | def execvpe(file, args, env): """execv(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env , replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args, env) |
except error, (errno, msg): if errno != ENOENT and errno != ENOTDIR: raise raise error, (errno, msg) | except error, e: tb = sys.exc_info()[2] if (e.errno != ENOENT and e.errno != ENOTDIR and saved_exc is None): saved_exc = e saved_tb = tb if saved_exc: raise error, saved_exc, saved_tb raise error, e, tb | def _execvpe(file, args, env=None): from errno import ENOENT, ENOTDIR if env is not None: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ head, tail = path.split(file) if head: apply(func, (file,) + argrest) return if 'PATH' in env: envpath = env['PATH'] else: envpath = defpath PATH = envpath.split(pathsep) for dir in PATH: fullname = path.join(dir, file) try: apply(func, (fullname,) + argrest) except error, (errno, msg): if errno != ENOENT and errno != ENOTDIR: raise raise error, (errno, msg) |
return eval("self.%s" % attr.lower()) | return getattr(self, attr.lower()) | def __getattr__(self, attr): # Allow UPPERCASE variants of IMAP4 command methods. if Commands.has_key(attr): return eval("self.%s" % attr.lower()) raise AttributeError("Unknown IMAP4 command: '%s'" % attr) |
def socket(self): """Return socket instance used to connect to IMAP4 server. socket = <instance>.socket() """ return self.sock | def response(self, code): """Return data for response 'code' if received, or None. |
|
self.file.close() self.sock.close() | self.shutdown() | def logout(self): """Shutdown connection to server. |
charset = 'CHARSET ' + charset typ, dat = apply(self._simple_command, (name, charset) + criteria) | typ, dat = apply(self._simple_command, (name, 'CHARSET', charset) + criteria) else: typ, dat = apply(self._simple_command, (name,) + criteria) | def search(self, charset, *criteria): """Search mailbox for matching messages. |
if self.PROTOCOL_VERSION == 'IMAP4': raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name) | def status(self, mailbox, names): """Request named status conditions for mailbox. |
|
if command == 'SEARCH': name = 'SEARCH' | if command in ('SEARCH', 'SORT'): name = command | def uid(self, command, *args): """Execute "command arg ..." with messages identified by UID, rather than message number. |
""" if name[0] != 'X' or not name in self.capabilities: raise self.error('unknown extension command: %s' % name) | Returns response appropriate to extension command `name'. """ name = name.upper() if not Commands.has_key(name): Commands[name] = (self.state,) | def xatom(self, name, *args): """Allow simple extension commands notified by server in CAPABILITY response. |
def namespace(self): """ Returns IMAP namespaces ala rfc2342 """ name = 'NAMESPACE' typ, dat = self._simple_command(name) return self._untagged_response(typ, dat, name) | def namespace(self): """ Returns IMAP namespaces ala rfc2342 """ name = 'NAMESPACE' typ, dat = self._simple_command(name) return self._untagged_response(typ, dat, name) |
|
self.sock.send('%s%s' % (data, CRLF)) except socket.error, val: | self.send('%s%s' % (data, CRLF)) except (socket.error, OSError), val: | def _command(self, name, *args): |
self.sock.send(literal) self.sock.send(CRLF) except socket.error, val: | self.send(literal) self.send(CRLF) except (socket.error, OSError), val: | def _command(self, name, *args): |
data = self.file.read(size) | data = self.read(size) | def _get_response(self): |
line = self.file.readline() | line = self.readline() | def _get_line(self): |
typ, dat = apply(eval('M.%s' % cmd), args) | typ, dat = apply(getattr(M, cmd), args) | def run(cmd, args): _mesg('%s %s' % (cmd, args)) typ, dat = apply(eval('M.%s' % cmd), args) _mesg('%s => %s %s' % (cmd, typ, dat)) return dat |
ext.export_symbol_file = build_info.get('def_file') | if build_info.has_key('def_file'): self.warn("'def_file' element of build info dict " "no longer supported") | def check_extensions_list (self, extensions): """Ensure that the list of extensions (presumably provided as a command option 'extensions') is valid, i.e. it is a list of Extension objects. We also support the old-style list of 2-tuples, where the tuples are (ext_name, build_info), which are converted to Extension instances here. |
if self.compiler.compiler_type == 'msvc': self.msvc_prelink_hack(sources, ext, extra_args) | def build_extensions (self): |
|
libraries=ext.libraries, | libraries=self.get_libraries(ext), | def build_extensions (self): |
def msvc_prelink_hack (self, sources, ext, extra_args): def_file = ext.export_symbol_file if def_file is not None: extra_args.append ('/DEF:' + def_file) else: modname = string.split (ext.name, '.')[-1] extra_args.append('/export:init%s' % modname) implib_file = os.path.join ( self.implib_dir, self.get_ext_libname (ext.name)) extra_args.append ('/IMPLIB:' + implib_file) self.mkpath (os.path.dirname (implib_file)) | def find_swig (self): """Return the name of the SWIG executable. On Unix, this is just "swig" -- it should be in the PATH. Tries a bit harder on Windows. """ |
|
f.name) else: raise try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.errno == errno.EWOULDBLOCK: raise ExternalClashError('flock: lock unavailable: %s' % | def _lock_file(f, dotlock=True): """Lock file f using lockf, flock, and dot locking.""" dotlock_done = False try: if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.errno == errno.EAGAIN: raise ExternalClashError('lockf: lock unavailable: %s' % f.name) else: raise try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.errno == errno.EWOULDBLOCK: raise ExternalClashError('flock: lock unavailable: %s' % f.name) else: raise if dotlock: try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() except IOError, e: if e.errno == errno.EACCES: return # Without write access, just skip dotlocking. else: raise try: if hasattr(os, 'link'): os.link(pre_lock.name, f.name + '.lock') dotlock_done = True os.unlink(pre_lock.name) else: os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True except OSError, e: if e.errno == errno.EEXIST: os.remove(pre_lock.name) raise ExternalClashError('dot lock unavailable: %s' % f.name) else: raise except: if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) fcntl.flock(f, fcntl.LOCK_UN) if dotlock_done: os.remove(f.name + '.lock') raise |
|
fcntl.flock(f, fcntl.LOCK_UN) | def _lock_file(f, dotlock=True): """Lock file f using lockf, flock, and dot locking.""" dotlock_done = False try: if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.errno == errno.EAGAIN: raise ExternalClashError('lockf: lock unavailable: %s' % f.name) else: raise try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.errno == errno.EWOULDBLOCK: raise ExternalClashError('flock: lock unavailable: %s' % f.name) else: raise if dotlock: try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() except IOError, e: if e.errno == errno.EACCES: return # Without write access, just skip dotlocking. else: raise try: if hasattr(os, 'link'): os.link(pre_lock.name, f.name + '.lock') dotlock_done = True os.unlink(pre_lock.name) else: os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True except OSError, e: if e.errno == errno.EEXIST: os.remove(pre_lock.name) raise ExternalClashError('dot lock unavailable: %s' % f.name) else: raise except: if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) fcntl.flock(f, fcntl.LOCK_UN) if dotlock_done: os.remove(f.name + '.lock') raise |
|
fcntl.flock(f, fcntl.LOCK_UN) | def _unlock_file(f): """Unlock file f using lockf, flock, and dot locking.""" if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) fcntl.flock(f, fcntl.LOCK_UN) if os.path.exists(f.name + '.lock'): os.remove(f.name + '.lock') |
|
return map(self._nametowidget, self.tk.splitlist(self.tk.call( 'winfo', 'children', self._w))) | result = [] for child in self.tk.splitlist( self.tk.call('winfo', 'children', self._w)): try: result.append(self._nametowidget(child)) except KeyError: pass return result | def winfo_children(self): """Return a list of all widgets which are children of this widget.""" return map(self._nametowidget, self.tk.splitlist(self.tk.call( 'winfo', 'children', self._w))) |
print "proxy via http:", host, selector | def open_http(self, url, data=None): 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_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) print "proxy via http:", host, selector if not host: raise IOError, ('http error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTP(host) if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector) if auth: h.putheader('Authorization', 'Basic %s' % auth) for args in self.addheaders: apply(h.putheader, args) h.endheaders() if data is not None: h.send(data + '\r\n') errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, self.openedurl) else: return self.http_error(url, fp, errcode, errmsg, headers) |
|
req_host, erhn = eff_request_host(request) strict_non_domain = ( self._policy.strict_ns_domain & self._policy.DomainStrictNonDomain) | def add_cookie_header(self, request): """Add correct Cookie: header to request (urllib2.Request object). |
|
pid, sts = os.wait(G.busy, options) | pid, sts = os.waitpid(G.busy, options) | def waitchild(options): pid, sts = os.wait(G.busy, options) if pid == G.busy: G.busy = 0 G.stop.enable(0) |
r = (40, 40, 400, 300) | r = windowbounds(400, 400) | def open(self, path, name, data): self.path = path self.name = name r = (40, 40, 400, 300) w = Win.NewWindow(r, name, 1, 0, -1, 1, 0x55555555) self.wid = w r2 = (0, 0, 345, 245) Qd.SetPort(w) Qd.TextFont(4) Qd.TextSize(9) self.ted = TE.TENew(r2, r2) self.ted.TEAutoView(1) self.ted.TESetText(data) w.DrawGrowIcon() self.scrollbars() self.changed = 0 self.do_postopen() self.do_activate(1, None) |
r2 = (0, 0, 345, 245) | vr = 0, 0, r[2]-r[0]-15, r[3]-r[1]-15 dr = (0, 0, vr[2], 0) | def open(self, path, name, data): self.path = path self.name = name r = (40, 40, 400, 300) w = Win.NewWindow(r, name, 1, 0, -1, 1, 0x55555555) self.wid = w r2 = (0, 0, 345, 245) Qd.SetPort(w) Qd.TextFont(4) Qd.TextSize(9) self.ted = TE.TENew(r2, r2) self.ted.TEAutoView(1) self.ted.TESetText(data) w.DrawGrowIcon() self.scrollbars() self.changed = 0 self.do_postopen() self.do_activate(1, None) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.