bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
12,800
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
12,801
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
12,802
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
12,803
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
12,804
def run (self):
def run (self):
12,805
def run (self):
def run (self):
12,806
def run (self):
def run (self):
12,807
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version(), '%define release ' + self.release, '', 'Summary: ' + self.distribution.get_description(), ]
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version(), '%define release ' + self.release, '', 'Summary: ' + self.distribution.get_description(), ]
12,808
def testNoArgFunctions(self): # test posix functions which take no arguments and have # no side-effects which we need to cleanup (e.g., fork, wait, abort) NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname", "times", "getlogin", "getloadavg", "tmpnam", "getegid", "geteuid", "getgid", "getgroups", "getpid", "getpgrp", "getppid", "getuid", ] for name in NO_ARG_FUNCTIONS: posix_func = getattr(posix, name, None) if posix_func is not None: posix_func() self.assertRaises(TypeError, posix_func, 1)
def testNoArgFunctions(self): # test posix functions which take no arguments and have # no side-effects which we need to cleanup (e.g., fork, wait, abort) NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname", "times", "getloadavg", "tmpnam", "getegid", "geteuid", "getgid", "getgroups", "getpid", "getpgrp", "getppid", "getuid", ] for name in NO_ARG_FUNCTIONS: posix_func = getattr(posix, name, None) if posix_func is not None: posix_func() self.assertRaises(TypeError, posix_func, 1)
12,809
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash. """ if os.sep == '/': return pathname if pathname[0] == '/': raise ValueError, "path '%s' cannot be absolute" % pathname if pathname[-1] == '/': raise ValueError, "path '%s' cannot end with '/'" % pathname paths = string.split(pathname, '/') while '.' in paths: paths.remove('.') if not paths: return os.curdir return apply(os.path.join, paths)
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash. """ if os.sep == '/': return pathname if pathname and pathname[0] == '/': raise ValueError, "path '%s' cannot be absolute" % pathname if pathname[-1] == '/': raise ValueError, "path '%s' cannot end with '/'" % pathname paths = string.split(pathname, '/') while '.' in paths: paths.remove('.') if not paths: return os.curdir return apply(os.path.join, paths)
12,810
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash. """ if os.sep == '/': return pathname if pathname[0] == '/': raise ValueError, "path '%s' cannot be absolute" % pathname if pathname[-1] == '/': raise ValueError, "path '%s' cannot end with '/'" % pathname paths = string.split(pathname, '/') while '.' in paths: paths.remove('.') if not paths: return os.curdir return apply(os.path.join, paths)
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash. """ if os.sep == '/': return pathname if pathname[0] == '/': raise ValueError, "path '%s' cannot be absolute" % pathname if pathname and pathname[-1] == '/': raise ValueError, "path '%s' cannot end with '/'" % pathname paths = string.split(pathname, '/') while '.' in paths: paths.remove('.') if not paths: return os.curdir return apply(os.path.join, paths)
12,811
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
12,812
def __init__(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_response = '' # Last continuation response self.tagnum = 0
def __init__(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_response = '' # Last continuation response self.tagnum = 0
12,813
def search_text(self, text, prog=None, ok=0): """Search a text widget for the pattern.
def search_text(self, text, prog=None, ok=0): """Search a text widget for the pattern.
12,814
def search_backward(self, text, prog, line, col, wrap, ok=0): chars = text.get("%d.0" % line, "%d.0" % (line+1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: i, j = m.span() if ok or m.start() < col: return line, m line = line - 1 ok = 1 if line <= 0: if not wrap: break wrap = 0 pos = text.index("end-1c") line, col = map(int, string.split(pos, ".")) chars = text.get("%d.0" % line, "%d.0" % (line+1)) col = len(chars) - 1 return None
def search_backward(self, text, prog, line, col, wrap, ok=0): chars = text.get("%d.0" % line, "%d.0" % (line+1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: if ok or m.start() < col: return line, m line = line - 1 ok = 1 if line <= 0: if not wrap: break wrap = 0 pos = text.index("end-1c") line, col = map(int, string.split(pos, ".")) chars = text.get("%d.0" % line, "%d.0" % (line+1)) col = len(chars) - 1 return None
12,815
def finalize_options (self):
def finalize_options (self):
12,816
def test_bad_sys_path(self): import sys orig_path = sys.path coverage = hotshot._hotshot.coverage try: # verify we require a list for sys.path sys.path = 'abc' self.assertRaises(RuntimeError, coverage, test_support.TESTFN) # verify sys.path exists del sys.path self.assertRaises(RuntimeError, coverage, test_support.TESTFN) finally: sys.path = orig_path
def test_bad_sys_path(self): import sys orig_path = sys.path coverage = hotshot._hotshot.coverage try: # verify we require a list for sys.path sys.path = 'abc' self.assertRaises(RuntimeError, coverage, test_support.TESTFN) # verify sys.path exists del sys.path self.assertRaises(RuntimeError, coverage, test_support.TESTFN) finally: sys.path = orig_path
12,817
def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)] # manage the individual handlers self.handlers = [] self.handle_open = {} self.handle_error = {} self.process_response = {} self.process_request = {}
def __init__(self): client_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', client_version)] # manage the individual handlers self.handlers = [] self.handle_open = {} self.handle_error = {} self.process_response = {} self.process_request = {}
12,818
def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir'))
def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir'))
12,819
def spawn (cmd, search_path=1, verbose=0, dry_run=0): """Run another program, specified as a command list 'cmd', in a new process. 'cmd' is just the argument list for the new process, ie. cmd[0] is the program to run and cmd[1:] are the rest of its arguments. There is no way to run a program with a name different from that of its executable. If 'search_path' is true (the default), the system's executable search path will be used to find the program; otherwise, cmd[0] must be the exact path to the executable. If 'verbose' is true, a one-line summary of the command will be printed before it is run. If 'dry_run' is true, the command will not actually be run. Raise DistutilsExecError if running the program fails in any way; just return on success.""" if os.name == 'posix': _spawn_posix (cmd, search_path, verbose, dry_run) elif os.name == 'windows': # ??? # XXX should 'args' be cmd[1:] or cmd? # XXX how do we detect failure? # XXX how to do this in pre-1.5.2? # XXX is P_WAIT the correct mode? # XXX how to make Windows search the path? if verbose: print string.join (cmd, ' ') if not dry_run: os.spawnv (os.P_WAIT, cmd[0], cmd[1:]) else: raise DistutilsPlatformError, \ "don't know how to spawn programs on platform '%s'" % os.name
def spawn (cmd, search_path=1, verbose=0, dry_run=0): """Run another program, specified as a command list 'cmd', in a new process. 'cmd' is just the argument list for the new process, ie. cmd[0] is the program to run and cmd[1:] are the rest of its arguments. There is no way to run a program with a name different from that of its executable. If 'search_path' is true (the default), the system's executable search path will be used to find the program; otherwise, cmd[0] must be the exact path to the executable. If 'verbose' is true, a one-line summary of the command will be printed before it is run. If 'dry_run' is true, the command will not actually be run. Raise DistutilsExecError if running the program fails in any way; just return on success.""" if os.name == 'posix': _spawn_posix (cmd, search_path, verbose, dry_run) elif os.name == 'windows': # ??? # XXX should 'args' be cmd[1:] or cmd? # XXX how do we detect failure? # XXX how to do this in pre-1.5.2? # XXX is P_WAIT the correct mode? # XXX how to make Windows search the path? if verbose: print string.join (cmd, ' ') if not dry_run: os.spawnv (os.P_WAIT, cmd[0], cmd[1:]) else: raise DistutilsPlatformError, \ "don't know how to spawn programs on platform '%s'" % os.name
12,820
def dynamics(): if verbose: print "Testing __dynamic__..." verify(object.__dynamic__ == 0) verify(list.__dynamic__ == 0) class S1: __metaclass__ = type verify(S1.__dynamic__ == 0) class S(object): pass verify(S.__dynamic__ == 0) class D(object): __dynamic__ = 1 verify(D.__dynamic__ == 1) class E(D, S): pass verify(E.__dynamic__ == 1) class F(S, D): pass verify(F.__dynamic__ == 1) try: S.foo = 1 except (AttributeError, TypeError): pass else: verify(0, "assignment to a static class attribute should be illegal") D.foo = 1 verify(D.foo == 1) # Test that dynamic attributes are inherited verify(E.foo == 1) verify(F.foo == 1) class SS(D): __dynamic__ = 0 verify(SS.__dynamic__ == 0) verify(SS.foo == 1) try: SS.foo = 1 except (AttributeError, TypeError): pass else: verify(0, "assignment to SS.foo should be illegal") # Test dynamic instances class C(object): __dynamic__ = 1 a = C() verify(not hasattr(a, "foobar")) C.foobar = 2 verify(a.foobar == 2) C.method = lambda self: 42 verify(a.method() == 42) C.__repr__ = lambda self: "C()" verify(repr(a) == "C()") C.__int__ = lambda self: 100 verify(int(a) == 100) verify(a.foobar == 2) verify(not hasattr(a, "spam")) def mygetattr(self, name): if name == "spam": return "spam" raise AttributeError C.__getattr__ = mygetattr verify(a.spam == "spam") a.new = 12 verify(a.new == 12) def mysetattr(self, name, value): if name == "spam": raise AttributeError return object.__setattr__(self, name, value) C.__setattr__ = mysetattr try: a.spam = "not spam" except AttributeError: pass else: verify(0, "expected AttributeError") verify(a.spam == "spam") class D(C): pass d = D() d.foo = 1 verify(d.foo == 1) # Test handling of int*seq and seq*int class I(int): __dynamic__ = 1 verify("a"*I(2) == "aa") verify(I(2)*"a" == "aa") verify(2*I(3) == 6) verify(I(3)*2 == 6) verify(I(3)*I(2) == 6) # Test handling of long*seq and seq*long class L(long): __dynamic__ = 1 verify("a"*L(2L) == "aa") verify(L(2L)*"a" == "aa") verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) # Test comparison of classes with dynamic metaclasses class dynamicmetaclass(type): __dynamic__ = 1 class someclass: __metaclass__ = dynamicmetaclass verify(someclass != object)
def dynamics(): if verbose: print "Testing __dynamic__..." verify(object.__dynamic__ == 0) verify(list.__dynamic__ == 0) class S1: __metaclass__ = type verify(S1.__dynamic__ == 0) class S(object): __dynamic__ = 0 verify(S.__dynamic__ == 0) class D(object): __dynamic__ = 1 verify(D.__dynamic__ == 1) class E(D, S): __dynamic__ = 0 verify(E.__dynamic__ == 1) class F(S, D): __dynamic__ = 0 verify(F.__dynamic__ == 1) try: S.foo = 1 except (AttributeError, TypeError): __dynamic__ = 0 else: verify(0, "assignment to a static class attribute should be illegal") D.foo = 1 verify(D.foo == 1) # Test that dynamic attributes are inherited verify(E.foo == 1) verify(F.foo == 1) class SS(D): __dynamic__ = 0 verify(SS.__dynamic__ == 0) verify(SS.foo == 1) try: SS.foo = 1 except (AttributeError, TypeError): __dynamic__ = 0 else: verify(0, "assignment to SS.foo should be illegal") # Test dynamic instances class C(object): __dynamic__ = 1 a = C() verify(not hasattr(a, "foobar")) C.foobar = 2 verify(a.foobar == 2) C.method = lambda self: 42 verify(a.method() == 42) C.__repr__ = lambda self: "C()" verify(repr(a) == "C()") C.__int__ = lambda self: 100 verify(int(a) == 100) verify(a.foobar == 2) verify(not hasattr(a, "spam")) def mygetattr(self, name): if name == "spam": return "spam" raise AttributeError C.__getattr__ = mygetattr verify(a.spam == "spam") a.new = 12 verify(a.new == 12) def mysetattr(self, name, value): if name == "spam": raise AttributeError return object.__setattr__(self, name, value) C.__setattr__ = mysetattr try: a.spam = "not spam" except AttributeError: __dynamic__ = 0 else: verify(0, "expected AttributeError") verify(a.spam == "spam") class D(C): __dynamic__ = 0 d = D() d.foo = 1 verify(d.foo == 1) # Test handling of int*seq and seq*int class I(int): __dynamic__ = 1 verify("a"*I(2) == "aa") verify(I(2)*"a" == "aa") verify(2*I(3) == 6) verify(I(3)*2 == 6) verify(I(3)*I(2) == 6) # Test handling of long*seq and seq*long class L(long): __dynamic__ = 1 verify("a"*L(2L) == "aa") verify(L(2L)*"a" == "aa") verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) # Test comparison of classes with dynamic metaclasses class dynamicmetaclass(type): __dynamic__ = 1 class someclass: __metaclass__ = dynamicmetaclass verify(someclass != object)
12,821
def rich_comparisons(): if verbose: print "Testing rich comparisons..." class Z(complex): pass z = Z(1) verify(z == 1+0j) verify(1+0j == z) class ZZ(complex): def __eq__(self, other): try: return abs(self - other) <= 1e-6 except: return NotImplemented zz = ZZ(1.0000003) verify(zz == 1+0j) verify(1+0j == zz) class classic: pass for base in (classic, int, object, list): if verbose: print " (base = %s)" % base class C(base): def __init__(self, value): self.value = int(value) def __cmp__(self, other): raise TestFailed, "shouldn't call __cmp__" def __eq__(self, other): if isinstance(other, C): return self.value == other.value if isinstance(other, int) or isinstance(other, long): return self.value == other return NotImplemented def __ne__(self, other): if isinstance(other, C): return self.value != other.value if isinstance(other, int) or isinstance(other, long): return self.value != other return NotImplemented def __lt__(self, other): if isinstance(other, C): return self.value < other.value if isinstance(other, int) or isinstance(other, long): return self.value < other return NotImplemented def __le__(self, other): if isinstance(other, C): return self.value <= other.value if isinstance(other, int) or isinstance(other, long): return self.value <= other return NotImplemented def __gt__(self, other): if isinstance(other, C): return self.value > other.value if isinstance(other, int) or isinstance(other, long): return self.value > other return NotImplemented def __ge__(self, other): if isinstance(other, C): return self.value >= other.value if isinstance(other, int) or isinstance(other, long): return self.value >= other return NotImplemented c1 = C(1) c2 = C(2) c3 = C(3) verify(c1 == 1) c = {1: c1, 2: c2, 3: c3} for x in 1, 2, 3: for y in 1, 2, 3: for op in "<", "<=", "==", "!=", ">", ">=": verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("c[x] %s y" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("x %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y))
def rich_comparisons(): if verbose: print "Testing rich comparisons..." class Z(complex): __dynamic__ = 0 z = Z(1) verify(z == 1+0j) verify(1+0j == z) class ZZ(complex): def __eq__(self, other): try: return abs(self - other) <= 1e-6 except: return NotImplemented zz = ZZ(1.0000003) verify(zz == 1+0j) verify(1+0j == zz) class classic: __dynamic__ = 0 for base in (classic, int, object, list): if verbose: print " (base = %s)" % base class C(base): def __init__(self, value): self.value = int(value) def __cmp__(self, other): raise TestFailed, "shouldn't call __cmp__" def __eq__(self, other): if isinstance(other, C): return self.value == other.value if isinstance(other, int) or isinstance(other, long): return self.value == other return NotImplemented def __ne__(self, other): if isinstance(other, C): return self.value != other.value if isinstance(other, int) or isinstance(other, long): return self.value != other return NotImplemented def __lt__(self, other): if isinstance(other, C): return self.value < other.value if isinstance(other, int) or isinstance(other, long): return self.value < other return NotImplemented def __le__(self, other): if isinstance(other, C): return self.value <= other.value if isinstance(other, int) or isinstance(other, long): return self.value <= other return NotImplemented def __gt__(self, other): if isinstance(other, C): return self.value > other.value if isinstance(other, int) or isinstance(other, long): return self.value > other return NotImplemented def __ge__(self, other): if isinstance(other, C): return self.value >= other.value if isinstance(other, int) or isinstance(other, long): return self.value >= other return NotImplemented c1 = C(1) c2 = C(2) c3 = C(3) verify(c1 == 1) c = {1: c1, 2: c2, 3: c3} for x in 1, 2, 3: for y in 1, 2, 3: for op in "<", "<=", "==", "!=", ">", ">=": verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("c[x] %s y" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("x %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y))
12,822
def coercions(): if verbose: print "Testing coercions..." class I(int): pass coerce(I(0), 0) coerce(0, I(0)) class L(long): pass coerce(L(0), 0) coerce(L(0), 0L) coerce(0, L(0)) coerce(0L, L(0)) class F(float): pass coerce(F(0), 0) coerce(F(0), 0L) coerce(F(0), 0.) coerce(0, F(0)) coerce(0L, F(0)) coerce(0., F(0)) class C(complex): pass coerce(C(0), 0) coerce(C(0), 0L) coerce(C(0), 0.) coerce(C(0), 0j) coerce(0, C(0)) coerce(0L, C(0)) coerce(0., C(0)) coerce(0j, C(0))
def coercions(): if verbose: print "Testing coercions..." class I(int): pass coerce(I(0), 0) coerce(0, I(0)) class L(long): pass coerce(L(0), 0) coerce(L(0), 0L) coerce(0, L(0)) coerce(0L, L(0)) class F(float): pass coerce(F(0), 0) coerce(F(0), 0L) coerce(F(0), 0.) coerce(0, F(0)) coerce(0L, F(0)) coerce(0., F(0)) class C(complex): __dynamic__ = 0 coerce(C(0), 0) coerce(C(0), 0L) coerce(C(0), 0.) coerce(C(0), 0j) coerce(0, C(0)) coerce(0L, C(0)) coerce(0., C(0)) coerce(0j, C(0))
12,823
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
def test_encode(self): try: fin = open(self.tmpin, 'w') fin.write(plaintext) fin.close()
12,824
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
12,825
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
12,826
def test_decode(self): try: f = open(self.tmpin, 'wb') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close()
def test_decode(self): try: f = open(self.tmpin, 'w') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close()
12,827
def test_decode(self): try: f = open(self.tmpin, 'wb') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close()
def test_decode(self): try: f = open(self.tmpin, 'wb') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close()
12,828
def test_decodetwice(self): # Verify that decode() will refuse to overwrite an existing file try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout))
def test_decodetwice(self): # Verify that decode() will refuse to overwrite an existing file try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout))
12,829
def test_decodetwice(self): # Verify that decode() will refuse to overwrite an existing file try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout))
def test_decodetwice(self): # Verify that decode() will refuse to overwrite an existing file try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout))
12,830
def test_GL(self): cdll.load('libGL.so', mode=RTLD_GLOBAL) cdll.load('libGLU.so')
def test_GL(self): cdll.load('libGL.so', mode=RTLD_GLOBAL) cdll.load('libGLU.so')
12,831
def main(): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(sys.argv[1:], "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-e': edit = 1 if o == '-s': startup = 1 if o == '-t': PyShell.shell_title = a if not edit: if cmd: sys.argv = ["-c"] + args else: sys.argv = args or [""] for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) pathx = [] if edit: for filename in args: pathx.append(os.path.dirname(filename)) elif args and args[0] != "-": pathx.append(os.path.dirname(args[0])) else: pathx.append(os.curdir) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if edit: for filename in args: flist.open(filename) shell = PyShell(flist) interp = shell.interp flist.pyshell = shell if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): interp.execfile(filename) if debug: shell.open_debugger() if cmd: interp.execsource(cmd) elif not edit and args and args[0] != "-": interp.execfile(args[0]) shell.begin() root.mainloop() root.destroy()
def main(): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(sys.argv[1:], "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-e': edit = 1 if o == '-s': startup = 1 if o == '-t': PyShell.shell_title = a for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) pathx = [] if edit: for filename in args: pathx.append(os.path.dirname(filename)) elif args and args[0] != "-": pathx.append(os.path.dirname(args[0])) else: pathx.append(os.curdir) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if edit: for filename in args: flist.open(filename) shell = PyShell(flist) interp = shell.interp flist.pyshell = shell if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): interp.execfile(filename) if debug: shell.open_debugger() if cmd: interp.execsource(cmd) elif not edit and args and args[0] != "-": interp.execfile(args[0]) shell.begin() root.mainloop() root.destroy()
12,832
def main(): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(sys.argv[1:], "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-e': edit = 1 if o == '-s': startup = 1 if o == '-t': PyShell.shell_title = a if not edit: if cmd: sys.argv = ["-c"] + args else: sys.argv = args or [""] for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) pathx = [] if edit: for filename in args: pathx.append(os.path.dirname(filename)) elif args and args[0] != "-": pathx.append(os.path.dirname(args[0])) else: pathx.append(os.curdir) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if edit: for filename in args: flist.open(filename) shell = PyShell(flist) interp = shell.interp flist.pyshell = shell if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): interp.execfile(filename) if debug: shell.open_debugger() if cmd: interp.execsource(cmd) elif not edit and args and args[0] != "-": interp.execfile(args[0]) shell.begin() root.mainloop() root.destroy()
def main(): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(sys.argv[1:], "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-e': edit = 1 if o == '-s': startup = 1 if o == '-t': PyShell.shell_title = a if not edit: if cmd: sys.argv = ["-c"] + args else: sys.argv = args or [""] for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) pathx = [] if edit: for filename in args: pathx.append(os.path.dirname(filename)) elif args and args[0] != "-": pathx.append(os.path.dirname(args[0])) else: pathx.append(os.curdir) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) global flist, root root = Tk(className="Idle") fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if edit: for filename in args: flist.open(filename) shell = PyShell(flist) interp = shell.interp flist.pyshell = shell if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): interp.execfile(filename) if debug: shell.open_debugger() if cmd: interp.execsource(cmd) elif not edit and args and args[0] != "-": interp.execfile(args[0]) shell.begin() root.mainloop() root.destroy()
12,833
def resolveEntity(self, publicId, systemId): self._ent_handler.resolveEntity(publicId, systemId)
def resolveEntity(self, publicId, systemId): self._ent_handler.resolveEntity(publicId, systemId)
12,834
fp.write("\tdef %s(self, "%funcname)
fp.write("\tdef %s(self, "%funcname)
12,835
def read(self, filenames):
defread(self,filenames):
12,836
def read(self, filenames):
def read(self, filenames):
12,837
def run (self): if (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform")
def run (self): if (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform")
12,838
def get_inidata (self): # Return data describing the installation.
def get_inidata (self): # Return data describing the installation.
12,839
def create_exe (self, arcname, fullname): import struct
def create_exe (self, arcname, fullname, bitmap=None): import struct
12,840
def create_exe (self, arcname, fullname): import struct
def create_exe (self, arcname, fullname): import struct
12,841
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
12,842
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
12,843
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
12,844
def __init__(self, switchboard, master=None): self.__sb = switchboard self.__frame = Frame(master, relief=RAISED, borderwidth=1) self.__frame.grid(row=3, column=0, ipadx=5) # create the chip that will display the currently selected color # exactly self.__sframe = Frame(self.__frame) self.__sframe.grid(row=0, column=0) self.__selected = ChipWidget(self.__sframe, text='Selected') # create the chip that will display the nearest real X11 color # database color name self.__nframe = Frame(self.__frame) self.__nframe.grid(row=0, column=1) self.__nearest = ChipWidget(self.__nframe, text='Nearest', presscmd = self.__buttonpress, releasecmd = self.__buttonrelease)
def __init__(self, switchboard, master=None): self.__sb = switchboard self.__frame = Frame(master, relief=RAISED, borderwidth=1) self.__frame.grid(row=3, column=0, ipadx=5, sticky='NSEW') # create the chip that will display the currently selected color # exactly self.__sframe = Frame(self.__frame) self.__sframe.grid(row=0, column=0) self.__selected = ChipWidget(self.__sframe, text='Selected') # create the chip that will display the nearest real X11 color # database color name self.__nframe = Frame(self.__frame) self.__nframe.grid(row=0, column=1) self.__nearest = ChipWidget(self.__nframe, text='Nearest', presscmd = self.__buttonpress, releasecmd = self.__buttonrelease)
12,845
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
12,846
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
12,847
def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def').""" # XXX Can speed this up an order of magnitude safe = always_safe + safe res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02x' % ord(c) return string.joinfields(res, '')
def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def'.""" # XXX Can speed this up an order of magnitude safe = always_safe + safe res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02x' % ord(c) return string.joinfields(res, '')
12,848
def finalize_options (self): pass
def finalize_options (self): pass
12,849
def _reconstruct(x, info, deep, memo=None): if isinstance(info, str): return x assert isinstance(info, tuple) if memo is None: memo = {} n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args, memo) y = callable(*args) if state: if deep: state = deepcopy(state, memo) y.__dict__.update(state) return y
def _reconstruct(x, info, deep, memo=None): if isinstance(info, str): return x assert isinstance(info, tuple) if memo is None: memo = {} n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args, memo) y = callable(*args) if state: if deep: state = deepcopy(state, memo) if hasattr(y, '__setstate__'): y.__setstate__(state) else: y.__dict__.update(state) return y
12,850
def test_timeout(): test_support.requires('network') if test_support.verbose: print "test_timeout ..." # A service which issues a welcome banner (without need to write # anything). # XXX ("gmail.org", 995) has been unreliable so far, from time to time # XXX non-responsive for hours on end (& across all buildbot slaves, # XXX so that's not just a local thing). ADDR = "gmail.org", 995 s = socket.socket() s.settimeout(30.0) try: s.connect(ADDR) except socket.timeout: print >> sys.stderr, """\ WARNING: an attempt to connect to %r timed out, in test_timeout. That may be legitimate, but is not the outcome we hoped for. If this message is seen often, test_timeout should be changed to use a more reliable address.""" % (ADDR,) return except socket.err, exc: # In case connection is refused. if (isinstance(exc.message, tuple) and exc.message[0] == errno.ECONNREFUSED): raise test_support.TestSkipped("test socket connection refused") else: raise exc ss = socket.ssl(s) # Read part of return welcome banner twice. ss.read(1) ss.read(1) s.close()
def test_timeout(): test_support.requires('network') if test_support.verbose: print "test_timeout ..." # A service which issues a welcome banner (without need to write # anything). # XXX ("gmail.org", 995) has been unreliable so far, from time to time # XXX non-responsive for hours on end (& across all buildbot slaves, # XXX so that's not just a local thing). ADDR = "gmail.org", 995 s = socket.socket() s.settimeout(30.0) try: s.connect(ADDR) except socket.timeout: print >> sys.stderr, """\ WARNING: an attempt to connect to %r timed out, in test_timeout. That may be legitimate, but is not the outcome we hoped for. If this message is seen often, test_timeout should be changed to use a more reliable address.""" % (ADDR,) return except socket.error, exc: # In case connection is refused. if (isinstance(exc.message, tuple) and exc.message[0] == errno.ECONNREFUSED): raise test_support.TestSkipped("test socket connection refused") else: raise exc ss = socket.ssl(s) # Read part of return welcome banner twice. ss.read(1) ss.read(1) s.close()
12,851
def main(): VERBOSE = 0 opts, args = getopt.getopt(sys.argv[1:], 'vq') for k, v in opts: if k == '-v': VERBOSE = 1 visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1 if k == '-q': f = open('/dev/null', 'wb') sys.stdout = f if not args: print "no files to compile" else: for filename in args: if VERBOSE: print filename compile(filename)
def main(): VERBOSE = 0 opts, args = getopt.getopt(sys.argv[1:], 'vq') for k, v in opts: if k == '-v': VERBOSE = 1 visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1 if k == '-q': if sys.platform[:3]=="win": f = open('nul', 'wb') else: f = open('/dev/null', 'wb') sys.stdout = f if not args: print "no files to compile" else: for filename in args: if VERBOSE: print filename compile(filename)
12,852
def page(self, title, contents): """Format an HTML page.""" return '''
def page(self, title, contents): """Format an HTML page.""" return '''
12,853
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return '''
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return '''
12,854
def section(self, title, fgcol, bgcol, contents, width=10, prelude='', marginalia=None, gap='&nbsp;&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '<tt>' + '&nbsp;' * width + '</tt>' result = '''
def section(self, title, fgcol, bgcol, contents, width=10, prelude='', marginalia=None, gap='&nbsp;&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '<tt>' + '&nbsp;' * width + '</tt>' result = '''
12,855
def multicolumn(self, list, format, cols=4): """Format a list of items into a multi-column list.""" result = '' rows = (len(list)+cols-1)/cols for col in range(cols): result = result + '<td width="%d%%" valign=top>' % (100/cols) for i in range(rows*col, rows*col+rows): if i < len(list): result = result + format(list[i]) + '<br>\n' result = result + '</td>' return '<table width="100%%"><tr>%s</tr></table>' % result
def multicolumn(self, list, format, cols=4): """Format a list of items into a multi-column list.""" result = '' rows = (len(list)+cols-1)/cols for col in range(cols): result = result + '<td width="%d%%" valign=top>' % (100/cols) for i in range(rows*col, rows*col+rows): if i < len(list): result = result + format(list[i]) + '<br>\n' result = result + '</td>' return '<table width="100%%"><tr>%s</tr></table>' % result
12,856
def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if imclass is not cl: note = ' from ' + self.classlink(imclass, mod) else: if object.im_self: note = ' method of %s instance' % self.classlink( object.im_self.__class__, mod) else: note = ' unbound %s method' % self.classlink(imclass,mod) object = object.im_func
def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if imclass is not cl: note = ' from ' + self.classlink(imclass, mod) else: if object.im_self: note = ' method of %s instance' % self.classlink( object.im_self.__class__, mod) else: note = ' unbound %s method' % self.classlink(imclass,mod) object = object.im_func
12,857
def walk_python_files(self, paths, *args, **kwargs): for path in paths: if os.path.isfile(path): yield path.endswith(".py") elif os.path.isdir(path): for root, dirs, files in os.walk(path): for filename in files: if filename.endswith(".py"): yield os.path.join(root, filename)
def walk_python_files(self, paths, *args, **kwargs): for path in paths: if os.path.isfile(path): yield path.endswith(".py") elif os.path.isdir(path): for root, dirs, files in os.walk(path): for filename in files: if filename.endswith(".py"): yield os.path.join(root, filename)
12,858
def get_declaration(line): match = decl_re.search(line) if match: return match.group(1) return ''
binary_re = re.compile('[\x00-\x08\x0E-\x1F\x7F]')
12,859
def has_correct_encoding(text, codec): try: unicode(text, codec) except UnicodeDecodeError: return False else: return True
debug = False def print_debug(msg): if debug: print msg def _open(fullpath): try: unicode(text, codec) except UnicodeDecodeError: return False else: return True
12,860
def has_correct_encoding(text, codec): try: unicode(text, codec) except UnicodeDecodeError: return False else: return True
def has_correct_encoding(text, codec): try: size = os.stat(fullpath).st_size except OSError, err: print_debug("%s: permission denied: %s" % (fullpath, err)) return None if size > 1024*1024: print_debug("%s: the file is too big: %d bytes" % (fullpath, size)) return None try: return open(fullpath, 'rU') except IOError, err: print_debug("%s: access denied: %s" % (fullpath, err)) return None def has_python_ext(fullpath): return fullpath.endswith(".py") or fullpath.endswith(".pyw") def looks_like_python(fullpath): infile = _open(fullpath) if infile is None: return False else: return True
12,861
def has_correct_encoding(text, codec): try: unicode(text, codec) except UnicodeDecodeError: return False else: return True
def has_correct_encoding(text, codec): try: unicode(text, codec) except UnicodeDecodeError: return False line = infile.readline() infile.close() if binary_re.search(line): print_debug("%s: appears to be binary" % fullpath) return False if fullpath.endswith(".py") or fullpath.endswith(".pyw"): return True elif "python" in line: return True
12,862
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
return False def can_be_compiled(fullpath): infile = _open(fullpath) if infile is None: return False code = infile.read() infile.close() try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
12,863
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
12,864
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
12,865
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
12,866
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() return False # check the whole file for non-ASCII characters rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False return True
12,867
def link_shared_lib (self, objects, output_libname, libraries=None, library_dirs=None): """Link a bunch of stuff together to create a shared library file. Has the same effect as 'link_static_lib()' except that the filename inferred from 'output_libname' will most likely be different, and the type of file generated will almost certainly be different.""" pass
def link_shared_lib (self, objects, output_libname, libraries=None, library_dirs=None, build_info=None): """Link a bunch of stuff together to create a shared library file. Has the same effect as 'link_static_lib()' except that the filename inferred from 'output_libname' will most likely be different, and the type of file generated will almost certainly be different.""" pass
12,868
def link_shared_object (self, objects, output_filename, libraries=None, library_dirs=None): """Link a bunch of stuff together to create a shared object file. Much like 'link_shared_lib()', except the output filename is explicitly supplied as 'output_filename'.""" pass
def link_shared_object (self, objects, output_filename, libraries=None, library_dirs=None, build_info=None): """Link a bunch of stuff together to create a shared object file. Much like 'link_shared_lib()', except the output filename is explicitly supplied as 'output_filename'.""" pass
12,869
def object_filenames (source_filenames): """Return the list of object filenames corresponding to each specified source filename.""" pass
def object_filenames (self, source_filenames): """Return the list of object filenames corresponding to each specified source filename.""" pass
12,870
def shared_object_filename (source_filename): """Return the shared object filename corresponding to a specified source filename.""" pass
def shared_object_filename (self, source_filename): """Return the shared object filename corresponding to a specified source filename.""" pass
12,871
def library_filename (libname): """Return the static library filename corresponding to the specified library name.""" pass
def library_filename (self, libname): """Return the static library filename corresponding to the specified library name.""" pass
12,872
def shared_library_filename (libname): """Return the shared library filename corresponding to the specified library name.""" pass
def shared_library_filename (self, libname): """Return the shared library filename corresponding to the specified library name.""" pass
12,873
def __index__(self): return self.ind
def __index__(self): return self.ind
12,874
def setUp(self): self.seq = [0,10,20,30,40,50] self.o = oldstyle() self.n = newstyle() self.o2 = oldstyle() self.n2 = newstyle()
def setUp(self): self.o = oldstyle() self.n = newstyle() self.o2 = oldstyle() self.n2 = newstyle()
12,875
def setUp(self): self.seq = [0,10,20,30,40,50] self.o = oldstyle() self.n = newstyle() self.o2 = oldstyle() self.n2 = newstyle()
def setUp(self): self.seq = [0,10,20,30,40,50] self.o = oldstyle() self.n = newstyle() self.o2 = oldstyle() self.n2 = newstyle()
12,876
def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 assert(self.seq[self.o:self.o2] == self.seq[1:3]) assert(self.seq[self.n:self.n2] == self.seq[2:4])
def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 assert(self.seq[self.o:self.o2] == self.seq[1:3]) assert(self.seq[self.n:self.n2] == self.seq[2:4])
12,877
def test_basic(self): self.o.ind = -2 self.n.ind = 2 assert(self.seq[self.n] == self.seq[2]) assert(self.seq[self.o] == self.seq[-2]) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2)
class ListTestCase(BaseTestCase): seq = [0,10,20,30,40,50] def test_setdelitem(self): self.o.ind = -2 self.n.ind = 2 assert(self.seq[self.n] == self.seq[2]) assert(self.seq[self.o] == self.seq[-2]) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2)
12,878
def test_basic(self): self.o.ind = -2 self.n.ind = 2 assert(self.seq[self.n] == self.seq[2]) assert(self.seq[self.o] == self.seq[-2]) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2)
def test_basic(self): self.o.ind = -2 self.n.ind = 2 assert(self.seq[self.n] == self.seq[2]) assert(self.seq[self.o] == self.seq[-2]) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2)
12,879
def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' myfunc = lambda x, obj: obj.seq[x] self.failUnlessRaises(TypeError, operator.index, self.o) self.failUnlessRaises(TypeError, operator.index, self.n) self.failUnlessRaises(TypeError, myfunc, self.o, self) self.failUnlessRaises(TypeError, myfunc, self.n, self)
def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' myfunc = lambda x, obj: obj.seq[x] self.failUnlessRaises(TypeError, operator.index, self.o) self.failUnlessRaises(TypeError, operator.index, self.n) self.failUnlessRaises(TypeError, myfunc, self.o, self) self.failUnlessRaises(TypeError, myfunc, self.n, self)
12,880
def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 assert(self.seq[self.o:self.o2] == self.seq[1:3]) assert(self.seq[self.n:self.n2] == self.seq[2:4])
def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 assert(self.seq[self.o:self.o2] == self.seq[1:3]) assert(self.seq[self.n:self.n2] == self.seq[2:4])
12,881
def test_main(): test_support.run_unittest( ListTestCase, TupleTestCase, StringTestCase, UnicodeTestCase )
def test_main(): test_support.run_unittest( ListTestCase, TupleTestCase, StringTestCase, UnicodeTestCase, XRangeTestCase, )
12,882
def anchor_bgn(self, href, name, type): if self.proc: self.saved_clear() self.write('<OBJECT type="text/sitemap">\n') self.tab('\t<param name="Local" value="%s/%s">\n' % (self.path, href))
def anchor_bgn(self, href, name, type): if self.proc: self.saved_clear() self.write('<OBJECT type="text/sitemap">\n') self.tab('\t<param name="Local" value="%s/%s">\n' % (self.path, href))
12,883
def anchor_end(self): if self.proc: self.tab('\t<param name="Name" value="%s">\n' % self.saved_get()) self.tab('\t</OBJECT>\n')
def anchor_end(self): if self.proc: self.tab('\t<param name="Name" value="%s">\n' % self.saved_get()) self.tab('\t</OBJECT>\n')
12,884
def do_content(library, version, output): output.write(contents_header % version) for book in library: print '\t', book.title, '-', book.firstpage output.write(object_sitemap % (book.directory + "/" + book.firstpage, book.title)) if book.contentpage: content(book.directory, book.contentpage, output) output.write(contents_footer)
def do_content(library, version, output): output.write(contents_header % version) for book in library: print '\t', book.title, '-', book.firstpage path = book.directory + "/" + book.firstpage output.write('<LI>') output.write(object_sitemap % (book.title, path)) if book.contentpage: content(book.directory, book.contentpage, output) output.write(contents_footer)
12,885
def getaddrlist(self, name): """Get a list of addresses from a header. Retrieves a list of addresses from a header, where each address is a tuple as returned by getaddr(). """ # New, by Ben Escoto try: data = self[name] except KeyError: return [] a = AddrlistClass(data) return a.getaddrlist()
def getaddrlist(self, name): """Get a list of addresses from a header. Retrieves a list of addresses from a header, where each address is a tuple as returned by getaddr(). """ # New, by Ben Escoto try: data = self[name] except KeyError: return [] a = AddrlistClass(data) return a.getaddrlist()
12,886
def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r' self.atomends = self.specials + self.LWS + self.CR self.field = field self.commentlist = []
def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r\n' self.atomends = self.specials + self.LWS + self.CR self.field = field self.commentlist = []
12,887
def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r' self.atomends = self.specials + self.LWS + self.CR self.field = field self.commentlist = []
def__init__(self,field):"""Initializeanewinstance.`field'isanunparsedaddressheaderfield,containingoneormoreaddresses."""self.specials='()<>@,:;.\"[]'self.pos=0self.LWS='\t'self.CR='\r'self.atomends=self.specials+self.LWS+self.CRself.field=fieldself.commentlist=[]
12,888
def getdomain(self): """Get the complete domain name from an address.""" sdlist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS: self.pos = self.pos + 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] == '[': sdlist.append(self.getdomainliteral()) elif self.field[self.pos] == '.': self.pos = self.pos + 1 sdlist.append('.') elif self.field[self.pos] in self.atomends: break else: sdlist.append(self.getatom()) return string.join(sdlist, '')
defgetdomain(self):"""Getthecompletedomainnamefromanaddress."""sdlist=[]whileself.pos<len(self.field):ifself.field[self.pos]inself.LWS:self.pos=self.pos+1elifself.field[self.pos]=='(':self.commentlist.append(self.getcomment())elifself.field[self.pos]=='[':sdlist.append(self.getdomainliteral())elifself.field[self.pos]=='.':self.pos=self.pos+1sdlist.append('.')elifself.field[self.pos]inself.atomends:breakelse:sdlist.append(self.getatom())returnstring.join(sdlist,'')
12,889
def appendChild( self, node ): if node.nodeType==Node.ELEMENT_NODE and self.documentElement: raise TypeError, "Two document elements disallowed" else: self.documentElement=node Node.appendChild( self, node ) return node
def appendChild( self, node ): if node.nodeType==Node.ELEMENT_NODE: if self.documentElement: raise TypeError, "Two document elements disallowed" else: self.documentElement=node Node.appendChild( self, node ) return node
12,890
def poll2(timeout=0.0, map=None): import poll if map is None: map = socket_map if timeout is not None: # timeout is in milliseconds timeout = int(timeout*1000) if map: l = [] for fd, obj in map.items(): flags = 0 if obj.readable(): flags = poll.POLLIN if obj.writable(): flags = flags | poll.POLLOUT if flags: l.append((fd, flags)) r = poll.poll(l, timeout) for fd, flags in r: obj = map.get(fd) if obj is None: continue readwrite(obj, flags)
def poll2(timeout=0.0, map=None): import poll if map is None: map = socket_map if timeout is not None: # timeout is in milliseconds timeout = int(timeout*1000) if map: l = [] for fd, obj in map.items(): flags = 0 if obj.readable(): flags = poll.POLLIN if obj.writable(): flags = flags | poll.POLLOUT if flags: l.append((fd, flags)) r = poll.poll(l, timeout) for fd, flags in r: obj = map.get(fd) if obj is None: continue readwrite(obj, flags)
12,891
def loop(timeout=30.0, use_poll=0, map=None): if map is None: map = socket_map if use_poll: if hasattr(select, 'poll'): poll_fun = poll3 else: poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
def loop(timeout=30.0, use_poll=0, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
12,892
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
def loop(timeout=30.0, use_poll=False, map=None, count=1e309): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
12,893
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map and count >= 0: poll_fun(timeout, map)
12,894
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): # XXX The server can force infinite recursion here! if headers.has_key('location'): newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return void = fp.read() fp.close() # In case the server sent a relative URL, join with original: newurl = basejoin("http:" + url, newurl) return self.open(newurl, data)
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): # XXX The server can force infinite recursion here! if headers.has_key('location'): newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return void = fp.read() fp.close() # In case the server sent a relative URL, join with original: newurl = basejoin("http:" + url, newurl) return self.open(newurl, data)
12,895
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): if headers.has_key('www-authenticate'): stuff = headers['www-authenticate'] import re match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) if match: scheme, realm = match.groups() if string.lower(scheme) == 'basic': name = 'retry_' + self.type + '_basic_auth' return getattr(self,name)(url, realm)
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): if headers.has_key('www-authenticate'): stuff = headers['www-authenticate'] import re match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) if match: scheme, realm = match.groups() if string.lower(scheme) == 'basic': name = 'retry_' + self.type + '_basic_auth' return getattr(self,name)(url, realm)
12,896
def retry_http_basic_auth(self, url, realm, data): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = 'http://' + host + selector return self.open(newurl, data)
def retry_http_basic_auth(self, url, realm, data): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = 'http://' + host + selector return self.open(newurl, data)
12,897
def retry_https_basic_auth(self, url, realm): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = '//' + host + selector return self.open_https(newurl)
def retry_https_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = '//' + host + selector return self.open_https(newurl)
12,898
def link_shared_lib (self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
def link_shared_lib (self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
12,899