bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint_event(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
14,400
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint_event(X) e.y_root = getint_event(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
14,401
def run_tests(): for input, output, kind in ((exec_tests, exec_results, "exec"), (single_tests, single_results, "single"), (eval_tests, eval_results, "eval")): for i, o in itertools.izip(input, output): ast_tree = compile(i, "?", kind, 0x400) # XXX(nnorwitz): these prints seem to be only for debugging. # If they are really desired, we must generate the output file. # print repr(to_tuple(ast_tree)) # print repr(o) assert to_tuple(ast_tree) == o test_order(ast_tree, (0, 0))
def run_tests(): for input, output, kind in ((exec_tests, exec_results, "exec"), (single_tests, single_results, "single"), (eval_tests, eval_results, "eval")): for i, o in itertools.izip(input, output): ast_tree = compile(i, "?", kind, 0x400) # XXX(nnorwitz): these prints seem to be only for debugging. # If they are really desired, we must generate the output file. # print repr(to_tuple(ast_tree)) # print repr(o) assert to_tuple(ast_tree) == o test_order(ast_tree, (0, 0))
14,402
def main(): global app initialcolor = (128, 128, 128) try: opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['color=', 'help']) except getopt.error, msg: usage(1, msg) if args: usage(1) for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-c', '--color'): initialcolor = arg # create the windows and go for f in RGB_TXT: try: colordb = ColorDB.get_colordb(f) break except IOError: pass else: raise IOError('No color database file found') app = Pmw.initialise(fontScheme='pmw1') app.title('Pynche %s' % __version__) app.tk.createtimerhandler(KEEPALIVE_TIMER, keepalive) # get triplet for initial color try: red, green, blue = colordb.find_byname(initialcolor) except ColorDB.BadColor: # must be a #rrggbb style color try: red, green, blue = ColorDB.rrggbb_to_triplet(initialcolor) except ColorDB.BadColor: usage(1, 'Bad initial color: %s' % initialcolor) p = PyncheWidget(colordb, app, color=(red, green, blue)) try: keepalive() app.mainloop() except KeyboardInterrupt: pass
def main(): global app initialcolor = 'grey50' try: opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['color=', 'help']) except getopt.error, msg: usage(1, msg) if args: usage(1) for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-c', '--color'): initialcolor = arg # create the windows and go for f in RGB_TXT: try: colordb = ColorDB.get_colordb(f) break except IOError: pass else: raise IOError('No color database file found') app = Pmw.initialise(fontScheme='pmw1') app.title('Pynche %s' % __version__) app.tk.createtimerhandler(KEEPALIVE_TIMER, keepalive) # get triplet for initial color try: red, green, blue = colordb.find_byname(initialcolor) except ColorDB.BadColor: # must be a #rrggbb style color try: red, green, blue = ColorDB.rrggbb_to_triplet(initialcolor) except ColorDB.BadColor: usage(1, 'Bad initial color: %s' % initialcolor) p = PyncheWidget(colordb, app, color=(red, green, blue)) try: keepalive() app.mainloop() except KeyboardInterrupt: pass
14,403
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses # and that the result always go's through __getitem__ funcs = (None, lambda x: True) class tuple2(tuple): def __getitem__(self, index): return 2*tuple.__getitem__(self, index) class str2(str): def __getitem__(self, index): return 2*str.__getitem__(self, index) inputs = { tuple2: {(): (), (1, 2, 3): (2, 4, 6)}, str2: {"": "", "123": "112233"} } if have_unicode: class unicode2(unicode): def __getitem__(self, index): return 2*unicode.__getitem__(self, index) inputs[unicode2] = { unicode(): unicode(), unicode("123"): unicode("112233") }
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses # and that the result always go's through __getitem__ funcs = (None, lambda x: True) class tuple2(tuple): def __getitem__(self, index): return 2*tuple.__getitem__(self, index) class str2(str): def __getitem__(self, index): return 2*str.__getitem__(self, index) inputs = { tuple2: {(): (), (1, 2, 3): (2, 4, 6)}, str2: {"": "", "123": "112233"} } if have_unicode: class unicode2(unicode): def __getitem__(self, index): return 2*unicode.__getitem__(self, index) inputs[unicode2] = { unicode(): unicode(), unicode("123"): unicode("112233") }
14,404
def test_long(self): self.assertEqual(long(314), 314L) self.assertEqual(long(3.14), 3L) self.assertEqual(long(314L), 314L) # Check that conversion from float truncates towards zero self.assertEqual(long(-3.14), -3L) self.assertEqual(long(3.9), 3L) self.assertEqual(long(-3.9), -3L) self.assertEqual(long(3.5), 3L) self.assertEqual(long(-3.5), -3L) self.assertEqual(long("-3"), -3L) if have_unicode: self.assertEqual(long(unicode("-3")), -3L) # Different base: self.assertEqual(long("10",16), 16L) if have_unicode: self.assertEqual(long(unicode("10"),16), 16L) # Check conversions from string (same test set as for int(), and then some) LL = [ ('1' + '0'*20, 10L**20), ('1' + '0'*100, 10L**100) ] L2 = L if have_unicode: L2 += [ (unicode('1') + unicode('0')*20, 10L**20), (unicode('1') + unicode('0')*100, 10L**100), ] for s, v in L2 + LL: for sign in "", "+", "-": for prefix in "", " ", "\t", " \t\t ": ss = prefix + sign + s vv = v if sign == "-" and v is not ValueError: vv = -v try: self.assertEqual(long(ss), long(vv)) except v: pass
def test_long(self): self.assertEqual(long(314), 314L) self.assertEqual(long(3.14), 3L) self.assertEqual(long(314L), 314L) # Check that conversion from float truncates towards zero self.assertEqual(long(-3.14), -3L) self.assertEqual(long(3.9), 3L) self.assertEqual(long(-3.9), -3L) self.assertEqual(long(3.5), 3L) self.assertEqual(long(-3.5), -3L) self.assertEqual(long("-3"), -3L) if have_unicode: self.assertEqual(long(unicode("-3")), -3L) # Different base: self.assertEqual(long("10",16), 16L) if have_unicode: self.assertEqual(long(unicode("10"),16), 16L) # Check conversions from string (same test set as for int(), and then some) LL = [ ('1' + '0'*20, 10L**20), ('1' + '0'*100, 10L**100) ] L2 = L[:] if have_unicode: L2 += [ (unicode('1') + unicode('0')*20, 10L**20), (unicode('1') + unicode('0')*100, 10L**100), ] for s, v in L2 + LL: for sign in "", "+", "-": for prefix in "", " ", "\t", " \t\t ": ss = prefix + sign + s vv = v if sign == "-" and v is not ValueError: vv = -v try: self.assertEqual(long(ss), long(vv)) except v: pass
14,405
def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if browser.find('%s') > -1: # User gave us a command line, don't mess with it. return browser else: # User gave us a browser name. command = _browsers[browser.lower()] if command[1] is None: return command[0]() else: return command[1] raise Error("could not locate runnable browser")
def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if browser.find('%s') > -1: # User gave us a command line, don't mess with it. return GenericBrowser(browser) else: # User gave us a browser name. command = _browsers[browser.lower()] if command[1] is None: return command[0]() else: return command[1] raise Error("could not locate runnable browser")
14,406
def main(): # turn off warnings when deprecated modules are imported import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) setup(name = 'Python standard library', version = '%d.%d' % sys.version_info[:2], cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall}, # The struct module is defined here, because build_ext won't be # called unless there's at least one extension module defined. ext_modules=[Extension('struct', ['structmodule.c'])], # Scripts to install scripts = ['Tools/scripts/pydoc'] )
def main(): # turn off warnings when deprecated modules are imported import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) setup(name = 'Python standard library', version = '%d.%d' % sys.version_info[:2], cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall, 'install_lib':PyBuildInstallLib}, # The struct module is defined here, because build_ext won't be # called unless there's at least one extension module defined. ext_modules=[Extension('struct', ['structmodule.c'])], # Scripts to install scripts = ['Tools/scripts/pydoc'] )
14,407
def getmodule(object): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) main = sys.modules['__main__'] if not hasattr(object, '__name__'): return None if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main builtin = sys.modules['__builtin__'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin
def getmodule(object): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[ os.path.realpath( getabsfile(module))] = module.__name__ if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) main = sys.modules['__main__'] if not hasattr(object, '__name__'): return None if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main builtin = sys.modules['__builtin__'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin
14,408
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj
14,409
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ if allow_dotted_names: attrs = attr.split('.') else: attrs = [attr] for i in attrs: if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj
14,410
def register_instance(self, instance): """Registers an instance to respond to XML-RPC requests.
def register_instance(self, instance, allow_dotted_names=False): """Registers an instance to respond to XML-RPC requests.
14,411
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together"
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together"
14,412
def _dispatch(self, method, params): """Dispatches the XML-RPC method.
def _dispatch(self, method, params): """Dispatches the XML-RPC method.
14,413
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) vereq(x.a, None) x.a = 1 vereq(x.a, 1) del x.a vereq(x.a, None) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(x.a is None) verify(x.b is None) verify(x.c is None) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "a")) x.a = 1 vereq(x.a, 1) del x.a verify(not hasattr(x, "a")) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(x.a is None) verify(x.b is None) verify(x.c is None) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
14,414
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) vereq(x.a, None) x.a = 1 vereq(x.a, 1) del x.a vereq(x.a, None) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(x.a is None) verify(x.b is None) verify(x.c is None) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "a")) x.a = 1 vereq(x.a, 1) del x.a verify(not hasattr(x, "a")) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(x.a is None) verify(x.b is None) verify(x.c is None) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
14,415
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) vereq(x.a, None) x.a = 1 vereq(x.a, 1) del x.a vereq(x.a, None) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(x.a is None) verify(x.b is None) verify(x.c is None) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) vereq(x.a, None) x.a = 1 vereq(x.a, 1) del x.a vereq(x.a, None) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, 'a')) verify(not hasattr(x, 'b')) verify(not hasattr(x, 'c')) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
14,416
def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, StringIO mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO.StringIO( 'Content-Type: %s\n' % (mtype or 'text/plain'))) host, file = splithost(url) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(url2pathname(file), 'rb'), headers, urlfile) host, port = splitport(host) if not port \ and socket.gethostbyname(host) in (localhost(), thishost()): urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(url2pathname(file), 'rb'), headers, urlfile) raise IOError, ('local file error', 'not on local host')
def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, StringIO mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO.StringIO( 'Content-Type: %s\n' % (mtype or 'text/plain'))) host, file = splithost(url) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(url2pathname(file), 'rb'), headers, urlfile) host, port = splitport(host) if not port \ and socket.gethostbyname(host) in (localhost(), thishost()): urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(url2pathname(file), 'rb'), headers, urlfile) raise IOError, ('local file error', 'not on local host')
14,417
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): """Error 302 -- relocated (temporarily).""" # 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) if data is None: return self.open(newurl) else: return self.open(newurl, data)
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): """Error 302 -- relocated (temporarily).""" # 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) if data is None: return self.open(newurl) else: return self.open(newurl, data)
14,418
def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): """Error 301 -- also relocated (permanently).""" return self.http_error_302(url, fp, errcode, errmsg, headers, data)
def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): """Error 301 -- also relocated (permanently).""" return self.http_error_302(url, fp, errcode, errmsg, headers, data)
14,419
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): """Error 401 -- authentication required. See this URL for a description of the basic authentication scheme: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt""" 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' if data is None: return getattr(self,name)(url, realm) else: return getattr(self,name)(url, realm, data)
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): """Error 401 -- authentication required. See this URL for a description of the basic authentication scheme: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt""" 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' if data is None: return getattr(self,name)(url, realm) else: return getattr(self,name)(url, realm, data)
14,420
def retry_http_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 = 'http://' + host + selector if data is None: return self.open(newurl) else: return self.open(newurl, data)
def retry_http_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 = 'http://' + host + selector if data is None: return self.open(newurl) else: return self.open(newurl, data)
14,421
def prompt_user_passwd(self, host, realm): """Override this in a GUI environment!""" import getpass try: user = raw_input("Enter username for %s at %s: " % (realm, host)) passwd = getpass.getpass("Enter password for %s in %s at %s: " % (user, realm, host)) return user, passwd except KeyboardInterrupt: print return None, None
def prompt_user_passwd(self, host, realm): """Override this in a GUI environment!""" import getpass try: user = raw_input("Enter username for %s at %s: " % (realm, host)) passwd = getpass.getpass("Enter password for %s in %s at %s: " % (user, realm, host)) return user, passwd except KeyboardInterrupt: print return None, None
14,422
def retrfile(self, file, type): import ftplib self.endtransfer() if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 else: cmd = 'TYPE ' + type; isdir = 0 try: self.ftp.voidcmd(cmd) except ftplib.all_errors: self.init() self.ftp.voidcmd(cmd) conn = None if file and not isdir: # Use nlst to see if the file exists at all try: self.ftp.nlst(file) except ftplib.error_perm, reason: raise IOError, ('ftp error', reason), sys.exc_info()[2] # Restore the transfer mode! self.ftp.voidcmd(cmd) # Try to retrieve as a file try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) except ftplib.error_perm, reason: if reason[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: # Set transfer mode to ASCII! self.ftp.voidcmd('TYPE A') # Try a directory listing if file: cmd = 'LIST ' + file else: cmd = 'LIST' conn = self.ftp.ntransfercmd(cmd) self.busy = 1 # Pass back both a suitably decorated object and a retrieval length return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
def retrfile(self, file, type): import ftplib self.endtransfer() if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 else: cmd = 'TYPE ' + type; isdir = 0 try: self.ftp.voidcmd(cmd) except ftplib.all_errors: self.init() self.ftp.voidcmd(cmd) conn = None if file and not isdir: # Use nlst to see if the file exists at all try: self.ftp.nlst(file) except ftplib.error_perm, reason: raise IOError, ('ftp error', reason), sys.exc_info()[2] # Restore the transfer mode! self.ftp.voidcmd(cmd) # Try to retrieve as a file try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) except ftplib.error_perm, reason: if reason[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: # Set transfer mode to ASCII! self.ftp.voidcmd('TYPE A') # Try a directory listing if file: cmd = 'LIST ' + file else: cmd = 'LIST' conn = self.ftp.ntransfercmd(cmd) self.busy = 1 # Pass back both a suitably decorated object and a retrieval length return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
14,423
def __repr__(self): return '<%s at %s whose fp = %s>' % (self.__class__.__name__, `id(self)`, `self.fp`)
def __repr__(self): return '<%s at %s whose fp = %s>' % (self.__class__.__name__, `id(self)`, `self.fp`)
14,424
def basejoin(base, url): """Utility to combine a URL with a base URL to form a new URL.""" type, path = splittype(url) if type: # if url is complete (i.e., it contains a type), return it return url host, path = splithost(path) type, basepath = splittype(base) # inherit type from base if host: # if url contains host, just inherit type if type: return type + '://' + host + path else: # no type inherited, so url must have started with // # just return it return url host, basepath = splithost(basepath) # inherit host basepath, basetag = splittag(basepath) # remove extraneous cruft basepath, basequery = splitquery(basepath) # idem if path[:1] != '/': # non-absolute path name if path[:1] in ('#', '?'): # path is just a tag or query, attach to basepath i = len(basepath) else: # else replace last component i = string.rfind(basepath, '/') if i < 0: # basepath not absolute if host: # host present, make absolute basepath = '/' else: # else keep non-absolute basepath = '' else: # remove last file component basepath = basepath[:i+1] # Interpret ../ (important because of symlinks) while basepath and path[:3] == '../': path = path[3:] i = string.rfind(basepath[:-1], '/') if i > 0: basepath = basepath[:i+1] elif i == 0: basepath = '/' break else: basepath = '' path = basepath + path if type and host: return type + '://' + host + path elif type: return type + ':' + path elif host: return '//' + host + path # don't know what this means else: return path
def basejoin(base, url): """Utility to combine a URL with a base URL to form a new URL.""" type, path = splittype(url) if type: # if url is complete (i.e., it contains a type), return it return url host, path = splithost(path) type, basepath = splittype(base) # inherit type from base if host: # if url contains host, just inherit type if type: return type + '://' + host + path else: # no type inherited, so url must have started with // # just return it return url host, basepath = splithost(basepath) # inherit host basepath, basetag = splittag(basepath) # remove extraneous cruft basepath, basequery = splitquery(basepath) # idem if path[:1] != '/': # non-absolute path name if path[:1] in ('#', '?'): # path is just a tag or query, attach to basepath i = len(basepath) else: # else replace last component i = string.rfind(basepath, '/') if i < 0: # basepath not absolute if host: # host present, make absolute basepath = '/' else: # else keep non-absolute basepath = '' else: # remove last file component basepath = basepath[:i+1] # Interpret ../ (important because of symlinks) while basepath and path[:3] == '../': path = path[3:] i = string.rfind(basepath[:-1], '/') if i > 0: basepath = basepath[:i+1] elif i == 0: basepath = '/' break else: basepath = '' path = basepath + path if type and host: return type + '://' + host + path elif type: return type + ':' + path elif host: return '//' + host + path # don't know what this means else: return path
14,425
def splithost(url): """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" global _hostprog if _hostprog is None: import re _hostprog = re.compile('^//([^/]*)(.*)$') match = _hostprog.match(url) if match: return match.group(1, 2) return None, url
def splithost(url): """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" global _hostprog if _hostprog is None: import re _hostprog = re.compile('^//([^/]*)(.*)$') match = _hostprog.match(url) if match: return match.group(1, 2) return None, url
14,426
def unquote_plus(s): """unquote('%7e/abc+def') -> '~/abc def'""" if '+' in s: # replace '+' with ' ' s = string.join(string.split(s, '+'), ' ') return unquote(s)
def unquote_plus(s): """unquote('%7e/abc+def') -> '~/abc def'""" if '+' in s: # replace '+' with ' ' s = string.join(string.split(s, '+'), ' ') return unquote(s)
14,427
def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ safe = always_safe + safe if _fast_safe_test == safe: return _fast_quote(s) res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02x' % ord(c) return string.join(res, '')
def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ safe = always_safe + safe if _fast_safe_test == safe: return _fast_quote(s) res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02x' % ord(c) return string.join(res, '')
14,428
def getproxies(): """Return a dictionary of scheme -> proxy server URL mappings.
def getproxies(): """Return a dictionary of scheme -> proxy server URL mappings.
14,429
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
14,430
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
14,431
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
14,432
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
14,433
def parseitem(x, self=self): return x[:1] + tuple(map(getint, x[1:]))
def parseitem(x, self=self): return x[:1] + tuple(map(getint, x[1:]))
14,434
def testBug1191043(self): # readlines() for files containing no newline data = 'BZh91AY&SY\xd9b\x89]\x00\x00\x00\x03\x80\x04\x00\x02\x00\x0c\x00 \x00!\x9ah3M\x13<]\xc9\x14\xe1BCe\x8a%t' f = open(self.filename, "wb") f.write(data) f.close() bz2f = BZ2File(self.filename) lines = bz2f.readlines() bz2f.close() self.assertEqual(lines, ['Test']) bz2f = BZ2File(self.filename) xlines = list(bz2f.xreadlines()) bz2f.close() self.assertEqual(lines, ['Test'])
def testBug1191043(self): # readlines() for files containing no newline data = 'BZh91AY&SY\xd9b\x89]\x00\x00\x00\x03\x80\x04\x00\x02\x00\x0c\x00 \x00!\x9ah3M\x13<]\xc9\x14\xe1BCe\x8a%t' f = open(self.filename, "wb") f.write(data) f.close() bz2f = BZ2File(self.filename) lines = bz2f.readlines() bz2f.close() self.assertEqual(xlines, ['Test']) bz2f = BZ2File(self.filename) xlines = list(bz2f.xreadlines()) bz2f.close() self.assertEqual(lines, ['Test'])
14,435
def test_xrange(self): self.assertEqual(list(xrange(3)), [0, 1, 2]) self.assertEqual(list(xrange(1, 5)), [1, 2, 3, 4]) self.assertEqual(list(xrange(0)), []) self.assertEqual(list(xrange(-3)), []) self.assertEqual(list(xrange(1, 10, 3)), [1, 4, 7]) self.assertEqual(list(xrange(5, -5, -3)), [5, 2, -1, -4])
def test_xrange(self): self.assertEqual(list(xrange(3)), [0, 1, 2]) self.assertEqual(list(xrange(1, 5)), [1, 2, 3, 4]) self.assertEqual(list(xrange(0)), []) self.assertEqual(list(xrange(-3)), []) self.assertEqual(list(xrange(1, 10, 3)), [1, 4, 7]) self.assertEqual(list(xrange(5, -5, -3)), [5, 2, -1, -4])
14,436
def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" print '--Call--' self.interaction(frame, None)
def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" print '--Call--' self.interaction(frame, None)
14,437
def test_main(): test_support.run_unittest( UTF16Test, UTF16LETest, UTF16BETest, UTF8Test, EscapeDecodeTest, RecodingTest, PunycodeTest, UnicodeInternalTest, NameprepTest, CodecTest, CodecsModuleTest, StreamReaderTest, Str2StrTest, BasicUnicodeTest, BasicStrTest )
def test_main(): test_support.run_unittest( UTF16Test, UTF16LETest, UTF16BETest, UTF8Test, EscapeDecodeTest, RecodingTest, PunycodeTest, UnicodeInternalTest, NameprepTest, CodecTest, CodecsModuleTest, StreamReaderTest, Str2StrTest, BasicUnicodeTest, BasicStrTest, CharmapTest )
14,438
def betavariate(self, alpha, beta):
def betavariate(self, alpha, beta):
14,439
def retrieve(self, url): if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] url1 = unwrap(url) if self.tempcache and self.tempcache.has_key(url1): self.tempcache[url] = self.tempcache[url1] return self.tempcache[url1] type, url1 = splittype(url1) if not type or type == 'file': try: fp = self.open_local_file(url1) del fp return splithost(url1)[1], None except IOError, msg: pass fp = self.open(url) headers = fp.info() import tempfile tfn = tempfile.mktemp() if self.tempcache is not None: self.tempcache[url] = result = tfn, headers tfp = open(tfn, 'w') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) del fp del tfp return result
def retrieve(self, url): if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] url1 = unwrap(url) if self.tempcache and self.tempcache.has_key(url1): self.tempcache[url] = self.tempcache[url1] return self.tempcache[url1] type, url1 = splittype(url1) if not type or type == 'file': try: fp = self.open_local_file(url1) del fp return splithost(url1)[1], None except IOError, msg: pass fp = self.open(url) headers = fp.info() import tempfile tfn = tempfile.mktemp() if self.tempcache is not None: self.tempcache[url] = result tfp = open(tfn, 'w') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) del fp del tfp return result
14,440
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses # and that the result always go's through __getitem__ # FIXME: For tuple currently it doesn't go through __getitem__ funcs = (None, lambda x: True) class tuple2(tuple): def __getitem__(self, index): return 2*tuple.__getitem__(self, index) class str2(str): def __getitem__(self, index): return 2*str.__getitem__(self, index) inputs = { tuple2: {(): (), (1, 2, 3): (1, 2, 3)}, # FIXME str2: {"": "", "123": "112233"} } if have_unicode: class unicode2(unicode): def __getitem__(self, index): return 2*unicode.__getitem__(self, index) inputs[unicode2] = { unicode(): unicode(), unicode("123"): unicode("112233") }
deftest_filter_subclasses(self):#test,thatfilter()neverreturnstuple,strorunicodesubclasses#andthattheresultalwaysgo'sthrough__getitem__#FIXME:Fortuplecurrentlyitdoesn'tgothrough__getitem__funcs=(None,lambdax:True)classtuple2(tuple):def__getitem__(self,index):return2*tuple.__getitem__(self,index)classstr2(str):def__getitem__(self,index):return2*str.__getitem__(self,index)inputs={tuple2:{():(),(1,2,3):(1,2,3)},#FIXMEstr2:{"":"","123":"112233"}}ifhave_unicode:classunicode2(unicode):def__getitem__(self,index):return2*unicode.__getitem__(self,index)inputs[unicode2]={unicode():unicode(),unicode("123"):unicode("112233")}
14,441
def __getitem__(self, index): return 2*str.__getitem__(self, index)
def __getitem__(self, index): return 2*str.__getitem__(self, index)
14,442
def __bootstrap(self): try: self.__started = 1 _active_limbo_lock.acquire() _active[_get_ident()] = self del _limbo[self] _active_limbo_lock.release() if __debug__: self._note("%s.__bootstrap(): thread started", self) try: self.run() except SystemExit: if __debug__: self._note("%s.__bootstrap(): raised SystemExit", self) except: if __debug__: self._note("%s.__bootstrap(): unhandled exception", self) s = _StringIO() _print_exc(file=s) _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), s.getvalue())) else: if __debug__: self._note("%s.__bootstrap(): normal return", self) finally: self.__stop() self.__delete()
def __bootstrap(self): try: self.__started = 1 _active_limbo_lock.acquire() _active[_get_ident()] = self del _limbo[self] _active_limbo_lock.release() if __debug__: self._note("%s.__bootstrap(): thread started", self) try: self.run() except SystemExit: if __debug__: self._note("%s.__bootstrap(): raised SystemExit", self) except: if __debug__: self._note("%s.__bootstrap(): unhandled exception", self) s = _StringIO() _print_exc(file=s) _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), s.getvalue())) else: if __debug__: self._note("%s.__bootstrap(): normal return", self) finally: self.__stop() self.__delete()
14,443
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
14,444
def __str__(self): return self.x
def __str__(self): return self.x
14,445
def __str__(self): return self.x
def __str__(self): return self.x
14,446
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
14,447
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
14,448
def test_expat_entityresolver(): return 1 # disabling this until pyexpat.c has been fixed parser = create_parser() parser.setEntityResolver(TestEntityResolver()) result = StringIO() parser.setContentHandler(XMLGenerator(result)) parser.feed('<!DOCTYPE doc [\n') parser.feed(' <!ENTITY test SYSTEM "whatever">\n') parser.feed(']>\n') parser.feed('<doc>&test;</doc>') parser.close() return result.getvalue() == start + "<doc><entity></entity></doc>"
def test_expat_entityresolver(): # disabling this until pyexpat.c has been fixed parser = create_parser() parser.setEntityResolver(TestEntityResolver()) result = StringIO() parser.setContentHandler(XMLGenerator(result)) parser.feed('<!DOCTYPE doc [\n') parser.feed(' <!ENTITY test SYSTEM "whatever">\n') parser.feed(']>\n') parser.feed('<doc>&test;</doc>') parser.close() return result.getvalue() == start + "<doc><entity></entity></doc>"
14,449
def sendevent(self, event): """Send a pre-created appleevent, await the reply and unpack it""" reply = event.AESend(self.send_flags, self.send_priority, self.send_timeout) parameters, attributes = unpackevent(reply, self._moduleName) return reply, parameters, attributes
defif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" sendevent(self,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" event):if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" """Sendif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" aif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" pre-createdif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" appleevent,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" awaitif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" theif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" replyif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" andif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" unpackif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" it"""if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" replyif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" =if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" event.AESend(self.send_flags,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" self.send_priority,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" self.send_timeout)if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" parameters,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" attributesif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" =if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" unpackevent(reply,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" self._moduleName)if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" returnif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" reply,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" parameters,if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent" attributesif not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent"
14,450
def _write_headers(self, msg): for h, v in msg.items(): # We only write the MIME-Version: header for the outermost # container message. Unfortunately, we can't use same technique # as for the Unix-From above because we don't know when # MIME-Version: will occur. if h.lower() == 'mime-version' and not self.__first: continue # RFC 2822 says that lines SHOULD be no more than maxheaderlen # characters wide, so we're well within our rights to split long # headers. text = '%s: %s' % (h, v) if self.__maxheaderlen > 0 and len(text) > self.__maxheaderlen: text = self._split_header(text) print >> self._fp, text # A blank line always separates headers from body print >> self._fp
def _write_headers(self, msg): for h, v in msg.items(): # We only write the MIME-Version: header for the outermost # container message. Unfortunately, we can't use same technique # as for the Unix-From above because we don't know when # MIME-Version: will occur. if h.lower() == 'mime-version' and not self.__first: continue # RFC 2822 says that lines SHOULD be no more than maxheaderlen # characters wide, so we're well within our rights to split long # headers. text = '%s: %s' % (h, v) if self.__maxheaderlen > 0 and len(text) > self.__maxheaderlen: text = self._split_header(h, text) print >> self._fp, text # A blank line always separates headers from body print >> self._fp
14,451
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
def _split_header(self, name, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
14,452
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.splitlines()] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
14,453
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
14,454
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
def checkit(source, opts, morecmds=[]): """Check the LaTeX formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
14,455
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTeX commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
14,456
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d" % (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
14,457
def open(self, url, new=0): os.system(self.command % url)
def open(self, url, new=0, autoraise=1): os.system(self.command % url)
14,458
def open(self, url, new=1): # XXX Currently I know no way to prevent KFM from opening a new win. self._remote("openURL %s" % url)
def open(self, url, new=1, autoraise=1): # XXX Currently I know no way to prevent KFM from opening a new win. self._remote("openURL %s" % url)
14,459
def open(self, url, new=0): if new: self._remote("LOADNEW " + url) else: self._remote("LOAD " + url)
def open(self, url, new=0, autoraise=1): if new: self._remote("LOADNEW " + url) else: self._remote("LOAD " + url)
14,460
def open(self, url, new=0): os.startfile(url)
def open(self, url, new=0, autoraise=1): os.startfile(url)
14,461
def open(self, url, new=0): ic.launchurl(url)
def open(self, url, new=0, autoraise=1): ic.launchurl(url)
14,462
def http_error_auth_reqed(self, authreq, host, req, headers): # XXX could be multiple headers authreq = headers.get(authreq, None) if authreq: mo = AbstractBasicAuthHandler.rx.match(authreq) if mo: scheme, realm = mo.groups() if scheme.lower() == 'basic': return self.retry_http_basic_auth(host, req, realm)
def http_error_auth_reqed(self, authreq, host, req, headers): # XXX could be multiple headers authreq = headers.get(authreq, None) if authreq: mo = AbstractBasicAuthHandler.rx.search(authreq) if mo: scheme, realm = mo.groups() if scheme.lower() == 'basic': return self.retry_http_basic_auth(host, req, realm)
14,463
def __setitem__(self, key, value): Form.form({key: value})
def __setitem__(self, key, value): Form.form({key: value})
14,464
def __getitem__(self,key): return self.tk.call(self.stylename, 'cget', '-%s'%key, value)
def __getitem__(self,key): return self.tk.call(self.stylename, 'cget', '-%s'%key, value)
14,465
def test_folding_of_tuples_of_constants(self): for line, elem in ( ('a = 1,2,3', '((1, 2, 3))',), ('("a","b","c")', "(('a', 'b', 'c'))",), ('a,b,c = 1,2,3', '((1, 2, 3))',), ): asm = dis_single(line) self.assert_(elem in asm) self.assert_('BUILD_TUPLE' not in asm)
def test_folding_of_tuples_of_constants(self): for line, elem in ( ('a = 1,2,3', '((1, 2, 3))'), ('("a","b","c")', "(('a', 'b', 'c'))"), ('a,b,c = 1,2,3', '((1, 2, 3))'), ('(None, 1, None)', '((None, 1, None))'), ('((1, 2), 3, 4)', '(((1, 2), 3, 4))'), ): asm = dis_single(line) self.assert_(elem in asm) self.assert_('BUILD_TUPLE' not in asm)
14,466
def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/usr/tmp', '/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 1) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir
def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/usr/tmp', '/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 1) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) if os.name == 'posix': try: fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700) except OSError: pass else: fp = os.fdopen(fd, 'w') fp.write('blat') fp.close() os.unlink(filename) del fp, fd tempdir = dir break else: fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir
14,467
def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback.''' if not callable(callback): callback = print_line resp = self.sendcmd('TYPE A') conn = self.transfercmd(cmd) fp = conn.makefile('rb') while 1: line = fp.readline() if self.debugging > 2: print '*retr*', `line` if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) fp.close() conn.close() return self.voidresp()
def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback.''' if callback is None: callback = print_line resp = self.sendcmd('TYPE A') conn = self.transfercmd(cmd) fp = conn.makefile('rb') while 1: line = fp.readline() if self.debugging > 2: print '*retr*', `line` if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) fp.close() conn.close() return self.voidresp()
14,468
def __add__(self, other): return hexint(int.__add__(self, other))
defverify(int(a) == 12345) __add__(self,verify(int(a) == 12345) other):verify(int(a) == 12345) returnverify(int(a) == 12345) hexint(int.__add__(self,verify(int(a) == 12345) other))
14,469
def __add__(self, other): return self.__class__(super(octlong, self).__add__(other))
defverify(long(a) == 12345L) __add__(self,verify(long(a) == 12345L) other):verify(long(a) == 12345L) returnverify(long(a) == 12345L) self.__class__(super(octlong,verify(long(a) == 12345L) self).__add__(other))
14,470
def __repr__(self): return "%.*g" % (self.prec, self)
defverify(float(a) == 12345.0) __repr__(self):verify(float(a) == 12345.0) returnverify(float(a) == 12345.0) "%.*g"verify(float(a) == 12345.0) %verify(float(a) == 12345.0) (self.prec,verify(float(a) == 12345.0) self)
14,471
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__(L) return self._rev
defverify(tuple(a).__class__ is tuple) rev(self):verify(tuple(a).__class__ is tuple) ifverify(tuple(a).__class__ is tuple) self._revverify(tuple(a).__class__ is tuple) isverify(tuple(a).__class__ is tuple) notverify(tuple(a).__class__ is tuple) None:verify(tuple(a).__class__ is tuple) returnverify(tuple(a).__class__ is tuple) self._revverify(tuple(a).__class__ is tuple) Lverify(tuple(a).__class__ is tuple) =verify(tuple(a).__class__ is tuple) list(self)verify(tuple(a).__class__ is tuple) L.reverse()verify(tuple(a).__class__ is tuple) self._revverify(tuple(a).__class__ is tuple) =verify(tuple(a).__class__ is tuple) self.__class__(L)verify(tuple(a).__class__ is tuple) returnverify(tuple(a).__class__ is tuple) self._rev
14,472
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
defverify(str(s) == "12345") rev(self):verify(str(s) == "12345") ifverify(str(s) == "12345") self._revverify(str(s) == "12345") isverify(str(s) == "12345") notverify(str(s) == "12345") None:verify(str(s) == "12345") returnverify(str(s) == "12345") self._revverify(str(s) == "12345") Lverify(str(s) == "12345") =verify(str(s) == "12345") list(self)verify(str(s) == "12345") L.reverse()verify(str(s) == "12345") self._revverify(str(s) == "12345") =verify(str(s) == "12345") self.__class__("".join(L))verify(str(s) == "12345") returnverify(str(s) == "12345") self._rev
14,473
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
defverify(str(s) == "\x00" * 5) rev(self):verify(str(s) == "\x00" * 5) ifverify(str(s) == "\x00" * 5) self._revverify(str(s) == "\x00" * 5) isverify(str(s) == "\x00" * 5) notverify(str(s) == "\x00" * 5) None:verify(str(s) == "\x00" * 5) returnverify(str(s) == "\x00" * 5) self._revverify(str(s) == "\x00" * 5) Lverify(str(s) == "\x00" * 5) =verify(str(s) == "\x00" * 5) list(self)verify(str(s) == "\x00" * 5) L.reverse()verify(str(s) == "\x00" * 5) self._revverify(str(s) == "\x00" * 5) =verify(str(s) == "\x00" * 5) self.__class__("".join(L))verify(str(s) == "\x00" * 5) returnverify(str(s) == "\x00" * 5) self._rev
14,474
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] exclude = [] # settable with -x option addn_link = [] # settable with -l, but only honored under Windows. path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # default the exclude list for each platform if win: exclude = exclude + [ 'dos', 'dospath', 'mac', 'macpath', 'macfs', 'MACFS', 'posix', 'os2'] # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line by first replacing any "-i" options with the file contents. pos = 1 while pos < len(sys.argv)-1: # last option can not be "-i", so this ensures "pos+1" is in range! if sys.argv[pos] == '-i': try: options = string.split(open(sys.argv[pos+1]).read()) except IOError, why: usage("File name '%s' specified with the -i option can not be read - %s" % (sys.argv[pos+1], why) ) # Replace the '-i' and the filename with the read params. sys.argv[pos:pos+2] = options pos = pos + len(options) - 1 # Skip the name and the included args. pos = pos + 1 # Now parse the command line with the extras inserted. try: opts, args = getopt.getopt(sys.argv[1:], 'a:de:hmo:p:P:qs:wx:l:') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a if o == '-x': exclude.append(a) if o == '-l': addn_link.append(a) if o == '-a': apply(modulefinder.AddPackagePath, tuple(string.split(a,"=", 2))) # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c')) # locations derived from options version = sys.version[:3] if win: extensions_c = 'frozen_extensions.c' if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_h_dir = exec_prefix config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') if win: frozendllmain_c = os.path.join(exec_prefix, 'Pc\\frozen_dllmain.c') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_h_dir = os.path.join(exec_prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') frozendllmain_c = os.path.join(binlib, 'frozen_dllmain.c') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + config_h_dir] # sanity check of directories and files check_dirs = [prefix, exec_prefix, binlib, incldir] if not win: check_dirs = check_dirs + extensions # These are not directories on Windows. for dir in check_dirs: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources + extensions # extensions are files on Windows. else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that file arguments exist for arg in args: if arg == '-m': break # if user specified -m on the command line before _any_ # file names, then nothing should be checked (as the # very first file should be a module name) if modargs: break if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' if odir: base = os.path.join(odir, '') frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) if win: extensions_c = os.path.join(odir, extensions_c) # Handle special entry point requirements # (on Windows, some frozen programs do not use __main__, but # import the module directly. Eg, DLLs, Services, etc custom_entry_point = None # Currently only used on Windows python_entry_is_main = 1 # Is the entry point called __main__? # handle -s option on Windows if win: import winmakemakefile try: custom_entry_point, python_entry_is_main = \ winmakemakefile.get_custom_entry_point(subsystem) except ValueError, why: usage(why) # Actual work starts here... # collect all modules of the program dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug, exclude) if win and subsystem=='service': # If a Windows service, then add the "built-in" module. mod = mf.add_module("servicemanager") mod.__file__="dummy.pyd" # really built-in to the resulting EXE for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) # Add the main script as either __main__, or the actual module name. if python_entry_is_main: mf.run_script(scriptfile) else: if modargs: mf.import_hook(scriptfile) else: mf.load_file(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules files = makefreeze.makefreeze(base, dict, debug, custom_entry_point) # look for unfrozen modules (builtin and of unknown origin) builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) # search for unknown modules in extensions directories (not on Windows) addfiles = [] frozen_extensions = [] # Windows list of modules. if unknown or (not win and builtins): if not win: addfiles, addmods = \ checkextensions.checkextensions(unknown+builtins, extensions) for mod in addmods: if mod in unknown: unknown.remove(mod) builtins.append(mod) else: # Do the windows thang... import checkextensions_win32 # Get a list of CExtension instances, each describing a module # (including its source files) frozen_extensions = checkextensions_win32.checkextensions( unknown, extensions) for mod in frozen_extensions: unknown.remove(mod.name) # report unknown modules if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile, checkextensions_win32 checkextensions_win32.write_extension_table(extensions_c, frozen_extensions) # Create a module definition for the bootstrap C code. xtras = [frozenmain_c, os.path.basename(frozen_c), frozendllmain_c, os.path.basename(extensions_c)] + files maindefn = checkextensions_win32.CExtension( '__main__', xtras ) frozen_extensions.append( maindefn ) outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), frozen_extensions, os.path.basename(target)) finally: outfp.close() return # generate config.c and Makefile builtins.sort() infp = open(config_c_in) outfp = bkfile.open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ files + supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] outfp = bkfile.open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] exclude = [] # settable with -x option addn_link = [] # settable with -l, but only honored under Windows. path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # default the exclude list for each platform if win: exclude = exclude + [ 'dos', 'dospath', 'mac', 'macpath', 'macfs', 'MACFS', 'posix', 'os2'] # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line by first replacing any "-i" options with the file contents. pos = 1 while pos < len(sys.argv)-1: # last option can not be "-i", so this ensures "pos+1" is in range! if sys.argv[pos] == '-i': try: options = string.split(open(sys.argv[pos+1]).read()) except IOError, why: usage("File name '%s' specified with the -i option can not be read - %s" % (sys.argv[pos+1], why) ) # Replace the '-i' and the filename with the read params. sys.argv[pos:pos+2] = options pos = pos + len(options) - 1 # Skip the name and the included args. pos = pos + 1 # Now parse the command line with the extras inserted. try: opts, args = getopt.getopt(sys.argv[1:], 'a:de:hmo:p:P:qs:wx:l:') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a if o == '-x': exclude.append(a) if o == '-l': addn_link.append(a) if o == '-a': apply(modulefinder.AddPackagePath, tuple(string.split(a,"=", 2))) # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c')) # locations derived from options version = sys.version[:3] if win: extensions_c = 'frozen_extensions.c' if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_h_dir = exec_prefix config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') if win: frozendllmain_c = os.path.join(exec_prefix, 'Pc\\frozen_dllmain.c') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_h_dir = os.path.join(exec_prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') frozendllmain_c = os.path.join(binlib, 'frozen_dllmain.c') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + config_h_dir] # sanity check of directories and files check_dirs = [prefix, exec_prefix, binlib, incldir] if not win: check_dirs = check_dirs + extensions # These are not directories on Windows. for dir in check_dirs: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources + extensions # extensions are files on Windows. else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that file arguments exist for arg in args: if arg == '-m': break # if user specified -m on the command line before _any_ # file names, then nothing should be checked (as the # very first file should be a module name) if modargs: break if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' if odir: base = os.path.join(odir, '') frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) if win: extensions_c = os.path.join(odir, extensions_c) # Handle special entry point requirements # (on Windows, some frozen programs do not use __main__, but # import the module directly. Eg, DLLs, Services, etc custom_entry_point = None # Currently only used on Windows python_entry_is_main = 1 # Is the entry point called __main__? # handle -s option on Windows if win: import winmakemakefile try: custom_entry_point, python_entry_is_main = \ winmakemakefile.get_custom_entry_point(subsystem) except ValueError, why: usage(why) # Actual work starts here... # collect all modules of the program dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug, exclude) if win and subsystem=='service': # If a Windows service, then add the "built-in" module. mod = mf.add_module("servicemanager") mod.__file__="dummy.pyd" # really built-in to the resulting EXE for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) # Add the main script as either __main__, or the actual module name. if python_entry_is_main: mf.run_script(scriptfile) else: mf.load_file(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules files = makefreeze.makefreeze(base, dict, debug, custom_entry_point) # look for unfrozen modules (builtin and of unknown origin) builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) # search for unknown modules in extensions directories (not on Windows) addfiles = [] frozen_extensions = [] # Windows list of modules. if unknown or (not win and builtins): if not win: addfiles, addmods = \ checkextensions.checkextensions(unknown+builtins, extensions) for mod in addmods: if mod in unknown: unknown.remove(mod) builtins.append(mod) else: # Do the windows thang... import checkextensions_win32 # Get a list of CExtension instances, each describing a module # (including its source files) frozen_extensions = checkextensions_win32.checkextensions( unknown, extensions) for mod in frozen_extensions: unknown.remove(mod.name) # report unknown modules if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile, checkextensions_win32 checkextensions_win32.write_extension_table(extensions_c, frozen_extensions) # Create a module definition for the bootstrap C code. xtras = [frozenmain_c, os.path.basename(frozen_c), frozendllmain_c, os.path.basename(extensions_c)] + files maindefn = checkextensions_win32.CExtension( '__main__', xtras ) frozen_extensions.append( maindefn ) outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), frozen_extensions, os.path.basename(target)) finally: outfp.close() return # generate config.c and Makefile builtins.sort() infp = open(config_c_in) outfp = bkfile.open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ files + supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] outfp = bkfile.open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
14,475
def do_updateEvt(self, event): (what, message, when, where, modifiers) = event wid = Win.WhichWindow(message) if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_rawupdate(wid, event) else: if wid: wid.HideWindow() import sys sys.stderr.write("XXX killed unknown (crashed?) Python window.\n") else: MacOS.HandleEvent(event)
def do_updateEvt(self, event): (what, message, when, where, modifiers) = event wid = Win.WhichWindow(message) if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_rawupdate(wid, event) else: if KILLUNKNOWNWINDOWS and wid: wid.HideWindow() import sys sys.stderr.write("XXX killed unknown (crashed?) Python window.\n") else: MacOS.HandleEvent(event)
14,476
def retry_http_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_http(newurl)
def retry_http_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_http(newurl)
14,477
def _decode_msg(self, msg): seqno = self.decode_seqno(msg[:self.SEQNO_ENC_LEN]) msg = msg[self.SEQNO_ENC_LEN:] parts = msg.split(" ", 2) if len(parts) == 1: cmd = msg arg = '' else: cmd = parts[0] arg = parts[1] return cmd, arg, seqno
def _decode_msg(self, msg): seqno = self.decode_seqno(msg[:self.SEQNO_ENC_LEN]) msg = msg[self.SEQNO_ENC_LEN:] parts = msg.split(" ", 1) if len(parts) == 1: cmd = msg arg = '' else: cmd = parts[0] arg = parts[1] return cmd, arg, seqno
14,478
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" _cleanup() p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
14,479
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.dup2(p2cread, 0) os.dup2(c2pwrite, 1) if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
14,480
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
14,481
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None # Child not completed yet _active.append(self)
14,482
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" w, r = os.popen2(cmd, mode, bufsize) return r, w
del Popen3, Popen4, _active, _cleanup def popen2(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" w, r = os.popen2(cmd, mode, bufsize) return r, w
14,483
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" w, r = os.popen2(cmd, mode, bufsize) return r, w
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" w, r = os.popen2(cmd, mode, bufsize) return r, w
14,484
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 0, bufsize) return inst.fromchild, inst.tochild
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 0, bufsize) return inst.fromchild, inst.tochild
14,485
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" w, r, e = os.popen3(cmd, mode, bufsize) return r, w, e
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" w, r, e = os.popen3(cmd, mode, bufsize) return r, w, e
14,486
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 1, bufsize) return inst.fromchild, inst.tochild, inst.childerr
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 1, bufsize) return inst.fromchild, inst.tochild, inst.childerr
14,487
def popen4(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout_stderr, child_stdin) are returned.""" w, r = os.popen4(cmd, mode, bufsize) return r, w
def popen4(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout_stderr, child_stdin) are returned.""" w, r = os.popen4(cmd, mode, bufsize) return r, w
14,488
def run (self): self.mkpath(self.install_dir) for f in self.data_files: if type(f) == StringType: # it's a simple file, so copy it if self.warn_dir: self.warn("setup script did not provide a directory for " "'%s' -- installing right in '%s'" % (f, self.install_dir)) (out, _) = self.copy_file(f, self.install_dir) self.outfiles.append(out) else: # it's a tuple with path to install to and a list of files dir = f[0] if not os.path.isabs(dir): dir = os.path.join(self.install_dir, dir) elif self.root: dir = change_root(self.root, dir) self.mkpath(dir) for data in f[1]: (out, _) = self.copy_file(data, dir) self.outfiles.append(out)
def run (self): self.mkpath(self.install_dir) for f in self.data_files: if type(f) == StringType: # it's a simple file, so copy it if self.warn_dir: self.warn("setup script did not provide a directory for " "'%s' -- installing right in '%s'" % (f, self.install_dir)) (out, _) = self.copy_file(f, self.install_dir) self.outfiles.append(out) else: # it's a tuple with path to install to and a list of files dir = convert_path(f[0]) if not os.path.isabs(dir): dir = os.path.join(self.install_dir, dir) elif self.root: dir = change_root(self.root, dir) self.mkpath(dir) for data in f[1]: (out, _) = self.copy_file(data, dir) self.outfiles.append(out)
14,489
def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", prefix=template, dir=gettempdir()): """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to os.fdopen (default "w+b"). 'bufsize' -- the buffer size argument to os.fdopen (default -1). The file is created as mkstemp() would do it. Returns a file object; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed. """ if 'b' in mode: flags = _bin_openflags else: flags = _text_openflags # Setting O_TEMPORARY in the flags causes the OS to delete # the file when it is closed. This is only supported by Windows. if _os.name == 'nt': flags |= _os.O_TEMPORARY (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) file = _os.fdopen(fd, mode, bufsize) return _TemporaryFileWrapper(file, name)
def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", prefix=template, dir=gettempdir()): """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to os.fdopen (default "w+b"). 'bufsize' -- the buffer size argument to os.fdopen (default -1). The file is created as mkstemp() would do it. Returns a file object; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed. """ if 'b' in mode: flags = _bin_openflags else: flags = _text_openflags # Setting O_TEMPORARY in the flags causes the OS to delete # the file when it is closed. This is only supported by Windows. if _os.name == 'nt': flags |= _os.O_TEMPORARY (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) file = _os.fdopen(fd, mode, bufsize) return _TemporaryFileWrapper(file, name)
14,490
# Look for a machine, default, or macdef top-level keyword
# Look for a machine, default, or macdef top-level keyword
14,491
# Look for a machine, default, or macdef top-level keyword
# Look for a machine, default, or macdef top-level keyword
14,492
def __init__ (self, verbose=0, dry_run=0, force=0):
def __init__ (self, verbose=0, dry_run=0, force=0):
14,493
def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
14,494
def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
14,495
def link_shared_lib (self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
def link_shared_lib (self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
14,496
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=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'.""" if libraries is None: libraries = [] if library_dirs is None: library_dirs = [] lib_opts = gen_lib_options (self, self.library_dirs + library_dirs, self.libraries + libraries)
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=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'.""" if libraries is None: libraries = [] if library_dirs is None: library_dirs = [] lib_opts = gen_lib_options (self, self.library_dirs + library_dirs, self.libraries + libraries)
14,497
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=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'.""" if libraries is None: libraries = [] if library_dirs is None: library_dirs = [] lib_opts = gen_lib_options (self, self.library_dirs + library_dirs, self.libraries + libraries)
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=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'.""" if libraries is None: libraries = [] if library_dirs is None: library_dirs = [] lib_opts = gen_lib_options (self, self.library_dirs + library_dirs, self.libraries + libraries)
14,498
def newtodolink(self, url, origin): if self.todo.has_key(url): self.todo[url].append(origin) self.note(3, " Seen todo link %s", url) else: self.todo[url] = [origin] self.note(3, " New todo link %s", url)
def newtodolink(self, url, origin): if self.todo.has_key(url): if origin not in self.todo[url]: self.todo[url].append(origin) self.note(3, " Seen todo link %s", url) else: self.todo[url] = [origin] self.note(3, " New todo link %s", url)
14,499