rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
db.readfp(f) return db.types_map | db.readfp(f, True) return db.types_map[True] | def read_mime_types(file): try: f = open(file) except IOError: return None db = MimeTypes() db.readfp(f) return db.types_map |
codecs.StreamReader.__init__(self,strict,errors) | codecs.StreamReader.__init__(self,stream,errors) | def __init__(self,stream,errors='strict',mapping=None): |
if optional and len(params) == 1: line = line[m.end():] else: | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
|
if optional and type(params[0]) is type(()): | if optional and type(params[0]) is TupleType: | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
if type(attrname) is type(""): | if type(attrname) is StringType: | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
elif type(attrname) is type(()): | elif type(attrname) is TupleType: | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
elif type(attrname) is type([]): | elif type(attrname) is ListType: | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
dbgmsg("subconvert() ==> " + `line[:20]`) | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
|
if params and type(params[-1]) is type('') \ | if params and type(params[-1]) is StringType \ | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
and type(conversion) is not type(""): | and type(conversion) is not StringType: | def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) 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 self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) 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] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: if optional and len(params) == 1: 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 pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) 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():] self.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) pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.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: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] dbgmsg("subconvert() ==> " + `line[:20]`) popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % 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" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is type('') \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not type(""): # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.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)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here... |
dummy, fp = os.popen4(cmd, "r") dummy.close() | child = popen2.Popen4(cmd) child.tochild.close() | def _cmd(self, output, dir, *cmditems): """Internal routine to run a shell command in a given directory.""" cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems) if output: output.write("+ %s\n" % cmd) if NO_EXECUTE: return 0 dummy, fp = os.popen4(cmd, "r") dummy.close() while 1: line = fp.readline() if not line: break if output: output.write(line) rv = fp.close() return rv |
line = fp.readline() | line = child.fromchild.readline() | def _cmd(self, output, dir, *cmditems): """Internal routine to run a shell command in a given directory.""" cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems) if output: output.write("+ %s\n" % cmd) if NO_EXECUTE: return 0 dummy, fp = os.popen4(cmd, "r") dummy.close() while 1: line = fp.readline() if not line: break if output: output.write(line) rv = fp.close() return rv |
rv = fp.close() return rv | return child.wait() | def _cmd(self, output, dir, *cmditems): """Internal routine to run a shell command in a given directory.""" cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems) if output: output.write("+ %s\n" % cmd) if NO_EXECUTE: return 0 dummy, fp = os.popen4(cmd, "r") dummy.close() while 1: line = fp.readline() if not line: break if output: output.write(line) rv = fp.close() return rv |
return "install %s: running \"%s\" failed" % self.fullname() | return "install %s: running \"%s\" failed" % \ (self.fullname(), installcmd) | def installPackageOnly(self, output=None): """Install a single source package. If output is given it should be a file-like object and it will receive a log of what happened.""" if self._dict.has_key('Pre-install-command'): if self._cmd(output, self._buildDirname, self._dict['Pre-install-command']): return "pre-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Pre-install-command']) self.beforeInstall() installcmd = self._dict.get('Install-command') if not installcmd: installcmd = '"%s" setup.py install' % sys.executable if self._cmd(output, self._buildDirname, installcmd): return "install %s: running \"%s\" failed" % self.fullname() self.afterInstall() if self._dict.has_key('Post-install-command'): if self._cmd(output, self._buildDirname, self._dict['Post-install-command']): return "post-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Post-install-command']) return None |
except error_proto(val): | except error_proto, val: | def quit(self): """Signoff: commit changes on server, unlock mailbox, close connection.""" try: resp = self._shortcmd('QUIT') except error_proto(val): resp = val self.file.close() self.sock.close() del self.file, self.sock return resp |
strip_dir=python_build, | strip_dir=0, | def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): """Process arguments and decide which source files to compile. |
objects = self.object_filenames(sources, strip_dir=python_build, output_dir=output_dir) | objects = self.object_filenames(sources, output_dir=output_dir) | def _prep_compile(self, sources, output_dir, depends=None): """Decide which souce files must be recompiled. |
_platform_cache = None _platform_aliased_cache = None | _platform_cache = {True:None, False:None} _platform_aliased_cache = {True:None, False:None} | def python_compiler(): """ Returns a string identifying the compiler used for compiling Python. """ return _sys_version()[3] |
if not aliased and (_platform_cache is not None): return _platform_cache elif _platform_aliased_cache is not None: return _platform_aliased_cache | if not aliased and (_platform_cache[bool(terse)] is not None): return _platform_cache[bool(terse)] elif _platform_aliased_cache[bool(terse)] is not None: return _platform_aliased_cache[bool(terse)] | def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache is not None): return _platform_cache elif _platform_aliased_cache is not None: return _platform_aliased_cache # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache = platform elif terse: pass else: _platform_cache = platform return platform |
_platform_aliased_cache = platform | _platform_aliased_cache[bool(terse)] = platform | def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache is not None): return _platform_cache elif _platform_aliased_cache is not None: return _platform_aliased_cache # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache = platform elif terse: pass else: _platform_cache = platform return platform |
_platform_cache = platform | _platform_cache[bool(terse)] = platform | def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache is not None): return _platform_cache elif _platform_aliased_cache is not None: return _platform_aliased_cache # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache = platform elif terse: pass else: _platform_cache = platform return platform |
ok_sys_names = ('ps1', 'ps2', 'copyright', 'version', | ok_sys_names = ('ps1', 'ps2', 'copyright', 'version', 'hexversion', | def default_path(self): return self.rexec.modules['sys'].path |
if cache.has_key(path): return cache[path] cache[path] = ret = os.stat(path) | ret = cache.get(path, None) if ret is None: cache[path] = ret = _os.stat(path) | def stat(path): """Stat a file, possibly out of the cache.""" if cache.has_key(path): return cache[path] cache[path] = ret = os.stat(path) return ret |
def reset(): """Reset the cache completely.""" global cache cache = {} | def reset(): """Reset the cache completely.""" global cache cache = {} |
|
if cache.has_key(path): | try: | def forget(path): """Remove a given item from the cache, if it exists.""" if cache.has_key(path): del cache[path] |
except KeyError: pass | def forget(path): """Remove a given item from the cache, if it exists.""" if cache.has_key(path): del cache[path] |
|
n = len(prefix) | def forget_prefix(prefix): """Remove all pathnames with a given prefix.""" n = len(prefix) for path in cache.keys(): if path[:n] == prefix: del cache[path] |
|
if path[:n] == prefix: del cache[path] | if path.startswith(prefix): forget(path) | def forget_prefix(prefix): """Remove all pathnames with a given prefix.""" n = len(prefix) for path in cache.keys(): if path[:n] == prefix: del cache[path] |
if prefix[-1:] == '/' and prefix != '/': prefix = prefix[:-1] | from os.path import split, join prefix = split(join(prefix, "xxx"))[0] | def forget_dir(prefix): """Forget about a directory and all entries in it, but not about entries in subdirectories.""" if prefix[-1:] == '/' and prefix != '/': prefix = prefix[:-1] forget(prefix) if prefix[-1:] != '/': prefix = prefix + '/' n = len(prefix) for path in cache.keys(): if path[:n] == prefix: rest = path[n:] if rest[-1:] == '/': rest = rest[:-1] if '/' not in rest: del cache[path] |
if prefix[-1:] != '/': prefix = prefix + '/' n = len(prefix) | def forget_dir(prefix): """Forget about a directory and all entries in it, but not about entries in subdirectories.""" if prefix[-1:] == '/' and prefix != '/': prefix = prefix[:-1] forget(prefix) if prefix[-1:] != '/': prefix = prefix + '/' n = len(prefix) for path in cache.keys(): if path[:n] == prefix: rest = path[n:] if rest[-1:] == '/': rest = rest[:-1] if '/' not in rest: del cache[path] |
|
if path[:n] == prefix: rest = path[n:] if rest[-1:] == '/': rest = rest[:-1] if '/' not in rest: del cache[path] | if path.startswith(prefix) and split(path)[0] == prefix: forget(path) | def forget_dir(prefix): """Forget about a directory and all entries in it, but not about entries in subdirectories.""" if prefix[-1:] == '/' and prefix != '/': prefix = prefix[:-1] forget(prefix) if prefix[-1:] != '/': prefix = prefix + '/' n = len(prefix) for path in cache.keys(): if path[:n] == prefix: rest = path[n:] if rest[-1:] == '/': rest = rest[:-1] if '/' not in rest: del cache[path] |
Normally used with prefix = '/' after a chdir().""" n = len(prefix) | Normally used with prefix = '/' after a chdir(). """ | def forget_except_prefix(prefix): """Remove all pathnames except with a given prefix. Normally used with prefix = '/' after a chdir().""" n = len(prefix) for path in cache.keys(): if path[:n] != prefix: del cache[path] |
if path[:n] != prefix: del cache[path] | if not path.startswith(prefix): forget(path) | def forget_except_prefix(prefix): """Remove all pathnames except with a given prefix. Normally used with prefix = '/' after a chdir().""" n = len(prefix) for path in cache.keys(): if path[:n] != prefix: del cache[path] |
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def date_time(self): """Return the current date and time formatted for a MIME header.""" year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time()) s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss) return s | def getSubject(self, record): """ Determine the subject for the email. |
|
self.date_time(), msg) | formatdate(), msg) | def emit(self, record): """ Emit a record. |
print 'XXX', (_function, (_object,), _parameters) | def callback_wrapper(self, _request, _reply): _parameters, _attributes = aetools.unpackevent(_request) _class = _attributes['evcl'].type _type = _attributes['evid'].type if self.ae_handlers.has_key((_class, _type)): _function = self.ae_handlers[(_class, _type)] elif self.ae_handlers.has_key((_class, '****')): _function = self.ae_handlers[(_class, '****')] elif self.ae_handlers.has_key(('****', '****')): _function = self.ae_handlers[('****', '****')] else: raise 'Cannot happen: AE callback without handler', (_class, _type) # XXXX Do key-to-name mapping here _parameters['_attributes'] = _attributes _parameters['_class'] = _class _parameters['_type'] = _type if _parameters.has_key('----'): _object = _parameters['----'] del _parameters['----'] print 'XXX', (_function, (_object,), _parameters) try: rv = apply(_function, (_object,), _parameters) except TypeError, name: raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name) else: try: rv = apply(_function, (), _parameters) except TypeError, name: raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name) if rv == None: aetools.packevent(_reply, {}) else: aetools.packevent(_reply, {'----':rv}) |
|
des = "_%s__%s" % (klass.__name__, name) | des = "1" | def adaptgetter(name, klass, getter): kind, des = getter if kind == 1: # AV happens when stepping from this line to next if des == "": des = "_%s__%s" % (klass.__name__, name) return lambda obj: getattr(obj, des) |
print "20. eval with free variables" | print "20. eval and exec with free variables" | def adaptgetter(name, klass, getter): kind, des = getter if kind == 1: # AV happens when stepping from this line to next if des == "": des = "_%s__%s" % (klass.__name__, name) return lambda obj: getattr(obj, des) |
return apply(pow, params) | return pow(*params) | def _dispatch(self, method, params): if method == 'pow': return apply(pow, params) elif method == 'add': return params[0] + params[1] else: raise 'bad method' |
4. Subclass SimpleXMLRPCRequestHandler: class MathHandler(SimpleXMLRPCRequestHandler): | 4. Subclass SimpleXMLRPCServer: class MathServer(SimpleXMLRPCServer): | def _dispatch(self, method, params): if method == 'pow': return apply(pow, params) elif method == 'add': return params[0] + params[1] else: raise 'bad method' |
return apply(func, params) def log_message(self, format, *args): pass | return func(*params) | def _dispatch(self, method, params): try: # We are forcing the 'export_' prefix on methods that are # callable through XML-RPC to prevent potential security # problems func = getattr(self, 'export_' + method) except AttributeError: raise Exception('method "%s" is not supported' % method) else: return apply(func, params) |
server = SimpleXMLRPCServer(("localhost", 8000), MathHandler) | server = MathServer(("localhost", 8000)) | def export_add(self, x, y): return x + y |
import types import os def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj def list_public_methods(obj): """Returns a list of attribute strings, found in the specified object, which represent callable attributes""" return [member for member in dir(obj) if not member.startswith('_') and callable(getattr(obj, member))] def remove_duplicates(lst): """remove_duplicates([2,2,2,1,3,3]) => [3,1,2] Returns a copy of a list without duplicates. Every list item must be hashable and the order of the items in the resulting list is not defined. """ u = {} for x in lst: u[x] = 1 return u.keys() class SimpleXMLRPCDispatcher: """Mix-in class that dispatches XML-RPC requests. This class is used to register XML-RPC method handlers and then to dispatch them. There should never be any reason to instantiate this class directly. """ def __init__(self): self.funcs = {} self.instance = None def register_instance(self, instance): """Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and it's parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. """ self.instance = instance def register_function(self, function, name = None): """Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function. """ if name is None: name = function.__name__ self.funcs[name] = function def register_introspection_functions(self): """Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html """ self.funcs.update({'system.listMethods' : self.system_listMethods, 'system.methodSignature' : self.system_methodSignature, 'system.methodHelp' : self.system_methodHelp}) def register_multicall_functions(self): """Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208""" self.funcs.update({'system.multicall' : self.system_multicall}) def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the prefered means of changing method dispatch behavior. """ params, method = xmlrpclib.loads(data) try: if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) response = (response,) response = xmlrpclib.dumps(response, methodresponse=1) except Fault, fault: response = xmlrpclib.dumps(fault) except: response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)) ) return response def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = self.funcs.keys() if self.instance is not None: if hasattr(self.instance, '_listMethods'): methods = remove_duplicates( methods + self.instance._listMethods() ) elif not hasattr(self.instance, '_dispatch'): methods = remove_duplicates( methods + list_public_methods(self.instance) ) methods.sort() return methods def system_methodSignature(self, method_name): """system.methodSignature('add') => [double, int, int] Returns a list describing the signiture of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.""" return 'signatures not supported' def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.""" method = None if self.funcs.has_key(method_name): method = self.funcs[method_name] elif self.instance is not None: if hasattr(self.instance, '_methodHelp'): return self.instance._methodHelp(method_name) elif not hasattr(self.instance, '_dispatch'): try: method = resolve_dotted_attribute( self.instance, method_name ) except AttributeError: pass if method is None: return "" else: return pydoc.getdoc(method) def system_multicall(self, call_list): """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \ [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208 """ results = [] for call in call_list: method_name = call['methodName'] params = call['params'] try: results.append([self._dispatch(method_name, params)]) except Fault, fault: results.append( {'faultCode' : fault.faultCode, 'faultString' : fault.faultString} ) except: results.append( {'faultCode' : 1, 'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)} ) return results def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and it's parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. """ func = None try: func = self.funcs[method] except KeyError: if self.instance is not None: if hasattr(self.instance, '_dispatch'): return self.instance._dispatch(method, params) else: try: func = resolve_dotted_attribute( self.instance, method ) except AttributeError: pass if func is not None: return func(*params) else: raise Exception('method "%s" is not supported' % method) | def export_add(self, x, y): return x + y |
|
XML-RPC requests are dispatched to the _dispatch method, which may be overriden by subclasses. The default implementation attempts to dispatch XML-RPC calls to the functions or instance installed in the server. | def export_add(self, x, y): return x + y |
|
which are forwarded to the _dispatch method for handling. """ | which are forwarded to the server's _dispatch method for handling. """ | def do_POST(self): """Handles the HTTP POST request. |
params, method = xmlrpclib.loads(data) try: response = self._dispatch(method, params) response = (response,) except: response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)) ) else: response = xmlrpclib.dumps(response, methodresponse=1) except: | response = self.server._marshaled_dispatch( data, getattr(self, '_dispatch', None) ) except: | def do_POST(self): """Handles the HTTP POST request. |
def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and it's parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. """ func = None try: func = self.server.funcs[method] except KeyError: if self.server.instance is not None: if hasattr(self.server.instance, '_dispatch'): return self.server.instance._dispatch(method, params) else: try: func = _resolve_dotted_attribute( self.server.instance, method ) except AttributeError: pass if func is not None: return apply(func, params) else: raise Exception('method "%s" is not supported' % method) | def do_POST(self): """Handles the HTTP POST request. |
|
def _resolve_dotted_attribute(obj, attr): """Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj class SimpleXMLRPCServer(SocketServer.TCPServer): | class SimpleXMLRPCServer(SocketServer.TCPServer, SimpleXMLRPCDispatcher): | def log_request(self, code='-', size='-'): """Selectively log an accepted request.""" |
to be installed to handle requests. | to be installed to handle requests. The default implementation attempts to dispatch XML-RPC calls to the functions or instance installed in the server. Override the _dispatch method inhereted from SimpleXMLRPCDispatcher to change this behavior. | def _resolve_dotted_attribute(obj, attr): """Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj |
self.funcs = {} | def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1): self.funcs = {} self.logRequests = logRequests self.instance = None SocketServer.TCPServer.__init__(self, addr, requestHandler) |
|
self.instance = None | SimpleXMLRPCDispatcher.__init__(self) | def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1): self.funcs = {} self.logRequests = logRequests self.instance = None SocketServer.TCPServer.__init__(self, addr, requestHandler) |
def register_instance(self, instance): """Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and it's parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. """ self.instance = instance def register_function(self, function, name = None): """Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function. If an instance is also registered then it will only be called if a matching function is not found. """ if name is None: name = function.__name__ self.funcs[name] = function | class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): """Simple handler for XML-RPC data passed through CGI.""" def __init__(self): SimpleXMLRPCDispatcher.__init__(self) def handle_xmlrpc(self, request_text): """Handle a single XML-RPC request""" response = self._marshaled_dispatch(request_text) print 'Content-Type: text/xml' print 'Content-Length: %d' % len(response) print print response def handle_get(self): """Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method. """ code = 400 message, explain = \ BaseHTTPServer.BaseHTTPRequestHandler.responses[code] response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \ { 'code' : code, 'message' : message, 'explain' : explain } print 'Status: %d %s' % (code, message) print 'Content-Type: text/html' print 'Content-Length: %d' % len(response) print print response def handle_request(self, request_text = None): """Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers. """ if request_text is None and \ os.environ.get('REQUEST_METHOD', None) == 'GET': self.handle_get() else: if request_text is None: request_text = sys.stdin.read() self.handle_xmlrpc(request_text) | def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1): self.funcs = {} self.logRequests = logRequests self.instance = None SocketServer.TCPServer.__init__(self, addr, requestHandler) |
def do_clear_break(self, arg): if not arg: self.do_clear("") return arg = string.strip(arg) args = string.split(arg) if len(args) < 2: print '*** Specify file and line number.' return try: line = int(args[1]) except: print '*** line number must be an integer.' return result =self.clear_break(args[0], line) if result: print result do_clb = do_clear_break | def do_clear(self, arg): # Three possibilities, tried in this order: # clear -> clear all breaks, ask for confirmation # clear file:lineno -> clear all breaks at file:lineno # clear bpno bpno ... -> clear breakpoints by number if not arg: try: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = string.lower(string.strip(reply)) if reply in ('y', 'yes'): self.clear_all_breaks() return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = string.rfind(arg, ':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except: err = "Invalid line number (%s)" % arg else: err = self.clear_break(filename, lineno) if err: print '***', err return numberlist = string.split(arg) for i in numberlist: err = self.clear_bpbynumber(i) if err: print '***', err else: print 'Deleted breakpoint %s ' % (i,) |
|
return apply(Open, (), options).show() | return Open(**options).show() | def askopenfilename(**options): "Ask for a filename to open" return apply(Open, (), options).show() |
return apply(SaveAs, (), options).show() | return SaveAs(**options).show() | def asksaveasfilename(**options): "Ask for a filename to save as" return apply(SaveAs, (), options).show() |
filename = apply(Open, (), options).show() | filename = Open(**options).show() | def askopenfile(mode = "r", **options): "Ask for a filename to open, and returned the opened file" filename = apply(Open, (), options).show() if filename: return open(filename, mode) return None |
filename = apply(SaveAs, (), options).show() | filename = SaveAs(**options).show() | def asksaveasfile(mode = "w", **options): "Ask for a filename to save as, and returned the opened file" filename = apply(SaveAs, (), options).show() if filename: return open(filename, mode) return None |
- reuse_address | - allow_reuse_address | def handle_error(self, request, client_address): """Handle an error gracefully. May be overridden. |
Technically, only a <mailbox> is allowed. In addition, email addresses without a domain are permitted. Addresses will not be modified if they are already quoted (actually if they begin with '<' and end with '>'.""" if re.match('(?s)\A<.*>\Z', addr): | Should be able to handle anything rfc822.parseaddr can handle.""" m=None try: m=rfc822.parseaddr(addr)[1] except AttributeError: pass if not m: | def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Technically, only a <mailbox> is allowed. In addition, email addresses without a domain are permitted. Addresses will not be modified if they are already quoted (actually if they begin with '<' and end with '>'.""" if re.match('(?s)\A<.*>\Z', addr): return addr localpart = None domain = '' try: at = string.rindex(addr, '@') localpart = addr[:at] domain = addr[at:] except ValueError: localpart = addr pat = re.compile(r'([<>()\[\]\\,;:@\"\001-\037\177])') return '<%s%s>' % (pat.sub(r'\\\1', localpart), domain) |
localpart = None domain = '' try: at = string.rindex(addr, '@') localpart = addr[:at] domain = addr[at:] except ValueError: localpart = addr pat = re.compile(r'([<>()\[\]\\,;:@\"\001-\037\177])') return '<%s%s>' % (pat.sub(r'\\\1', localpart), domain) | else: return "<%s>" % m | def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Technically, only a <mailbox> is allowed. In addition, email addresses without a domain are permitted. Addresses will not be modified if they are already quoted (actually if they begin with '<' and end with '>'.""" if re.match('(?s)\A<.*>\Z', addr): return addr localpart = None domain = '' try: at = string.rindex(addr, '@') localpart = addr[:at] domain = addr[at:] except ValueError: localpart = addr pat = re.compile(r'([<>()\[\]\\,;:@\"\001-\037\177])') return '<%s%s>' % (pat.sub(r'\\\1', localpart), domain) |
Double leading '.', and change Unix newline '\n' into | Double leading '.', and change Unix newline '\n', or Mac '\r' into | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n' into Internet CRLF end-of-line.""" return re.sub(r'(?m)^\.', '..', re.sub(r'\r?\n', CRLF, data)) |
re.sub(r'\r?\n', CRLF, data)) | re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n' into Internet CRLF end-of-line.""" return re.sub(r'(?m)^\.', '..', re.sub(r'\r?\n', CRLF, data)) |
esmtp_features = [] | does_esmtp = 0 | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n' into Internet CRLF end-of-line.""" return re.sub(r'(?m)^\.', '..', re.sub(r'\r?\n', CRLF, data)) |
def verify(self, address): """ SMTP 'verify' command. Checks for address validity. """ self.putcmd("vrfy", address) return self.getreply() | def verify(self, address): """ SMTP 'verify' command. Checks for address validity. """ self.putcmd("vrfy", address) return self.getreply() |
|
that suffix will be stripped off and the number interpreted as the port number to use. | and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. | def connect(self, host='localhost', port = 0): """Connect to a host on a given port. |
self.sock.send(str) | try: self.sock.send(str) except socket.error: raise SMTPServerDisconnected | def send(self, str): """Send `str' to the server.""" if self.debuglevel > 0: print 'send:', `str` if self.sock: self.sock.send(str) else: raise SMTPServerDisconnected |
def getreply(self, linehook=None): | def getreply(self): | def getreply(self, linehook=None): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (note : multiline responses converted to a single, multiline string) """ resp=[] self.file = self.sock.makefile('rb') while 1: line = self.file.readline() if self.debuglevel > 0: print 'reply:', `line` resp.append(string.strip(line[4:])) code=line[:3] #check if multiline resp if line[3:4]!="-": break elif linehook: linehook(line) try: errcode = string.atoi(code) except(ValueError): errcode = -1 |
elif linehook: linehook(line) | def getreply(self, linehook=None): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (note : multiline responses converted to a single, multiline string) """ resp=[] self.file = self.sock.makefile('rb') while 1: line = self.file.readline() if self.debuglevel > 0: print 'reply:', `line` resp.append(string.strip(line[4:])) code=line[:3] #check if multiline resp if line[3:4]!="-": break elif linehook: linehook(line) try: errcode = string.atoi(code) except(ValueError): errcode = -1 |
|
defaults to the FQDN of the local host """ | defaults to the FQDN of the local host. """ | def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("ehlo",name) (code,msg)=self.getreply(self.ehlo_hook) self.ehlo_resp=msg return code |
(code,msg)=self.getreply(self.ehlo_hook) | (code,msg)=self.getreply() if code == -1 and len(msg) == 0: raise SMTPServerDisconnected | def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host """ name=string.strip(name) if len(name)==0: name=socket.gethostbyaddr(socket.gethostname())[0] self.putcmd("ehlo",name) (code,msg)=self.getreply(self.ehlo_hook) self.ehlo_resp=msg return code |
def ehlo_hook(self, line): if line[4] in string.uppercase+string.digits: self.esmtp_features.append(string.lower(string.strip(line)[4:])) def has_option(self, opt): """Does the server support a given SMTP option?""" return opt in self.esmtp_features | def has_extn(self, opt): """Does the server support a given SMTP service extension?""" return self.esmtp_features.has_key(string.lower(opt)) | def ehlo_hook(self, line): # Interpret EHLO response lines if line[4] in string.uppercase+string.digits: self.esmtp_features.append(string.lower(string.strip(line)[4:])) |
if options: options = " " + string.joinfields(options, ' ') else: options = '' self.putcmd("mail", "from:" + quoteaddr(sender) + options) | optionlist = '' if options and self.does_esmtp: optionlist = string.join(options, ' ') self.putcmd("mail", "FROM:%s %s" % (quoteaddr(sender) ,optionlist)) | def mail(self,sender,options=[]): """ SMTP 'mail' command. Begins mail xfer session. """ if options: options = " " + string.joinfields(options, ' ') else: options = '' self.putcmd("mail", "from:" + quoteaddr(sender) + options) return self.getreply() |
def rcpt(self,recip): | def rcpt(self,recip,options=[]): | def rcpt(self,recip): """ SMTP 'rcpt' command. Indicates 1 recipient for this mail. """ self.putcmd("rcpt","to:%s" % quoteaddr(recip)) return self.getreply() |
self.putcmd("rcpt","to:%s" % quoteaddr(recip)) | optionlist = '' if options and self.does_esmtp: optionlist = string.join(options, ' ') self.putcmd("rcpt","TO:%s %s" % (quoteaddr(recip),optionlist)) | def rcpt(self,recip): """ SMTP 'rcpt' command. Indicates 1 recipient for this mail. """ self.putcmd("rcpt","to:%s" % quoteaddr(recip)) return self.getreply() |
def sendmail(self,from_addr,to_addrs,msg,options=[]): | def sendmail(self,from_addr,to_addrs,msg,mail_options=[],rcpt_options=[]): | def sendmail(self,from_addr,to_addrs,msg,options=[]): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send. - encoding : list of ESMTP options (such as 8bitmime) |
- encoding : list of ESMTP options (such as 8bitmime) | - mail_options : list of ESMTP options (such as 8bitmime) for the mail command - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands | def sendmail(self,from_addr,to_addrs,msg,options=[]): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send. - encoding : list of ESMTP options (such as 8bitmime) |
size and each of the specified options will be passed to it (if the option is in the feature set the server advertises). If EHLO fails, HELO will be tried and ESMTP options suppressed. | size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. | def sendmail(self,from_addr,to_addrs,msg,options=[]): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send. - encoding : list of ESMTP options (such as 8bitmime) |
if self.esmtp_features: self.esmtp_features.append('7bit') | def sendmail(self,from_addr,to_addrs,msg,options=[]): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send. - encoding : list of ESMTP options (such as 8bitmime) |
|
if 'size' in self.esmtp_features: esmtp_opts.append("size=" + `len(msg)`) for option in options: if option in self.esmtp_features: | if self.does_esmtp: if self.has_extn('size'): esmtp_opts.append("size=" + `len(msg)`) for option in mail_options: | def sendmail(self,from_addr,to_addrs,msg,options=[]): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send. - encoding : list of ESMTP options (such as 8bitmime) |
(code,resp)=self.rcpt(each) | (code,resp)=self.rcpt(each, rcpt_options) | def sendmail(self,from_addr,to_addrs,msg,options=[]): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send. - encoding : list of ESMTP options (such as 8bitmime) |
rm(filename + '.dir') rm(filename + '.dat') rm(filename + '.bak') | def test_dumbdbm_read(self): f = dumbdbm.open(self._fname, 'r') self.read_helper(f) f.close() def test_dumbdbm_keys(self): f = dumbdbm.open(self._fname) keys = self.keys_helper(f) f.close() def read_helper(self, f): keys = self.keys_helper(f) for key in self._dict: self.assertEqual(self._dict[key], f[key]) def keys_helper(self, f): keys = f.keys() keys.sort() self.assertEqual(keys, self._dkeys) return keys def test_main(): test_support.run_unittest(DumbDBMTestCase) if __name__ == "__main__": test_main() | def rm(fn): try: os.unlink(fn) except os.error: pass |
kControlProgressBarIndeterminateTag = 'inde' | def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262): """Display a QUESTION string which can be answered with Yes or No. Return 1 when the user clicks the Yes button. Return 0 when the user clicks the No button. Return -1 when the user clicks the Cancel button. When the user presses Return, the DEFAULT value is returned. If omitted, this is 0 (No). The QUESTION string can be at most 255 characters. """ d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return # Button assignments: # 1 = default (invisible) # 2 = Yes # 3 = No # 4 = Cancel # The question string is item 5 h = d.GetDialogItemAsControl(5) SetDialogItemText(h, lf2cr(question)) if yes != None: if yes == '': d.HideDialogItem(2) else: h = d.GetDialogItemAsControl(2) h.SetControlTitle(yes) if no != None: if no == '': d.HideDialogItem(3) else: h = d.GetDialogItemAsControl(3) h.SetControlTitle(no) if cancel != None: if cancel == '': d.HideDialogItem(4) else: h = d.GetDialogItemAsControl(4) h.SetControlTitle(cancel) d.SetDialogCancelItem(4) if default == 1: d.SetDialogDefaultItem(2) elif default == 0: d.SetDialogDefaultItem(3) elif default == -1: d.SetDialogDefaultItem(4) d.AutoSizeDialog() d.GetDialogWindow().ShowWindow() while 1: n = ModalDialog(None) if n == 1: return default if n == 2: return 1 if n == 3: return 0 if n == 4: return -1 |
|
def __init__(self, title="Working...", maxval=100, label="", id=263): | def __init__(self, title="Working...", maxval=0, label="", id=263): | def __init__(self, title="Working...", maxval=100, label="", id=263): self.w = None self.d = None self.maxval = maxval self.curval = -1 self.d = GetNewDialog(id, -1) self.w = self.d.GetDialogWindow() self.label(label) self._update(0) self.d.AutoSizeDialog() self.title(title) self.w.ShowWindow() self.d.DrawDialog() |
self.maxval = maxval self.curval = -1 | def __init__(self, title="Working...", maxval=100, label="", id=263): self.w = None self.d = None self.maxval = maxval self.curval = -1 self.d = GetNewDialog(id, -1) self.w = self.d.GetDialogWindow() self.label(label) self._update(0) self.d.AutoSizeDialog() self.title(title) self.w.ShowWindow() self.d.DrawDialog() |
|
self._update(0) | self.title(title) self.set(0, maxval) | def __init__(self, title="Working...", maxval=100, label="", id=263): self.w = None self.d = None self.maxval = maxval self.curval = -1 self.d = GetNewDialog(id, -1) self.w = self.d.GetDialogWindow() self.label(label) self._update(0) self.d.AutoSizeDialog() self.title(title) self.w.ShowWindow() self.d.DrawDialog() |
self.title(title) | def __init__(self, title="Working...", maxval=100, label="", id=263): self.w = None self.d = None self.maxval = maxval self.curval = -1 self.d = GetNewDialog(id, -1) self.w = self.d.GetDialogWindow() self.label(label) self._update(0) self.d.AutoSizeDialog() self.title(title) self.w.ShowWindow() self.d.DrawDialog() |
|
if maxval == 0: value = 0 maxval = 1 if maxval > 32767: value = int(value/(maxval/32767.0)) maxval = 32767 progbar = self.d.GetDialogItemAsControl(3) progbar.SetControlMaximum(maxval) progbar.SetControlValue(value) | if maxval == 0: Ctl.IdleControls(self.w) else: if maxval > 32767: value = int(value/(maxval/32767.0)) maxval = 32767 progbar = self.d.GetDialogItemAsControl(3) progbar.SetControlMaximum(maxval) progbar.SetControlValue(value) | def _update(self, value): maxval = self.maxval if maxval == 0: # XXXX Quick fix. Should probably display an unknown duration value = 0 maxval = 1 if maxval > 32767: value = int(value/(maxval/32767.0)) maxval = 32767 progbar = self.d.GetDialogItemAsControl(3) progbar.SetControlMaximum(maxval) progbar.SetControlValue(value) # Test for cancel button ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 ) if ready : what,msg,when,where,mod = ev part = Win.FindWindow(where)[0] if Dlg.IsDialogEvent(ev): ds = Dlg.DialogSelect(ev) if ds[0] and ds[1] == self.d and ds[-1] == 1: self.w.HideWindow() self.w = None self.d = None raise KeyboardInterrupt, ev else: if part == 4: # inDrag self.w.DragWindow(where, screenbounds) else: MacOS.HandleEvent(ev) |
if value < 0: value = 0 if value > self.maxval: value = self.maxval | bar = self.d.GetDialogItemAsControl(3) if max <= 0: bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x01') else: bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x00') if value < 0: value = 0 elif value > self.maxval: value = self.maxval | def set(self, value, max=None): """set(value) - Set progress bar position""" if max != None: self.maxval = max if value < 0: value = 0 if value > self.maxval: value = self.maxval self.curval = value self._update(value) |
bar = ProgressBar("Progress, progress...", 100) | bar = ProgressBar("Progress, progress...", 0, label="Ramping up...") | def test(): import time, sys Message("Testing EasyDialogs.") optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'), ('flags=', 'Valued option'), ('f:', 'Short valued option')) commandlist = (('start', 'Start something'), ('stop', 'Stop something')) argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) for i in range(len(argv)): print 'arg[%d] = %s'%(i, `argv[i]`) print 'Type return to continue - ', sys.stdin.readline() ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") if ok > 0: s = AskString("Enter your first name", "Joe") s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None") if not s2: Message("%s has no secret nickname"%s) else: Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2)) text = ( "Working Hard...", "Hardly Working..." , "So far, so good!", "Keep on truckin'" ) bar = ProgressBar("Progress, progress...", 100) try: appsw = MacOS.SchedParams(1, 0) for i in range(100): bar.set(i) time.sleep(0.1) if i % 10 == 0: bar.label(text[(i/10) % 4]) bar.label("Done.") time.sleep(0.3) # give'em a chance to see the done. finally: del bar apply(MacOS.SchedParams, appsw) |
for i in range(100): | for i in xrange(20): bar.inc() time.sleep(0.05) bar.set(0,100) for i in xrange(100): | def test(): import time, sys Message("Testing EasyDialogs.") optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'), ('flags=', 'Valued option'), ('f:', 'Short valued option')) commandlist = (('start', 'Start something'), ('stop', 'Stop something')) argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) for i in range(len(argv)): print 'arg[%d] = %s'%(i, `argv[i]`) print 'Type return to continue - ', sys.stdin.readline() ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") if ok > 0: s = AskString("Enter your first name", "Joe") s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None") if not s2: Message("%s has no secret nickname"%s) else: Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2)) text = ( "Working Hard...", "Hardly Working..." , "So far, so good!", "Keep on truckin'" ) bar = ProgressBar("Progress, progress...", 100) try: appsw = MacOS.SchedParams(1, 0) for i in range(100): bar.set(i) time.sleep(0.1) if i % 10 == 0: bar.label(text[(i/10) % 4]) bar.label("Done.") time.sleep(0.3) # give'em a chance to see the done. finally: del bar apply(MacOS.SchedParams, appsw) |
time.sleep(0.1) | time.sleep(0.05) | def test(): import time, sys Message("Testing EasyDialogs.") optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'), ('flags=', 'Valued option'), ('f:', 'Short valued option')) commandlist = (('start', 'Start something'), ('stop', 'Stop something')) argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) for i in range(len(argv)): print 'arg[%d] = %s'%(i, `argv[i]`) print 'Type return to continue - ', sys.stdin.readline() ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") if ok > 0: s = AskString("Enter your first name", "Joe") s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None") if not s2: Message("%s has no secret nickname"%s) else: Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2)) text = ( "Working Hard...", "Hardly Working..." , "So far, so good!", "Keep on truckin'" ) bar = ProgressBar("Progress, progress...", 100) try: appsw = MacOS.SchedParams(1, 0) for i in range(100): bar.set(i) time.sleep(0.1) if i % 10 == 0: bar.label(text[(i/10) % 4]) bar.label("Done.") time.sleep(0.3) # give'em a chance to see the done. finally: del bar apply(MacOS.SchedParams, appsw) |
time.sleep(0.3) | time.sleep(1.0) | def test(): import time, sys Message("Testing EasyDialogs.") optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'), ('flags=', 'Valued option'), ('f:', 'Short valued option')) commandlist = (('start', 'Start something'), ('stop', 'Stop something')) argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) for i in range(len(argv)): print 'arg[%d] = %s'%(i, `argv[i]`) print 'Type return to continue - ', sys.stdin.readline() ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") if ok > 0: s = AskString("Enter your first name", "Joe") s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None") if not s2: Message("%s has no secret nickname"%s) else: Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2)) text = ( "Working Hard...", "Hardly Working..." , "So far, so good!", "Keep on truckin'" ) bar = ProgressBar("Progress, progress...", 100) try: appsw = MacOS.SchedParams(1, 0) for i in range(100): bar.set(i) time.sleep(0.1) if i % 10 == 0: bar.label(text[(i/10) % 4]) bar.label("Done.") time.sleep(0.3) # give'em a chance to see the done. finally: del bar apply(MacOS.SchedParams, appsw) |
"install-base or install-platbase supplied, but " + \ "installation scheme is incomplete" | ("install-base or install-platbase supplied, but " "installation scheme is incomplete") | def finalize_unix (self): |
"'extra_path' option must be a list, tuple, or " + \ "comma-separated string with 1 or 2 elements" | ("'extra_path' option must be a list, tuple, or " "comma-separated string with 1 or 2 elements") | def handle_extra_path (self): |
self.warn(("modules installed to '%s', which is not in " + "Python's module search path (sys.path) -- " + "you'll have to change the search path yourself") % self.install_lib) | log.debug(("modules installed to '%s', which is not in " "Python's module search path (sys.path) -- " "you'll have to change the search path yourself"), self.install_lib) | def run (self): |
data, width, height, bytesperpixel = jpeg.decompress(data) | data, width, height, bytesperpixel = jpeg.decompress(img) | def jpeggrey2grey(img, width, height): import jpeg data, width, height, bytesperpixel = jpeg.decompress(data) if bytesperpixel <> 1: raise RuntimeError, 'not grayscale jpeg' return data |
data, width, height, bytesperpixel = jpeg.decompress(data) | data, width, height, bytesperpixel = jpeg.decompress(img) | def jpeg2rgb(img, width, height): import cl, CL import jpeg data, width, height, bytesperpixel = jpeg.decompress(data) if bytesperpixel <> 4: raise RuntimeError, 'not rgb jpeg' return data |
('grey', 'jpeggrey',grey2jpeggrey, NOT_LOSSY), \ | ('grey', 'jpeggrey',grey2jpeggrey, LOSSY), \ | def jpeg2rgb(img, width, height): import cl, CL import jpeg data, width, height, bytesperpixel = jpeg.decompress(data) if bytesperpixel <> 4: raise RuntimeError, 'not rgb jpeg' return data |
('rgb', 'jpeg', rgb2jpeg, NOT_LOSSY), \ | ('rgb', 'jpeg', rgb2jpeg, LOSSY), \ | def jpeg2rgb(img, width, height): import cl, CL import jpeg data, width, height, bytesperpixel = jpeg.decompress(data) if bytesperpixel <> 4: raise RuntimeError, 'not rgb jpeg' return data |
def constant_red_generator(numchips, rgbtuple): red = rgbtuple[0] | def constant_cyan_generator(numchips, rgbtuple): red, green, blue = rgbtuple | def constant_red_generator(numchips, rgbtuple): red = rgbtuple[0] seq = constant(numchips) return map(None, [red] * numchips, seq, seq) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.