bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def visitModule(self, mod): self.emit("""
def visitModule(self, mod): self.emit("""
9,600
def addObj(self, name): self.emit('if(PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return;' % (name, name), 1)
def addObj(self, name): self.emit('if(PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return;' % (name, name), 1)
9,601
def master_open(): """Open pty master and return (master_fd, tty_name). SGI and Linux/BSD version.""" try: import sgi except ImportError: pass else: try: tty_name, master_fd = sgi._getpty(FCNTL.O_RDWR, 0666, 0) except IOError, msg: raise os.error, msg return master_fd, tty_name for x in 'pqrstuvwxyzPQRST': for y in '0123456789abcdef': pty_name = '/dev/pty' + x + y try: fd = os.open(pty_name, FCNTL.O_RDWR) except os.error: continue return (fd, '/dev/tty' + x + y) raise os.error, 'out of pty devices'
def master_open(): """Open pty master and return (master_fd, tty_name). SGI and generic BSD version, for when openpty() fails.""" try: import sgi except ImportError: pass else: try: tty_name, master_fd = sgi._getpty(FCNTL.O_RDWR, 0666, 0) except IOError, msg: raise os.error, msg return master_fd, tty_name for x in 'pqrstuvwxyzPQRST': for y in '0123456789abcdef': pty_name = '/dev/pty' + x + y try: fd = os.open(pty_name, FCNTL.O_RDWR) except os.error: continue return (fd, '/dev/tty' + x + y) raise os.error, 'out of pty devices'
9,602
def slave_open(tty_name): """Open the pty slave and acquire the controlling terminal. Return the file descriptor. Linux version.""" # (Should be universal? --Guido) return os.open(tty_name, FCNTL.O_RDWR)
def slave_open(tty_name): """Open the pty slave and acquire the controlling terminal. Return the file descriptor. Linux version.""" # (Should be universal? --Guido) return os.open(tty_name, FCNTL.O_RDWR)
9,603
def fork(): """Fork and make the child a session leader with a controlling terminal. Return (pid, master_fd).""" master_fd, tty_name = master_open() pid = os.fork() if pid == CHILD: # Establish a new session. os.setsid() # Acquire controlling terminal. slave_fd = slave_open(tty_name) os.close(master_fd) # Slave becomes stdin/stdout/stderr of child. os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if (slave_fd > STDERR_FILENO): os.close (slave_fd) # Parent and child process. return pid, master_fd
def fork(): """fork() -> (pid, master_fd) Fork and make the child a session leader with a controlling terminal.""" try: pid, fd = os.forkpty() except (AttributeError, OSError): pass else: if pid == CHILD: try: os.setsid() except OSError: pass return pid, fd master_fd, slave_fd = openpty() pid = os.fork() if pid == CHILD: # Establish a new session. os.setsid() # Acquire controlling terminal. slave_fd = slave_open(tty_name) os.close(master_fd) # Slave becomes stdin/stdout/stderr of child. os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if (slave_fd > STDERR_FILENO): os.close (slave_fd) # Parent and child process. return pid, master_fd
9,604
def fork(): """Fork and make the child a session leader with a controlling terminal. Return (pid, master_fd).""" master_fd, tty_name = master_open() pid = os.fork() if pid == CHILD: # Establish a new session. os.setsid() # Acquire controlling terminal. slave_fd = slave_open(tty_name) os.close(master_fd) # Slave becomes stdin/stdout/stderr of child. os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if (slave_fd > STDERR_FILENO): os.close (slave_fd) # Parent and child process. return pid, master_fd
def fork(): """Fork and make the child a session leader with a controlling terminal. Return (pid, master_fd).""" master_fd, tty_name = master_open() pid = os.fork() if pid == CHILD: # Establish a new session. os.setsid() # Acquire controlling terminal. slave_fd = slave_open(tty_name) os.close(master_fd) # Slave becomes stdin/stdout/stderr of child. os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if (slave_fd > STDERR_FILENO): os.close (slave_fd) # Parent and child process. return pid, master_fd
9,605
def writen(fd, data): """Write all the data to a descriptor.""" while data != '': n = os.write(fd, data) data = data[n:]
def _writen(fd, data): """Write all the data to a descriptor.""" while data != '': n = os.write(fd, data) data = data[n:]
9,606
def read(fd): """Default read function.""" return os.read(fd, 1024)
def _read(fd): """Default read function.""" return os.read(fd, 1024)
9,607
def copy(master_fd, master_read=read, stdin_read=read): """Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)""" while 1: rfds, wfds, xfds = select( [master_fd, STDIN_FILENO], [], []) if master_fd in rfds: data = master_read(master_fd) os.write(STDOUT_FILENO, data) if STDIN_FILENO in rfds: data = stdin_read(STDIN_FILENO) writen(master_fd, data)
def _copy(master_fd, master_read=_read, stdin_read=_read): """Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)""" while 1: rfds, wfds, xfds = select( [master_fd, STDIN_FILENO], [], []) if master_fd in rfds: data = master_read(master_fd) os.write(STDOUT_FILENO, data) if STDIN_FILENO in rfds: data = stdin_read(STDIN_FILENO) writen(master_fd, data)
9,608
def copy(master_fd, master_read=read, stdin_read=read): """Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)""" while 1: rfds, wfds, xfds = select( [master_fd, STDIN_FILENO], [], []) if master_fd in rfds: data = master_read(master_fd) os.write(STDOUT_FILENO, data) if STDIN_FILENO in rfds: data = stdin_read(STDIN_FILENO) writen(master_fd, data)
def copy(master_fd, master_read=read, stdin_read=read): """Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)""" while 1: rfds, wfds, xfds = select( [master_fd, STDIN_FILENO], [], []) if master_fd in rfds: data = master_read(master_fd) os.write(STDOUT_FILENO, data) if STDIN_FILENO in rfds: data = stdin_read(STDIN_FILENO) _writen(master_fd, data)
9,609
def subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar=None): stack = [] while line: if line[0] == endchar and not stack: return line[1:] m = _comment_rx.match(line) if m: text = m.group(1) if text: ofp.write("(COMMENT\n") ofp.write("- %s \n" % encode(text)) ofp.write(")COMMENT\n") ofp.write("-\\n\n") else: ofp.write("-\\n\n") line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m =_end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in autoclosing: raise LaTeXFormatError("open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] ofp.write(")document\n") elif envname == stack[-1]: ofp.write(")%s\n" % envname) del stack[-1] else: raise LaTeXFormatError("environment close doesn't match") line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] ofp.write("(verbatim\n") ofp.write("-%s\n" % encode(text)) ofp.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in autoclosing and macroname in stack: while stack[-1] != macroname: if stack[-1] and stack[-1] not in discards: ofp.write(")%s\n-\\n\n" % stack[-1]) del stack[-1] if macroname not in discards: ofp.write("-\\n\n)%s\n-\\n\n" % macroname) del stack[-1] real_ofp = ofp if macroname in discards: ofp = StringIO.StringIO() # conversion = table.get(macroname, ([], 0, 0)) params, optional, empty = conversion empty = empty or knownempty(macroname) if empty: ofp.write("e\n") if not numbered: ofp.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: line = line = line[m.end():] else: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch is that # this needs to occur outside the for loop that handles attribute # parsing so we can 'continue' the outer loop. # if optional and type(params[0]) is type(()): # the attribute name isn't used in this special case stack.append(macroname) ofp.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: line = line[m.end():] line = subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar="]") line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is type(""): m = _optional_rx.match(line) if m: line = line[m.end():] ofp.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is type(()): # This is a sub-element; but don't place the # element we found on the stack (\section-like) stack.append(macroname) ofp.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is type([]): # A normal subelement. attrname = attrname[0] stack.append(macroname) stack.append(attrname) ofp.write("(%s\n" % macroname) macroname = attrname else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter group: " + `line`) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" ofp.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] stack.append(macroname) ofp.write("(%s\n" % macroname) if empty: line = "}" + line ofp = real_ofp continue if line[0] == "}": # end of macro macroname = stack[-1] conversion = table.get(macroname) if macroname \ and macroname not in discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group ofp.write(")%s\n" % stack[-1]) del stack[-1] line = line[1:] continue if line[0] == "{": stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: ofp.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": ofp.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) ofp.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": ofp.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra))
def subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar=None): stack = [] while line: if line[0] == endchar and not stack: return line[1:] m = _comment_rx.match(line) if m: text = m.group(1) if text: ofp.write("(COMMENT\n") ofp.write("- %s \n" % encode(text)) ofp.write(")COMMENT\n") ofp.write("-\\n\n") else: ofp.write("-\\n\n") line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m =_end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in autoclosing: raise LaTeXFormatError("open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] ofp.write(")document\n") elif envname == stack[-1]: ofp.write(")%s\n" % envname) del stack[-1] else: raise LaTeXFormatError("environment close doesn't match") line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] ofp.write("(verbatim\n") ofp.write("-%s\n" % encode(text)) ofp.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in autoclosing and macroname in stack: while stack[-1] != macroname: if stack[-1] and stack[-1] not in discards: ofp.write(")%s\n-\\n\n" % stack[-1]) del stack[-1] if macroname not in discards: ofp.write("-\\n\n)%s\n-\\n\n" % macroname) del stack[-1] real_ofp = ofp if macroname in discards: ofp = StringIO.StringIO() # conversion = table.get(macroname, ([], 0, 0)) params, optional, empty = conversion empty = empty or knownempty(macroname) if empty: ofp.write("e\n") if not numbered: ofp.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: line = line = line[m.end():] else: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch is that # this needs to occur outside the for loop that handles attribute # parsing so we can 'continue' the outer loop. # if optional and type(params[0]) is type(()): # the attribute name isn't used in this special case stack.append(macroname) ofp.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: line = line[m.end():] line = subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar="]") line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is type(""): m = _optional_rx.match(line) if m: line = line[m.end():] ofp.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is type(()): # This is a sub-element; but don't place the # element we found on the stack (\section-like) stack.append(macroname) ofp.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is type([]): # A normal subelement. attrname = attrname[0] stack.append(macroname) stack.append(attrname) ofp.write("(%s\n" % macroname) macroname = attrname else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" ofp.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] stack.append(macroname) ofp.write("(%s\n" % macroname) if empty: line = "}" + line ofp = real_ofp continue if line[0] == "}": # end of macro macroname = stack[-1] conversion = table.get(macroname) if macroname \ and macroname not in discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group ofp.write(")%s\n" % stack[-1]) del stack[-1] line = line[1:] continue if line[0] == "{": stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: ofp.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": ofp.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) ofp.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": ofp.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra))
9,610
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f,r in self.replace_paths: if original_filename.startswith(f): new_filename = r+original_filename[len(f):] break
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f,r in self.replace_paths: if original_filename.startswith(f): new_filename = r+original_filename[len(f):] break
9,611
def _stringify(string): return string
def _stringify(string): return string
9,612
def __repr__(self): return ( "<Fault %s: %s>" % (repr(self.faultCode), repr(self.faultString)) )
def __repr__(self): return ( "<Fault %s: %s>" % (self.faultCode, repr(self.faultString)) )
9,613
def __init__(self, target): import xmllib # lazy subclassing (!) if xmllib.XMLParser not in SlowParser.__bases__: SlowParser.__bases__ = (xmllib.XMLParser,) self.handle_xml = target.xml self.unknown_starttag = target.start self.handle_data = target.data self.unknown_endtag = target.end xmllib.XMLParser.__init__(self)
def __init__(self, target): import xmllib # lazy subclassing (!) if xmllib.XMLParser not in SlowParser.__bases__: SlowParser.__bases__ = (xmllib.XMLParser,) self.handle_xml = target.xml self.unknown_starttag = target.start self.handle_data = target.data self.unknown_endtag = target.end xmllib.XMLParser.__init__(self)
9,614
def dump_instance(self, value): # check for special wrappers if value.__class__ in WRAPPERS: value.encode(self) else: # store instance attributes as a struct (really?) self.dump_struct(value.__dict__)
def dump_instance(self, value): # check for special wrappers if value.__class__ in WRAPPERS: value.encode(self) else: # store instance attributes as a struct (really?) self.dump_struct(value.__dict__)
9,615
def dump_instance(self, value): # check for special wrappers if value.__class__ in WRAPPERS: value.encode(self) else: # store instance attributes as a struct (really?) self.dump_struct(value.__dict__)
def dump_instance(self, value): # check for special wrappers if value.__class__ in WRAPPERS: value.encode(self) else: # store instance attributes as a struct (really?) self.dump_struct(value.__dict__)
9,616
def getparser(): """getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects. """ if FastParser and FastUnmarshaller: target = FastUnmarshaller(True, False, binary, datetime) parser = FastParser(target) else: target = Unmarshaller() if FastParser: parser = FastParser(target) elif SgmlopParser: parser = SgmlopParser(target) elif ExpatParser: parser = ExpatParser(target) else: parser = SlowParser(target) return parser, target
def getparser(): """getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects. """ if FastParser and FastUnmarshaller: target = FastUnmarshaller(True, False, binary, datetime) parser = FastParser(target) else: target = Unmarshaller() if FastParser: parser = FastParser(target) elif SgmlopParser: parser = SgmlopParser(target) elif ExpatParser: parser = ExpatParser(target) else: parser = SlowParser(target) return parser, target
9,617
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert isinstance(params, TupleType) or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert isinstance(params, TupleType) or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
9,618
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert isinstance(params, TupleType) or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, where necessary. """ assert isinstance(params, TupleType) or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
9,619
def write(self, s, tags=(), mark="insert"): self.text.insert(mark, str(s), tags) self.text.see(mark) self.text.update()
def write(self, s, tags=(), mark="insert"): self.text.insert(mark, s, tags) self.text.see(mark) self.text.update()
9,620
def visitSum(self, sum, name): if is_simple(sum): self.simpleSum(sum, name) return self.func_begin(name) self.emit("switch (o->kind) {", 1) for i in range(len(sum.types)): t = sum.types[i] self.visitConstructor(t, i + 1, name) self.emit("}", 1) for a in sum.attributes: self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1) self.emit("if (!value) goto failed;", 1) self.emit('PyObject_SetAttrString(result, "%s", value);' % a.name, 1) self.func_end()
def visitSum(self, sum, name): if is_simple(sum): self.simpleSum(sum, name) return self.func_begin(name) self.emit("switch (o->kind) {", 1) for i in range(len(sum.types)): t = sum.types[i] self.visitConstructor(t, i + 1, name) self.emit("}", 1) for a in sum.attributes: self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1) self.emit("if (!value) goto failed;", 1) self.emit('if (PyObject_SetAttrString(result, "%s", value) < 0)' % a.name, 1) self.emit('goto failed;', 2) self.emit('Py_DECREF(value);', 1) self.func_end()
9,621
def mkpath (self, name, mode=0777): mkpath (name, mode, self.verbose, self.dry_run)
def mkpath (self, name, mode=0777): mkpath (name, mode, self.verbose, self.dry_run)
9,622
def test_main(): tests = [Signed_TestCase, Unsigned_TestCase] try: from _testcapi import getargs_L, getargs_K except ImportError: pass # PY_LONG_LONG not available else: tests.append(LongLong_TestCase) test_support.run_unittest(*tests)
def test_main(): tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase] try: from _testcapi import getargs_L, getargs_K except ImportError: pass # PY_LONG_LONG not available else: tests.append(LongLong_TestCase) test_support.run_unittest(*tests)
9,623
def findtemplate(template=None): """Locate the applet template along sys.path""" if MacOS.runtimemodel == 'macho': if template: return template return findtemplate_macho() if not template: template=TEMPLATE for p in sys.path: file = os.path.join(p, template) try: file, d1, d2 = Carbon.File.FSResolveAliasFile(file, 1) break except (Carbon.File.error, ValueError): continue else: raise BuildError, "Template %s not found on sys.path" % `template` file = file.as_pathname() return file
def findtemplate(template=None): """Locate the applet template along sys.path""" if MacOS.runtimemodel == 'macho': if template: return template return findtemplate_macho() if not template: template=TEMPLATE for p in sys.path: file = os.path.join(p, template) try: file, d1, d2 = Carbon.File.FSResolveAliasFile(file, 1) break except (Carbon.File.Error, ValueError): continue else: raise BuildError, "Template %s not found on sys.path" % `template` file = file.as_pathname() return file
9,624
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[]): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others) if others: raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template if progress: progress.label("Copy data fork...") progress.set(10) if copy_codefragment: tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl # Open the output resource fork if progress: progress.label("Copy resources...") progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, destfile, RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#'] if not copy_codefragment: skiptypes.append('cfrg')
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[]): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others) if others: raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template if progress: progress.label("Copy data fork...") progress.set(10) if copy_codefragment: tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl # Open the output resource fork if progress: progress.label("Copy resources...") progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#'] if not copy_codefragment: skiptypes.append('cfrg')
9,625
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[]): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others) if others: raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template if progress: progress.label("Copy data fork...") progress.set(10) if copy_codefragment: tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl # Open the output resource fork if progress: progress.label("Copy resources...") progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, destfile, RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#'] if not copy_codefragment: skiptypes.append('cfrg')
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[]): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others) if others: raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template if progress: progress.label("Copy data fork...") progress.set(10) if copy_codefragment: tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl # Open the output resource fork if progress: progress.label("Copy resources...") progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, destfile, RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#'] if not copy_codefragment: skiptypes.append('cfrg')
9,626
def fact(n): if n < 1: raise error # fact() argument should be >= 1 if n == 1: return [] # special case res = [] # Treat even factors special, so we can use i = i+2 later while n%2 == 0: res.append(2) n = n/2 # Try odd numbers up to sqrt(n) limit = sqrt(n+1) i = 3 while i <= limit: if n%i == 0: res.append(i) n = n/i limit = sqrt(n+1) else: i = i+2 res.append(n) return res
def fact(n): if n < 1: raise error # fact() argument should be >= 1 if n == 1: return [] # special case res = [] # Treat even factors special, so we can use i = i+2 later while n%2 == 0: res.append(2) n = n/2 # Try odd numbers up to sqrt(n) limit = sqrt(float(n+1)) i = 3 while i <= limit: if n%i == 0: res.append(i) n = n/i limit = sqrt(float(n+1)) else: i = i+2 res.append(n) return res
9,627
def fact(n): if n < 1: raise error # fact() argument should be >= 1 if n == 1: return [] # special case res = [] # Treat even factors special, so we can use i = i+2 later while n%2 == 0: res.append(2) n = n/2 # Try odd numbers up to sqrt(n) limit = sqrt(n+1) i = 3 while i <= limit: if n%i == 0: res.append(i) n = n/i limit = sqrt(n+1) else: i = i+2 res.append(n) return res
def fact(n): if n < 1: raise error # fact() argument should be >= 1 if n == 1: return [] # special case res = [] # Treat even factors special, so we can use i = i+2 later while n%2 == 0: res.append(2) n = n/2 # Try odd numbers up to sqrt(n) limit = sqrt(n+1) i = 3 while i <= limit: if n%i == 0: res.append(i) n = n/i limit = sqrt(n+1) else: i = i+2 if n != 1: res.append(n) return res
9,628
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
9,629
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
9,630
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
9,631
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
9,632
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
9,633
def all_method(self): return "D b"
def all_method(self): return "D b"
9,634
def all_method(self): return "M2 b"
def all_method(self): return "M2 b"
9,635
def all_method(self): return "M2 b"
def all_method(self): return "M2 b"
9,636
def all_method(self): return "M3 b"
def all_method(self): return "M3 b"
9,637
def boo(self): return "C"
def boo(self): return "C"
9,638
def slotspecials(): if verbose: print "Testing __dict__ and __weakref__ in __slots__..." class D(object): __slots__ = ["__dict__"] a = D() verify(hasattr(a, "__dict__")) verify(not hasattr(a, "__weakref__")) a.foo = 42 vereq(a.__dict__, {"foo": 42}) class W(object): __slots__ = ["__weakref__"] a = W() verify(hasattr(a, "__weakref__")) verify(not hasattr(a, "__dict__")) try: a.foo = 42 except AttributeError: pass else: raise TestFailed, "shouldn't be allowed to set a.foo" class C1(W, D): __slots__ = [] a = C1() verify(hasattr(a, "__dict__")) verify(hasattr(a, "__weakref__")) a.foo = 42 vereq(a.__dict__, {"foo": 42}) class C2(D, W): __slots__ = [] a = C2() verify(hasattr(a, "__dict__")) verify(hasattr(a, "__weakref__")) a.foo = 42 vereq(a.__dict__, {"foo": 42}) class C3(C1, C2): __slots__ = [] class C4(C2, C1): __slots__ = []
def slotspecials(): if verbose: print "Testing __dict__ and __weakref__ in __slots__..." class D(object): __slots__ = ["__dict__"] a = D() verify(hasattr(a, "__dict__")) verify(not hasattr(a, "__weakref__")) a.foo = 42 vereq(a.__dict__, {"foo": 42}) class W(object): __slots__ = ["__weakref__"] a = W() verify(hasattr(a, "__weakref__")) verify(not hasattr(a, "__dict__")) try: a.foo = 42 except AttributeError: pass else: raise TestFailed, "shouldn't be allowed to set a.foo" class C1(W, D): __slots__ = [] a = C1() verify(hasattr(a, "__dict__")) verify(hasattr(a, "__weakref__")) a.foo = 42 vereq(a.__dict__, {"foo": 42}) class C2(D, W): __slots__ = [] a = C2() verify(hasattr(a, "__dict__")) verify(hasattr(a, "__weakref__")) a.foo = 42 vereq(a.__dict__, {"foo": 42})
9,639
def mro(cls): L = type.mro(cls) L.reverse() return L
def mro(cls): L = type.mro(cls) L.reverse() return L
9,640
def testboth(formatstr, *args): testformat(formatstr, *args) testformat(unicode(formatstr), *args)
def testboth(formatstr, *args): testformat(formatstr, *args) testformat(unicode(formatstr), *args)
9,641
def msg(str): sys.stderr.write(str + '\n')
def msg(str): sys.stderr.write(str + '\n')
9,642
def _run_child(self, cmd): if isinstance(cmd, types.StringTypes): cmd = ['/bin/sh', '-c', cmd] for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1)
def _run_child(self, cmd): if isinstance(cmd, types.StringTypes): cmd = ['/bin/sh', '-c', cmd] for i in range(3, MAXFD): try: os.close(i) except OSError: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1)
9,643
>>> def gencopy(iterator):
>>> def gencopy(iterator):
9,644
def is_pure (self): return (self.has_pure_modules() and not self.has_ext_modules() and not self.has_c_libraries())
def is_pure (self): return (self.has_pure_modules() and not self.has_ext_modules() and not self.has_c_libraries())
9,645
def _StandardPutFile(prompt, default=None): args = {} flags = 0x57 if prompt: args['message'] = prompt args['preferenceKey'] = 'PyMC' if _movablemodal: args['eventProc'] = None try: rr = Nav.NavPutFile(args) good = 1 except Nav.error, arg: good = 0 fss = macfs.FSSpec(':cancelled') else: fss = rr.selection[0] return fss, good
def _StandardPutFile(prompt, default=None): args = {} flags = 0x07 if prompt: args['message'] = prompt args['preferenceKey'] = 'PyMC' if _movablemodal: args['eventProc'] = None try: rr = Nav.NavPutFile(args) good = 1 except Nav.error, arg: good = 0 fss = macfs.FSSpec(':cancelled') else: fss = rr.selection[0] return fss, good
9,646
def _SetFolder(folder): global _curfolder if _curfolder: rv = _curfolder else: _curfolder = macfs.FSSpec(":") _curfolder = macfs.FSSpec(folder) return rv
def _SetFolder(folder): global _curfolder if _curfolder: rv = _curfolder else: rv = None _curfolder = macfs.FSSpec(folder) return rv
9,647
def _GetDirectory(prompt=None): args = {} flags = 0x57 if prompt: args['message'] = prompt args['preferenceKey'] = 'PyMC' if _movablemodal: args['eventProc'] = None try: rr = Nav.NavChooseFolder(args) good = 1 except Nav.error, arg: good = 0 fss = macfs.FSSpec(':cancelled') else: fss = rr.selection[0] return fss, good
def _GetDirectory(prompt=None): args = {} flags = 0x17 if prompt: args['message'] = prompt args['preferenceKey'] = 'PyMC' if _movablemodal: args['eventProc'] = None try: rr = Nav.NavChooseFolder(args) good = 1 except Nav.error, arg: good = 0 fss = macfs.FSSpec(':cancelled') else: fss = rr.selection[0] return fss, good
9,648
def test_pnm(h, f): # PBM, PGM, PPM (portable {bit,gray,pix}map; together portable anymap) if h[0] == 'P' and h[1] in '123456' and h[2] in ' \t\n\r': return 'pnm'
def test_pnm(h, f): # PBM, PGM, PPM (portable {bit,gray,pix}map; together portable anymap) if len(h) >= 3 and \ h[0] == 'P' and h[1] in '123456' and h[2] in ' \t\n\r': return 'pnm'
9,649
def build_extensions(self):
def build_extensions(self):
9,650
def __init__(self, input_charset=DEFAULT_CHARSET): # RFC 2046, $4.1.2 says charsets are not case sensitive input_charset = input_charset.lower() # Set the input charset after filtering through the aliases self.input_charset = ALIASES.get(input_charset, input_charset) # We can try to guess which encoding and conversion to use by the # charset_map dictionary. Try that first, but let the user override # it. henc, benc, conv = CHARSETS.get(self.input_charset, (SHORTEST, BASE64, None)) if not conv: conv = self.input_charset # Set the attributes, allowing the arguments to override the default. self.header_encoding = henc self.body_encoding = benc self.output_charset = ALIASES.get(conv, conv) # Now set the codecs. If one isn't defined for input_charset, # guess and try a Unicode codec with the same name as input_codec. self.input_codec = CODEC_MAP.get(self.input_charset, self.input_charset) self.output_codec = CODEC_MAP.get(self.output_charset, self.output_charset)
def __init__(self, input_charset=DEFAULT_CHARSET): # RFC 2046, $4.1.2 says charsets are not case sensitive input_charset = unicode(input_charset, 'ascii').lower() # Set the input charset after filtering through the aliases self.input_charset = ALIASES.get(input_charset, input_charset) # We can try to guess which encoding and conversion to use by the # charset_map dictionary. Try that first, but let the user override # it. henc, benc, conv = CHARSETS.get(self.input_charset, (SHORTEST, BASE64, None)) if not conv: conv = self.input_charset # Set the attributes, allowing the arguments to override the default. self.header_encoding = henc self.body_encoding = benc self.output_charset = ALIASES.get(conv, conv) # Now set the codecs. If one isn't defined for input_charset, # guess and try a Unicode codec with the same name as input_codec. self.input_codec = CODEC_MAP.get(self.input_charset, self.input_charset) self.output_codec = CODEC_MAP.get(self.output_charset, self.output_charset)
9,651
def c2py(plural): """ Gets a C expression as used in PO files for plural forms and returns a Python lambda function that implements an equivalent expression. """ # Security check, allow only the "n" identifier from StringIO import StringIO import token, tokenize tokens = tokenize.generate_tokens(StringIO(plural).readline) danger = [ x for x in tokens if x[0] == token.NAME and x[1] != 'n' ] if danger: raise ValueError, 'dangerous expression' # Replace some C operators by their Python equivalents plural = plural.replace('&&', ' and ') plural = plural.replace('||', ' or ') expr = re.compile(r'\![^=]') plural = expr.sub(' not ', plural) # Regular expression and replacement function used to transform # "a?b:c" to "test(a,b,c)". expr = re.compile(r'(.*?)\?(.*?):(.*)') def repl(x): return "test(%s, %s, %s)" % (x.group(1), x.group(2), expr.sub(repl, x.group(3))) # Code to transform the plural expression, taking care of parentheses stack = [''] for c in plural: if c == '(': stack.append('') elif c == ')': if len(stack) == 0: raise ValueError, 'unbalanced parenthesis in plural form' s = expr.sub(repl, stack.pop()) stack[-1] += '(%s)' % s else: stack[-1] += c plural = expr.sub(repl, stack.pop()) return eval('lambda n: int(%s)' % plural)
def c2py(plural): """ Gets a C expression as used in PO files for plural forms and returns a Python lambda function that implements an equivalent expression. """ # Security check, allow only the "n" identifier from StringIO import StringIO import token, tokenize tokens = tokenize.generate_tokens(StringIO(plural).readline) try: danger = [ x for x in tokens if x[0] == token.NAME and x[1] != 'n' ] except tokenize.TokenError: raise ValueError, \ 'plural forms expression error, maybe unbalanced parenthesis' else: if danger: raise ValueError, 'plural forms expression could be dangerous' # Replace some C operators by their Python equivalents plural = plural.replace('&&', ' and ') plural = plural.replace('||', ' or ') expr = re.compile(r'\![^=]') plural = expr.sub(' not ', plural) # Regular expression and replacement function used to transform # "a?b:c" to "test(a,b,c)". expr = re.compile(r'(.*?)\?(.*?):(.*)') def repl(x): return "test(%s, %s, %s)" % (x.group(1), x.group(2), expr.sub(repl, x.group(3))) # Code to transform the plural expression, taking care of parentheses stack = [''] for c in plural: if c == '(': stack.append('') elif c == ')': if len(stack) == 0: raise ValueError, 'unbalanced parenthesis in plural form' s = expr.sub(repl, stack.pop()) stack[-1] += '(%s)' % s else: stack[-1] += c plural = expr.sub(repl, stack.pop()) return eval('lambda n: int(%s)' % plural)
9,652
def c2py(plural): """ Gets a C expression as used in PO files for plural forms and returns a Python lambda function that implements an equivalent expression. """ # Security check, allow only the "n" identifier from StringIO import StringIO import token, tokenize tokens = tokenize.generate_tokens(StringIO(plural).readline) danger = [ x for x in tokens if x[0] == token.NAME and x[1] != 'n' ] if danger: raise ValueError, 'dangerous expression' # Replace some C operators by their Python equivalents plural = plural.replace('&&', ' and ') plural = plural.replace('||', ' or ') expr = re.compile(r'\![^=]') plural = expr.sub(' not ', plural) # Regular expression and replacement function used to transform # "a?b:c" to "test(a,b,c)". expr = re.compile(r'(.*?)\?(.*?):(.*)') def repl(x): return "test(%s, %s, %s)" % (x.group(1), x.group(2), expr.sub(repl, x.group(3))) # Code to transform the plural expression, taking care of parentheses stack = [''] for c in plural: if c == '(': stack.append('') elif c == ')': if len(stack) == 0: raise ValueError, 'unbalanced parenthesis in plural form' s = expr.sub(repl, stack.pop()) stack[-1] += '(%s)' % s else: stack[-1] += c plural = expr.sub(repl, stack.pop()) return eval('lambda n: int(%s)' % plural)
def c2py(plural): """ Gets a C expression as used in PO files for plural forms and returns a Python lambda function that implements an equivalent expression. """ # Security check, allow only the "n" identifier from StringIO import StringIO import token, tokenize tokens = tokenize.generate_tokens(StringIO(plural).readline) danger = [ x for x in tokens if x[0] == token.NAME and x[1] != 'n' ] if danger: raise ValueError, 'dangerous expression' # Replace some C operators by their Python equivalents plural = plural.replace('&&', ' and ') plural = plural.replace('||', ' or ') expr = re.compile(r'\!([^=])') plural = expr.sub(' not \\1', plural) # Regular expression and replacement function used to transform # "a?b:c" to "test(a,b,c)". expr = re.compile(r'(.*?)\?(.*?):(.*)') def repl(x): return "test(%s, %s, %s)" % (x.group(1), x.group(2), expr.sub(repl, x.group(3))) # Code to transform the plural expression, taking care of parentheses stack = [''] for c in plural: if c == '(': stack.append('') elif c == ')': if len(stack) == 0: raise ValueError, 'unbalanced parenthesis in plural form' s = expr.sub(repl, stack.pop()) stack[-1] += '(%s)' % s else: stack[-1] += c plural = expr.sub(repl, stack.pop()) return eval('lambda n: int(%s)' % plural)
9,653
def repl(x): return "test(%s, %s, %s)" % (x.group(1), x.group(2), expr.sub(repl, x.group(3)))
def repl(x): return "test(%s, %s, %s)" % (x.group(1), x.group(2), expr.sub(repl, x.group(3)))
9,654
def _parse(self, fp): """Override this method to support alternative .mo formats.""" 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] 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) # 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]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < buflen and tend < buflen: msg = buf[moff:mend] tmsg = buf[toff:tend] if msg.find('\x00') >= 0: # Plural forms msgid1, msgid2 = msg.split('\x00') tmsg = tmsg.split('\x00') for i in range(len(tmsg)): catalog[(msgid1, i)] = tmsg[i] else: catalog[msg] = 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] elif k == 'plural-forms': v = v.split(';')
def _parse(self, fp): """Override this method to support alternative .mo formats.""" 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] 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) # 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]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < buflen and tend < buflen: msg = buf[moff:mend] tmsg = buf[toff:tend] if msg.find('\x00') >= 0: # Plural forms msgid1, msgid2 = msg.split('\x00') tmsg = tmsg.split('\x00') for i in range(len(tmsg)): catalog[(msgid1, i)] = tmsg[i] else: catalog[msg] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0: # 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] elif k == 'plural-forms': v = v.split(';')
9,655
def main(): if len(sys.argv) != 2: sys.stderr.write('usage: telnet hostname\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect(host, port) except error, msg: sys.stderr.write('connect failed: ' + `msg` + '\n') sys.exit(1) # thread.start_new(child, (s,)) parent(s)
def main(): if len(sys.argv) < 2: sys.stderr.write('usage: telnet hostname [port]\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect(host, port) except error, msg: sys.stderr.write('connect failed: ' + `msg` + '\n') sys.exit(1) # thread.start_new(child, (s,)) parent(s)
9,656
def main(): if len(sys.argv) != 2: sys.stderr.write('usage: telnet hostname\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect(host, port) except error, msg: sys.stderr.write('connect failed: ' + `msg` + '\n') sys.exit(1) # thread.start_new(child, (s,)) parent(s)
def main(): if len(sys.argv) != 2: sys.stderr.write('usage: telnet hostname\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect((host, port)) except error, msg: sys.stderr.write('connect failed: ' + `msg` + '\n') sys.exit(1) # thread.start_new(child, (s,)) parent(s)
9,657
# dlltool --dllname python15.dll --def python15.def \
# dlltool --dllname python15.dll --def python15.def \
9,658
# dlltool --dllname python15.dll --def python15.def \
# dlltool --dllname python15.dll --def python15.def \
9,659
def __init__ (self, verbose=0, dry_run=0, force=0):
def __init__ (self, verbose=0, dry_run=0, force=0):
9,660
def __init__ (self, verbose=0, dry_run=0, force=0):
def __init__ (self, verbose=0, dry_run=0, force=0):
9,661
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None): # use separate copies, so can modify the lists extra_preargs = list(extra_preargs or []) libraries = list(libraries or []) # Additional libraries libraries.extend(self.dll_libraries) # we want to put some files in the same directory as the # object files are, build_temp doesn't help much
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None): # use separate copies, so can modify the lists extra_preargs = copy.copy(extra_preargs or []) libraries = copy.copy(libraries or []) # Additional libraries libraries.extend(self.dll_libraries) # we want to put some files in the same directory as the # object files are, build_temp doesn't help much
9,662
def check_config_h(): """Checks if the GCC compiler is mentioned in config.h. If it is not, compiling probably doesn't work. """ # return values # 2: OK, python was compiled with GCC # 1: OK, python's config.h mentions __GCC__ # 0: uncertain, because we couldn't check it # -1: probably not OK, because we didn't found it in config.h # You could check check_config_h()>0 => OK from distutils import sysconfig import string,sys # if sys.version contains GCC then python was compiled with # GCC, and the config.h file should be OK if -1 == string.find(sys.version,"GCC"): pass # go to the next test else: return 2 try: # It would probably better to read single lines to search. # But we do this only once, and it is fast enough f=open(sysconfig.get_config_h_filename()) s=f.read() f.close() # is somewhere a #ifdef __GNUC__ or something similar if -1 == string.find(s,"__GNUC__"): return -1 else: return 1 except IOError: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing pass return 0
def check_config_h(): """Checks if the GCC compiler is mentioned in config.h. If it is not, compiling probably doesn't work. """ # return values # 2: OK, python was compiled with GCC # 1: OK, python's config.h mentions __GCC__ # 0: uncertain, because we couldn't check it # -1: probably not OK, because we didn't found it in config.h # You could check check_config_h()>0 => OK from distutils import sysconfig import string,sys # if sys.version contains GCC then python was compiled with # GCC, and the config.h file should be OK if -1 == string.find(sys.version,"GCC"): pass # go to the next test else: return 2 try: # It would probably better to read single lines to search. # But we do this only once, and it is fast enough f=open(sysconfig.get_config_h_filename()) s=f.read() f.close() # is somewhere a #ifdef __GNUC__ or something similar if -1 == string.find(s,"__GNUC__"): return -1 else: return 1 except IOError: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing pass return 0
9,663
def check_config_h(): """Checks if the GCC compiler is mentioned in config.h. If it is not, compiling probably doesn't work. """ # return values # 2: OK, python was compiled with GCC # 1: OK, python's config.h mentions __GCC__ # 0: uncertain, because we couldn't check it # -1: probably not OK, because we didn't found it in config.h # You could check check_config_h()>0 => OK from distutils import sysconfig import string,sys # if sys.version contains GCC then python was compiled with # GCC, and the config.h file should be OK if -1 == string.find(sys.version,"GCC"): pass # go to the next test else: return 2 try: # It would probably better to read single lines to search. # But we do this only once, and it is fast enough f=open(sysconfig.get_config_h_filename()) s=f.read() f.close() # is somewhere a #ifdef __GNUC__ or something similar if -1 == string.find(s,"__GNUC__"): return -1 else: return 1 except IOError: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing pass return 0
def check_config_h(): """Checks if the GCC compiler is mentioned in config.h. If it is not, compiling probably doesn't work. """ # return values # 2: OK, python was compiled with GCC # 1: OK, python's config.h mentions __GCC__ # 0: uncertain, because we couldn't check it # -1: probably not OK, because we didn't found it in config.h # You could check check_config_h()>0 => OK from distutils import sysconfig import string,sys # if sys.version contains GCC then python was compiled with # GCC, and the config.h file should be OK if -1 == string.find(sys.version,"GCC"): pass # go to the next test else: return "OK, python was compiled with GCC" try: # It would probably better to read single lines to search. # But we do this only once, and it is fast enough f=open(sysconfig.get_config_h_filename()) s=f.read() f.close() # is somewhere a #ifdef __GNUC__ or something similar if -1 == string.find(s,"__GNUC__"): return -1 else: return 1 except IOError: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing pass return 0
9,664
# is somewhere a #ifdef __GNUC__ or something similar
# is somewhere a #ifdef __GNUC__ or something similar
9,665
# is somewhere a #ifdef __GNUC__ or something similar
# is somewhere a #ifdef __GNUC__ or something similar
9,666
def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER.
def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER.
9,667
def __init__(self, master=None, cnf={}, **kw): """Construct a label widget with the parent MASTER.
def __init__(self, master=None, cnf={}, **kw): """Construct a label widget with the parent MASTER.
9,668
def set(self, *args): """Set the fractional values of the slider position (upper and lower ends as value between 0 and 1).""" self.tk.call((self._w, 'set') + args)
def set(self, *args): """Set the fractional values of the slider position (upper and lower ends as value between 0 and 1).""" self.tk.call((self._w, 'set') + args)
9,669
def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER.
def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER.
9,670
def printsum(filename, out = sys.stdout): try: fp = open(filename, rmode) except IOError, msg: sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg)) return 1 if fnfilter: filename = fnfilter(filename) sts = printsumfp(fp, filename, out) fp.close() return sts
def printsum(filename, out=sys.stdout): try: fp = open(filename, rmode) except IOError, msg: sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg)) return 1 if fnfilter: filename = fnfilter(filename) sts = printsumfp(fp, filename, out) fp.close() return sts
9,671
def printsumfp(fp, filename, out = sys.stdout): m = md5.new() try: while 1: data = fp.read(bufsize) if not data: break m.update(data) except IOError, msg: sys.stderr.write('%s: I/O error: %s\n' % (filename, msg)) return 1 out.write('%s %s\n' % (m.hexdigest(), filename)) return 0
def printsumfp(fp, filename, out=sys.stdout): m = md5.new() try: while 1: data = fp.read(bufsize) if not data: break m.update(data) except IOError, msg: sys.stderr.write('%s: I/O error: %s\n' % (filename, msg)) return 1 out.write('%s %s\n' % (m.hexdigest(), filename)) return 0
9,672
def printsumfp(fp, filename, out = sys.stdout): m = md5.new() try: while 1: data = fp.read(bufsize) if not data: break m.update(data) except IOError, msg: sys.stderr.write('%s: I/O error: %s\n' % (filename, msg)) return 1 out.write('%s %s\n' % (m.hexdigest(), filename)) return 0
def printsumfp(fp, filename, out = sys.stdout): m = md5.new() try: while 1: data = fp.read(bufsize) if not data: break m.update(data) except IOError, msg: sys.stderr.write('%s: I/O error: %s\n' % (filename, msg)) return 1 out.write('%s %s\n' % (m.hexdigest(), filename)) return 0
9,673
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t': rmode = 'r' if o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
def main(args = sys.argv[1:], out=sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t': rmode = 'r' if o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
9,674
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t': rmode = 'r' if o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename elif o == '-b': rmode = 'rb' if o == '-t': rmode = 'r' if o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
9,675
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t': rmode = 'r' if o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' elif o == '-t': rmode = 'r' if o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
9,676
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t': rmode = 'r' if o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
def main(args = sys.argv[1:], out = sys.stdout): global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') except getopt.error, msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: if o == '-l': fnfilter = os.path.basename if o == '-b': rmode = 'rb' if o == '-t': rmode = 'r' elif o == '-s': bufsize = int(a) if not args: args = ['-'] return sum(args, out)
9,677
def _get_time_times(timer=os.times): t = timer() return t[0] + t[1]
def _get_time_times(timer=os.times): t = timer() return t[0] + t[1]
9,678
def _get_time_times(timer=os.times): t = timer() return t[0] + t[1]
def _get_time_times(timer=os.times): t = timer() return t[0] + t[1]
9,679
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatch_return(rframe, 0) if self.cur and frame.f_back is not self.cur[4]: raise "Bad call[2]", self.cur[3] fcode = frame.f_code fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) self.cur = (t, 0, 0, fn, frame, self.cur) timings = self.timings if timings.has_key(fn): cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {} return 1
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[-2]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatch_return(rframe, 0) if self.cur and frame.f_back is not self.cur[-2]: raise "Bad call[2]", self.cur[3] fcode = frame.f_code fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) self.cur = (t, 0, 0, fn, frame, self.cur) timings = self.timings if timings.has_key(fn): cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {} return 1
9,680
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatch_return(rframe, 0) if self.cur and frame.f_back is not self.cur[4]: raise "Bad call[2]", self.cur[3] fcode = frame.f_code fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) self.cur = (t, 0, 0, fn, frame, self.cur) timings = self.timings if timings.has_key(fn): cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {} return 1
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[-3] self.trace_dispatch_return(rframe, 0) if self.cur and frame.f_back is not self.cur[4]: raise "Bad call[2]", self.cur[3] fcode = frame.f_code fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) self.cur = (t, 0, 0, fn, frame, self.cur) timings = self.timings if timings.has_key(fn): cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {} return 1
9,681
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatch_return(rframe, 0) if self.cur and frame.f_back is not self.cur[4]: raise "Bad call[2]", self.cur[3] fcode = frame.f_code fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) self.cur = (t, 0, 0, fn, frame, self.cur) timings = self.timings if timings.has_key(fn): cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {} return 1
def trace_dispatch_call(self, frame, t): if self.cur and frame.f_back is not self.cur[4]: rt, rtt, rct, rfn, rframe, rcur = self.cur if not isinstance(rframe, Profile.fake_frame): if rframe.f_back is not frame.f_back: print rframe, rframe.f_back print frame, frame.f_back raise "Bad call", self.cur[3] self.trace_dispatch_return(rframe, 0) if self.cur and frame.f_back is not self.cur[-2]: raise "Bad call[2]", self.cur[-3] fcode = frame.f_code fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) self.cur = (t, 0, 0, fn, frame, self.cur) timings = self.timings if timings.has_key(fn): cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {} return 1
9,682
def trace_dispatch_return(self, frame, t): if frame is not self.cur[4]: if frame is self.cur[4].f_back: self.trace_dispatch_return(self.cur[4], 0) else: raise "Bad return", self.cur[3]
def trace_dispatch_return(self, frame, t): if frame is not self.cur[-2]: if frame is self.cur[-2].f_back: self.trace_dispatch_return(self.cur[-2], 0) else: raise "Bad return", self.cur[3]
9,683
def trace_dispatch_return(self, frame, t): if frame is not self.cur[4]: if frame is self.cur[4].f_back: self.trace_dispatch_return(self.cur[4], 0) else: raise "Bad return", self.cur[3]
def trace_dispatch_return(self, frame, t): if frame is not self.cur[4]: if frame is self.cur[4].f_back: self.trace_dispatch_return(self.cur[4], 0) else: raise "Bad return", self.cur[3]
9,684
def set_cmd(self, cmd): if self.cur[5]: return # already set self.cmd = cmd self.simulate_call(cmd)
def set_cmd(self, cmd): if self.cur[-1]: return # already set self.cmd = cmd self.simulate_call(cmd)
9,685
def simulate_call(self, name): code = self.fake_code('profile', 0, name) if self.cur: pframe = self.cur[4] else: pframe = None frame = self.fake_frame(code, pframe) a = self.dispatch['call'](self, frame, 0) return
def simulate_call(self, name): code = self.fake_code('profile', 0, name) if self.cur: pframe = self.cur[-2] else: pframe = None frame = self.fake_frame(code, pframe) a = self.dispatch['call'](self, frame, 0) return
9,686
def simulate_cmd_complete(self): get_time = self.get_time t = get_time() - self.t while self.cur[5]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self, self.cur[4], t) t = 0 self.t = get_time() - t
def simulate_cmd_complete(self): get_time = self.get_time t = get_time() - self.t while self.cur[-1]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self, self.cur[4], t) t = 0 self.t = get_time() - t
9,687
def simulate_cmd_complete(self): get_time = self.get_time t = get_time() - self.t while self.cur[5]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self, self.cur[4], t) t = 0 self.t = get_time() - t
def simulate_cmd_complete(self): get_time = self.get_time t = get_time() - self.t while self.cur[5]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self, self.cur[-2], t) t = 0 self.t = get_time() - t
9,688
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
9,689
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
9,690
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): compile_dir(fullname, maxlevels - 1, dfile, force) return success
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): compile_dir(fullname, maxlevels - 1, dfile, force) return success
9,691
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): compile_dir(fullname, maxlevels - 1, dfile, force) return success
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: ok = py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): compile_dir(fullname, maxlevels - 1, dfile, force) return success
9,692
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): compile_dir(fullname, maxlevels - 1, dfile, force) return success
def compile_dir(dir, maxlevels=10, ddir=None, force=0): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): if not compile_dir(fullname, maxlevels - 1, dfile, force, rx): success = 0 return success
9,693
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:x:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
9,694
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: python compileall.py [-l] [-f] [-d destdir] " \ "[-s regexp] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
9,695
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print " if no directory arguments, -l sys.path is assumed" print "-x regexp: skip files matching the regular expression regexp" print " the regexp is search for in the full path of the file" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
9,696
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: if not compile_dir(dir, maxlevels, ddir, force, rx): success = 0 else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
9,697
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
9,698
def test_file(self): TESTFN = test_support.TESTFN f = open(TESTFN, 'w') try: f.write('hi there\n') f.close() urls = [ 'file:'+sanepathname2url(os.path.abspath(TESTFN)),
def test_file(self): TESTFN = test_support.TESTFN f = open(TESTFN, 'w') try: f.write('hi there\n') f.close() urls = [ 'file:'+sanepathname2url(os.path.abspath(TESTFN)),
9,699