bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def _do_under_lines(i, t_off, tx): y = tx.XtraState.cur_y - i*tx.XtraState.style.leading - tx.XtraState.f.fontSize/8.0 # 8.0 factor copied from para.py text = join(tx.lines[i][1]) textlen = tx._canvas.stringWidth(text, tx._fontname, tx._fontsize) tx._canvas.line(t_off, y, t_off+textlen, y)
def _do_under_lines(i, t_off, tx): y = tx.XtraState.cur_y - i*tx.XtraState.style.leading - tx.XtraState.f.fontSize/8.0 # 8.0 factor copied from para.py text = join(tx.XtraState.lines[i][1]) textlen = tx._canvas.stringWidth(text, tx._fontname, tx._fontsize) tx._canvas.line(t_off, y, t_off+textlen, y)
4,500
def cvs_checkout(d,u): recursive_rmdir(d) cvs = find_exe('cvs') if cvs is None: print "Can't find cvs anywhere on the path" os.exit(1) have_tmp = os.path.isdir(_tmp) os.makedirs(d) os.environ['HOME']=d os.environ['CVSROOT']=':pserver:anonymous@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' os.chdir(d) f = open(os.path.join(d,'.cvspass'),'w') f.write(_cvspass+'\n') f.close() i=os.popen(cvs+' -z7 -d:pserver:anonymous@cvs.reportlab.sourceforge.net:/cvsroot/reportlab co reportlab','r') print i.read() i = i.close() if i is not None: print 'there was an error during the download phase' sys.exit(1)
def cvs_checkout(d): recursive_rmdir(d) cvs = find_exe('cvs') if cvs is None: print "Can't find cvs anywhere on the path" os.exit(1) have_tmp = os.path.isdir(_tmp) os.makedirs(d) os.environ['HOME']=d os.environ['CVSROOT']=':pserver:anonymous@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' os.chdir(d) f = open(os.path.join(d,'.cvspass'),'w') f.write(_cvspass+'\n') f.close() i=os.popen(cvs+' -z7 -d:pserver:anonymous@cvs.reportlab.sourceforge.net:/cvsroot/reportlab co reportlab','r') print i.read() i = i.close() if i is not None: print 'there was an error during the download phase' sys.exit(1)
4,501
def _calcValueStep(self): '''Calculate _valueStep for the axis or get from valueStep.'''
def _calcValueStep(self): '''Calculate _valueStep for the axis or get from valueStep.'''
4,502
def inForm(self): """specify that we are in a form xobject (disable page features, etc)""" if self.inObject not in ["form", None]: raise ValueError, "can't go in form already in object %s" % self.inObject self.inObject = "form" # don't need to do anything else, I think...
def inForm(self): """specify that we are in a form xobject (disable page features, etc)""" self.inObject = "form" # don't need to do anything else, I think...
4,503
def registerTypeFace(face): assert isinstance(face, TypeFace), 'Not a TypeFace: %s' % face _typefaces[face.name] = face # HACK - bold/italic do not apply for type 1, so egister # all combinations of mappings. from reportlab.lib import fonts ttname = string.lower(face.name) if not face.name in standardFonts: fonts.addMapping(ttname, 0, 0, face.name) fonts.addMapping(ttname, 1, 0, face.name) fonts.addMapping(ttname, 0, 1, face.name) fonts.addMapping(ttname, 1, 1, face.name)
def registerTypeFace(face): assert isinstance(face, TypeFace), 'Not a TypeFace: %s' % face _typefaces[face.name] = face # HACK - bold/italic do not apply for type 1, so egister # all combinations of mappings. from reportlab.lib import fonts ttname = string.lower(face.name) if not face.name in standardFonts: fonts.addMapping(ttname, 0, 0, face.name) fonts.addMapping(ttname, 1, 0, face.name) fonts.addMapping(ttname, 0, 1, face.name) fonts.addMapping(ttname, 1, 1, face.name)
4,504
def __init__(self,validate=None,desc=None,initial=None, **kw): self.validate = validate or isAnything self.desc = desc self.initial = initial for k,v in kw.items(): setattr(self,k,v)
def __init__(self,validate=None,desc=None,initial=None, **kw): self.validate = validate or isAnything self.desc = desc self._initial = initial for k,v in kw.items(): setattr(self,k,v)
4,505
def __init__(self, data, colWidths=None, rowHeights=None, style=None, repeatRows=0, repeatCols=0, splitByRow=1, emptyTableAction=None): self.hAlign = 'CENTER' self.vAlign = 'MIDDLE' if type(data) not in _SeqTypes: raise ValueError, "%s invalid data type" % self.identity() self._nrows = nrows = len(data) self._cellvalues = [] if nrows: self._ncols = ncols = max(map(_rowLen,data)) elif colWidths: ncols = len(colWidths) else: ncols = 0 if not emptyTableAction: emptyTableAction = rl_config.emptyTableAction if not (nrows and ncols): if emptyTableAction=='error': raise ValueError, "%s must have at least a row and column" % self.identity() elif emptyTableAction=='indicate': self.__class__ = Preformatted global _emptyTableStyle if '_emptyTableStyle' not in globals().keys(): _emptyTableStyle = ParagraphStyle('_emptyTableStyle') _emptyTableStyle.textColor = colors.red _emptyTableStyle.backColor = colors.yellow Preformatted.__init__(self,'%s(%d,%d)' % (self.__class__.__name__,nrows,ncols), _emptyTableStyle) elif emptyTableAction=='ignore': self.__class__ = Spacer Spacer.__init__(self,0,0) else: raise ValueError, '%s bad emptyTableAction: "%s"' % (self.identity(),emptyTableAction) return
def __init__(self, data, colWidths=None, rowHeights=None, style=None, repeatRows=0, repeatCols=0, splitByRow=1, emptyTableAction=None): self.hAlign = 'CENTER' self.vAlign = 'MIDDLE' if type(data) not in _SeqTypes: raise ValueError, "%s invalid data type" % self.identity() self._nrows = nrows = len(data) self._cellvalues = [] if nrows: self._ncols = ncols = max(map(_rowLen,data)) elif colWidths: ncols = len(colWidths) else: ncols = 0 if not emptyTableAction: emptyTableAction = rl_config.emptyTableAction if not (nrows and ncols): if emptyTableAction=='error': raise ValueError, "%s must have at least a row and column" % self.identity() elif emptyTableAction=='indicate': self.__class__ = Preformatted global _emptyTableStyle if '_emptyTableStyle' not in globals().keys(): _emptyTableStyle = ParagraphStyle('_emptyTableStyle') _emptyTableStyle.textColor = colors.red _emptyTableStyle.backColor = colors.yellow Preformatted.__init__(self,'%s(%d,%d)' % (self.__class__.__name__,nrows,ncols), _emptyTableStyle) elif emptyTableAction=='ignore': self.__class__ = Spacer Spacer.__init__(self,0,0) else: raise ValueError, '%s bad emptyTableAction: "%s"' % (self.identity(),emptyTableAction) return
4,506
def identity(self, maxLen=30): '''Identify our selves as well as possible''' vx = None nr = getattr(self,'_nrows','unknown') nc = getattr(self,'_ncols','unknown') cv = self._cellvalues if cv and 'unknown' not in (nr,nc): b = 0 for i in xrange(nr): for j in xrange(nc): v = cv[i][j] t = type(v) if t in _SeqTypes or isinstance(v,Flowable): if not t in _SeqTypes: v = (v,) r = '' for vij in v: r = vij.identity(maxLen) if r and r[-4:]!='>...': break if r and r[-4:]!='>...': ix, jx, vx, b = i, j, r, 1 else: v = v is None and '' or str(v) ix, jx, vx = i, j, v b = (vx and t is StringType) and 1 or 0 if maxLen: vx = vx[:maxLen] if b: break if b: break if vx: vx = ' with cell(%d,%d) containing\n%s' % (ix,jx,repr(vx)) else: vx = '...'
def identity(self, maxLen=30): '''Identify our selves as well as possible''' vx = None nr = getattr(self,'_nrows','unknown') nc = getattr(self,'_ncols','unknown') cv = getattr(self,'_cellvalues',None) if cv and 'unknown' not in (nr,nc): b = 0 for i in xrange(nr): for j in xrange(nc): v = cv[i][j] t = type(v) if t in _SeqTypes or isinstance(v,Flowable): if not t in _SeqTypes: v = (v,) r = '' for vij in v: r = vij.identity(maxLen) if r and r[-4:]!='>...': break if r and r[-4:]!='>...': ix, jx, vx, b = i, j, r, 1 else: v = v is None and '' or str(v) ix, jx, vx = i, j, v b = (vx and t is StringType) and 1 or 0 if maxLen: vx = vx[:maxLen] if b: break if b: break if vx: vx = ' with cell(%d,%d) containing\n%s' % (ix,jx,repr(vx)) else: vx = '...'
4,507
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
4,508
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
4,509
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) os.chdir(cwd) sys.path = opath return objects
4,510
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
4,511
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.replace(prefix, os.sep, '.') modNames = glob.glob(pattern) modNames = filter(lambda m:string.find(m, '__init__.py') == -1, modNames) # Make module names fully qualified. for i in range(len(modNames)): modNames[i] = prefix + '.' + modNames[i][:string.find(modNames[i], '.')] for mName in modNames: module = __import__(mName) # Get the 'real' (leaf) module # (__import__ loads only the top-level one). if string.find(mName, '.') != -1: for part in string.split(mName, '.')[1:]: module = getattr(module, part) # Find the objects in the module's content. modContentNames = dir(module) # Handle modules. if typ == types.ModuleType: if string.find(module.__name__, 'reportlab') > -1: objects.append((mName, module)) continue for n in modContentNames: obj = eval(mName + '.' + n) # Handle functions and classes. if typ in (types.FunctionType, types.ClassType): if type(obj) == typ: objects.append((mName, obj)) # Handle methods. elif typ == types.MethodType: if type(obj) == types.ClassType: for m in dir(obj): a = getattr(obj, m) if type(a) == typ: cName = obj.__name__ objects.append(("%s.%s" % (mName, cName), a)) del sys.path[0] return objects
4,512
def _writeLogFile(self, objType): "Write log file for different kind of documentable objects." cwd = os.getcwd()
def _writeLogFile(self, objType): "Write log file for different kind of documentable objects." cwd = os.getcwd()
4,513
def _writeLogFile(self, objType): "Write log file for different kind of documentable objects." cwd = os.getcwd()
def _writeLogFile(self, objType): "Write log file for different kind of documentable objects." cwd = os.getcwd()
4,514
def makeSuite(): suite = unittest.TestSuite() suite.addTest(DocstringTestCase('test1')) suite.addTest(DocstringTestCase('test2')) suite.addTest(DocstringTestCase('test3')) suite.addTest(DocstringTestCase('test4')) return suite
def makeSuite(): suite = unittest.TestSuite() suite.addTest(DocstringTestCase('test1')) suite.addTest(DocstringTestCase('test2')) suite.addTest(DocstringTestCase('test3')) suite.addTest(DocstringTestCase('test4')) return suite
4,515
def makeSuite(): suite = unittest.TestSuite() suite.addTest(DocstringTestCase('test1')) suite.addTest(DocstringTestCase('test2')) suite.addTest(DocstringTestCase('test3')) suite.addTest(DocstringTestCase('test4')) return suite
defmakeSuite():suite=unittest.TestSuite()suite.addTest(DocstringTestCase('test1'))suite.addTest(DocstringTestCase('test2'))suite.addTest(DocstringTestCase('test3'))suite.addTest(DocstringTestCase('test4'))returnsuite
4,516
def __getitem__(self, index): try: return self._children[index] except KeyError: Klass = self._prototype if Klass in _ItemWrapper.keys(): WKlass = _ItemWrapper[Klass] else: class WKlass(Klass): def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name) _ItemWrapper[Klass] = WKlass
def __getitem__(self, index): try: return self._children[index] except KeyError: Klass = self._prototype if _ItemWrapper.has_key(Klass): WKlass = _ItemWrapper[Klass] else: class WKlass(Klass): def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name) _ItemWrapper[Klass] = WKlass
4,517
def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name)
def __getattr__(self,name): try: return self.__class__.__bases__[0].__getattr__(self,name) except: return getattr(self._parent,name)
4,518
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
4,519
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
4,520
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
4,521
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
4,522
def run(): started = time.time() canv = canvas.Canvas('odyssey.pdf') canv.setPageCompression(0) drawPageFrame(canv) #do some title page stuff canv.setFont("Times-Bold", 36) canv.drawCentredString(0.5 * A4[0], 7 * inch, "Homer's Odyssey") canv.setFont("Times-Bold", 18) canv.drawCentredString(0.5 * A4[0], 5 * inch, "Translated by Samuel Burton") canv.setFont("Times-Bold", 12) tx = canv.beginText(left_margin, 3 * inch) tx.textLine("This is a demo-cum-benchmark for PDFgen. It renders the complete text of Homer's Odyssey") tx.textLine("from a text file. On my humble P266, it does 77 pages per secondwhile creating a 238 page") tx.textLine("document. If it is asked to computer text metrics, measuring the width of each word as ") tx.textLine("one would for paragraph wrapping, it still manages 22 pages per second.") tx.textLine("") tx.textLine("Andy Robinson, Robinson Analytics Ltd.") canv.drawText(tx) canv.showPage() #on with the text... drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) data = open('odyssey.txt','r').readlines() for line in data: #this just does it the fast way... tx.textLine(line) #this forces it to do text metrics, which would be the slow #part if we were wrappng paragraphs. #canv.textOut(line) #canv.textLine('') #page breaking y = tx.getY() #get y coordinate if y < bottom_margin + 0.5*inch: canv.drawText(tx) canv.showPage() drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) #page pg = canv.getPageNumber() if pg % 10 == 0: print 'formatted page %d' % canv.getPageNumber() if tx: canv.drawText(tx) canv.showPage() drawPageFrame(canv) print 'about to write to disk...' canv.save() finished = time.time() elapsed = finished - started pages = canv.getPageNumber() speed = pages / elapsed print '%d pages in %0.2f seconds = %0.2f pages per second' % ( pages, elapsed, speed)
def run(): started = time.time() canv = canvas.Canvas('odyssey.pdf') canv.setPageCompression(0) drawPageFrame(canv) #do some title page stuff canv.setFont("Times-Bold", 36) canv.drawCentredString(0.5 * A4[0], 7 * inch, "Homer's Odyssey") canv.setFont("Times-Bold", 18) canv.drawCentredString(0.5 * A4[0], 5 * inch, "Translated by Samuel Burton") canv.setFont("Times-Bold", 12) tx = canv.beginText(left_margin, 3 * inch) tx.textLine("This is a demo-cum-benchmark for PDFgen. It renders the complete text of Homer's Odyssey") tx.textLine("from a text file. On my humble P266, it does 77 pages per secondwhile creating a 238 page") tx.textLine("document. If it is asked to computer text metrics, measuring the width of each word as ") tx.textLine("one would for paragraph wrapping, it still manages 22 pages per second.") tx.textLine("") tx.textLine("Andy Robinson, Robinson Analytics Ltd.") canv.drawText(tx) canv.showPage() #on with the text... drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) for fn in ('Odyssey.full.txt','Odyssey.txt'): if os.path.isfile(fn): break data = open(fn,'r').readlines() for line in data: #this just does it the fast way... tx.textLine(line) #this forces it to do text metrics, which would be the slow #part if we were wrappng paragraphs. #canv.textOut(line) #canv.textLine('') #page breaking y = tx.getY() #get y coordinate if y < bottom_margin + 0.5*inch: canv.drawText(tx) canv.showPage() drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) #page pg = canv.getPageNumber() if pg % 10 == 0: print 'formatted page %d' % canv.getPageNumber() if tx: canv.drawText(tx) canv.showPage() drawPageFrame(canv) print 'about to write to disk...' canv.save() finished = time.time() elapsed = finished - started pages = canv.getPageNumber() speed = pages / elapsed print '%d pages in %0.2f seconds = %0.2f pages per second' % ( pages, elapsed, speed)
4,523
def run(): started = time.time() canv = canvas.Canvas('odyssey.pdf') canv.setPageCompression(0) drawPageFrame(canv) #do some title page stuff canv.setFont("Times-Bold", 36) canv.drawCentredString(0.5 * A4[0], 7 * inch, "Homer's Odyssey") canv.setFont("Times-Bold", 18) canv.drawCentredString(0.5 * A4[0], 5 * inch, "Translated by Samuel Burton") canv.setFont("Times-Bold", 12) tx = canv.beginText(left_margin, 3 * inch) tx.textLine("This is a demo-cum-benchmark for PDFgen. It renders the complete text of Homer's Odyssey") tx.textLine("from a text file. On my humble P266, it does 77 pages per secondwhile creating a 238 page") tx.textLine("document. If it is asked to computer text metrics, measuring the width of each word as ") tx.textLine("one would for paragraph wrapping, it still manages 22 pages per second.") tx.textLine("") tx.textLine("Andy Robinson, Robinson Analytics Ltd.") canv.drawText(tx) canv.showPage() #on with the text... drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) data = open('odyssey.txt','r').readlines() for line in data: #this just does it the fast way... tx.textLine(line) #this forces it to do text metrics, which would be the slow #part if we were wrappng paragraphs. #canv.textOut(line) #canv.textLine('') #page breaking y = tx.getY() #get y coordinate if y < bottom_margin + 0.5*inch: canv.drawText(tx) canv.showPage() drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) #page pg = canv.getPageNumber() if pg % 10 == 0: print 'formatted page %d' % canv.getPageNumber() if tx: canv.drawText(tx) canv.showPage() drawPageFrame(canv) print 'about to write to disk...' canv.save() finished = time.time() elapsed = finished - started pages = canv.getPageNumber() speed = pages / elapsed print '%d pages in %0.2f seconds = %0.2f pages per second' % ( pages, elapsed, speed)
def run(): started = time.time() canv = canvas.Canvas('odyssey.pdf') canv.setPageCompression(0) drawPageFrame(canv) #do some title page stuff canv.setFont("Times-Bold", 36) canv.drawCentredString(0.5 * A4[0], 7 * inch, "Homer's Odyssey") canv.setFont("Times-Bold", 18) canv.drawCentredString(0.5 * A4[0], 5 * inch, "Translated by Samuel Burton") canv.setFont("Times-Bold", 12) tx = canv.beginText(left_margin, 3 * inch) tx.textLine("This is a demo-cum-benchmark for PDFgen. It renders the complete text of Homer's Odyssey") tx.textLine("from a text file. On my humble P266, it does 77 pages per secondwhile creating a 238 page") tx.textLine("document. If it is asked to computer text metrics, measuring the width of each word as ") tx.textLine("one would for paragraph wrapping, it still manages 22 pages per second.") tx.textLine("") tx.textLine("Andy Robinson, Robinson Analytics Ltd.") canv.drawText(tx) canv.showPage() #on with the text... drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) data = open('odyssey.txt','r').readlines() for line in data: #this just does it the fast way... tx.textLine(line) #this forces it to do text metrics, which would be the slow #part if we were wrappng paragraphs. #canv.textOut(line) #canv.textLine('') #page breaking y = tx.getY() #get y coordinate if y < bottom_margin + 0.5*inch: canv.drawText(tx) canv.showPage() drawPageFrame(canv) canv.setFont('Times-Roman', 12) tx = canv.beginText(left_margin, top_margin - 0.5*inch) #page pg = canv.getPageNumber() if pg % 10 == 0: print 'formatted page %d' % canv.getPageNumber() if tx: canv.drawText(tx) canv.showPage() drawPageFrame(canv) print 'about to write to disk...' canv.save() finished = time.time() elapsed = finished - started pages = canv.getPageNumber()-1 speed = pages / elapsed print '%d pages in %0.2f seconds = %0.2f pages per second' % ( pages, elapsed, speed)
4,524
def handle_pageEnd(self): ''' show the current page check the next page template hang a page begin ''' #detect infinite loops... if self._curPageFlowableCount == 0: self._emptyPages = self._emptyPages + 1 else: self._emptyPages = 0 if self._emptyPages >= self._emptyPagesAllowed: if 1: ident = "More than %d pages generated without content - halting layout. Likely that a flowable is too large for any frame." % self._emptyPagesAllowed #leave to keep apart from the raise raise LayoutError(ident) else: pass #attempt to restore to good state else: if self._onProgress: self._onProgress('PAGE', self.canv.getPageNumber()) self.pageTemplate.afterDrawPage(self.canv, self) self.pageTemplate.onPageEnd(self.canv, self) self.afterPage() self.canv.setPageRotation(getattr(self.pageTemplate,'rotation',0) self.canv.showPage()
def handle_pageEnd(self): ''' show the current page check the next page template hang a page begin ''' #detect infinite loops... if self._curPageFlowableCount == 0: self._emptyPages = self._emptyPages + 1 else: self._emptyPages = 0 if self._emptyPages >= self._emptyPagesAllowed: if 1: ident = "More than %d pages generated without content - halting layout. Likely that a flowable is too large for any frame." % self._emptyPagesAllowed #leave to keep apart from the raise raise LayoutError(ident) else: pass #attempt to restore to good state else: if self._onProgress: self._onProgress('PAGE', self.canv.getPageNumber()) self.pageTemplate.afterDrawPage(self.canv, self) self.pageTemplate.onPageEnd(self.canv, self) self.afterPage() self.canv.setPageRotation(getattr(self.pageTemplate,'rotation',0)) self.canv.showPage()
4,525
def draw(self): from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY style = self.style lines = self.lines rightIndent = style.rightIndent leftIndent = style.leftIndent leading = style.leading font = style.fontName size = style.fontSize alignment = style.alignment firstindent = style.firstLineIndent c = self.canv escape = c._escape #if debug: # print "FAST", id(self), "page number", c.getPageNumber() height = self.height #if debug: # c.rect(0,0,-1, height-size, fill=1, stroke=1) c.translate(0, height-size) textobject = c.beginText() code = textobject._code #textobject.setTextOrigin(0,firstindent) textobject.setFont(font, size) if style.textColor: textobject.setFillColor(style.textColor) first = 1 y = 0 basicWidth = self.availableWidth - rightIndent count = 0 nlines = len(lines) while count<nlines: (text, length, nwords) = lines[count] count = count+1 thisindent = leftIndent if first: thisindent = firstindent if alignment==TA_LEFT: x = thisindent elif alignment==TA_CENTER: extra = basicWidth - length x = thisindent + extra/2.0 elif alignment==TA_RIGHT: extra = basicWidth - length x = thisindent + extra elif alignment==TA_JUSTIFY: x = thisindent extra = basicWidth - length wordspace = extra*1.0/nwords if count<nlines: # patch from doug@pennatus.com, 9 Nov 2002 # was: textobject.setWordSpace(wordspace) textobject.setWordSpace((extra*1.0/(nwords - 1))) else: textobject.setWordSpace(0.0) textobject.setTextOrigin(x,y) text = escape(text) code.append('(%s) Tj' % text) #textobject.textOut(text) y = y-leading c.drawText(textobject)
def draw(self): from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY style = self.style lines = self.lines rightIndent = style.rightIndent leftIndent = style.leftIndent leading = style.leading font = style.fontName size = style.fontSize alignment = style.alignment firstindent = style.firstLineIndent c = self.canv escape = c._escape #if debug: # print "FAST", id(self), "page number", c.getPageNumber() height = self.height #if debug: # c.rect(0,0,-1, height-size, fill=1, stroke=1) c.translate(0, height-size) textobject = c.beginText() code = textobject._code #textobject.setTextOrigin(0,firstindent) textobject.setFont(font, size) if style.textColor: textobject.setFillColor(style.textColor) first = 1 y = 0 basicWidth = self.availableWidth - rightIndent count = 0 nlines = len(lines) while count<nlines: (text, length, nwords) = lines[count] count = count+1 thisindent = leftIndent if first: thisindent = firstindent if alignment==TA_LEFT: x = thisindent elif alignment==TA_CENTER: extra = basicWidth - length x = thisindent + extra/2.0 elif alignment==TA_RIGHT: extra = basicWidth - length x = thisindent + extra elif alignment==TA_JUSTIFY: x = thisindent if count<nlines: # patch from doug@pennatus.com, 9 Nov 2002 # was: textobject.setWordSpace(wordspace) textobject.setWordSpace((extra*1.0/(nwords - 1))) else: textobject.setWordSpace(0.0) textobject.setTextOrigin(x,y) text = escape(text) code.append('(%s) Tj' % text) #textobject.textOut(text) y = y-leading c.drawText(textobject)
4,526
def draw(self): from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY style = self.style lines = self.lines rightIndent = style.rightIndent leftIndent = style.leftIndent leading = style.leading font = style.fontName size = style.fontSize alignment = style.alignment firstindent = style.firstLineIndent c = self.canv escape = c._escape #if debug: # print "FAST", id(self), "page number", c.getPageNumber() height = self.height #if debug: # c.rect(0,0,-1, height-size, fill=1, stroke=1) c.translate(0, height-size) textobject = c.beginText() code = textobject._code #textobject.setTextOrigin(0,firstindent) textobject.setFont(font, size) if style.textColor: textobject.setFillColor(style.textColor) first = 1 y = 0 basicWidth = self.availableWidth - rightIndent count = 0 nlines = len(lines) while count<nlines: (text, length, nwords) = lines[count] count = count+1 thisindent = leftIndent if first: thisindent = firstindent if alignment==TA_LEFT: x = thisindent elif alignment==TA_CENTER: extra = basicWidth - length x = thisindent + extra/2.0 elif alignment==TA_RIGHT: extra = basicWidth - length x = thisindent + extra elif alignment==TA_JUSTIFY: x = thisindent extra = basicWidth - length wordspace = extra*1.0/nwords if count<nlines: # patch from doug@pennatus.com, 9 Nov 2002 # was: textobject.setWordSpace(wordspace) textobject.setWordSpace((extra*1.0/(nwords - 1))) else: textobject.setWordSpace(0.0) textobject.setTextOrigin(x,y) text = escape(text) code.append('(%s) Tj' % text) #textobject.textOut(text) y = y-leading c.drawText(textobject)
def draw(self): from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY style = self.style lines = self.lines rightIndent = style.rightIndent leftIndent = style.leftIndent leading = style.leading font = style.fontName size = style.fontSize alignment = style.alignment firstindent = style.firstLineIndent c = self.canv escape = c._escape #if debug: # print "FAST", id(self), "page number", c.getPageNumber() height = self.height #if debug: # c.rect(0,0,-1, height-size, fill=1, stroke=1) c.translate(0, height-size) textobject = c.beginText() code = textobject._code #textobject.setTextOrigin(0,firstindent) textobject.setFont(font, size) if style.textColor: textobject.setFillColor(style.textColor) first = 1 y = 0 basicWidth = self.availableWidth - rightIndent count = 0 nlines = len(lines) while count<nlines: (text, length, nwords) = lines[count] count = count+1 thisindent = leftIndent if first: thisindent = firstindent if alignment==TA_LEFT: x = thisindent elif alignment==TA_CENTER: extra = basicWidth - length x = thisindent + extra/2.0 elif alignment==TA_RIGHT: extra = basicWidth - length x = thisindent + extra elif alignment==TA_JUSTIFY: x = thisindent extra = basicWidth - length wordspace = extra*1.0/nwords if count<nlines: # patch from doug@pennatus.com, 9 Nov 2002 # was: textobject.setWordSpace(wordspace) textobject.setWordSpace((extra*1.0/(nwords - 1))) else: textobject.setWordSpace(0.0) textobject.setTextOrigin(x,y) text = escape(text) code.append('(%s) Tj' % text) #textobject.textOut(text) y = y-leading c.drawText(textobject)
4,527
def test(): from pprint import pprint #print test_program; return from reportlab.pdfgen import canvas from reportlab.lib.units import inch fn = "paratest0.pdf" c = canvas.Canvas(fn) test2(c) c.showPage() if 1: remainder = test_program + test_program + test_program laststate = {} while remainder: print "NEW PAGE" c.translate(inch, 8*inch) t = c.beginText() t.setTextOrigin(0,0) p = paragraphEngine() p.resetState(laststate) p.x = 0 p.y = 0 maxwidth = 7*inch maxheight = 500 (formattedprogram, remainder, laststate, height) = p.format(maxwidth, maxheight, remainder) if debug: pprint( formattedprogram )#; return laststate = p.runOpCodes(formattedprogram, c, t) c.drawText(t) c.showPage() print "="*30, "x=", laststate["x"], "y=", laststate["y"] c.save() print fn
def test(): from pprint import pprint #print test_program; return from reportlab.pdfgen import canvas from reportlab.lib.units import inch fn = "paratest0.pdf" c = canvas.Canvas(fn) test2(c) c.showPage() if 1: remainder = test_program + test_program + test_program laststate = {} while remainder: print "NEW PAGE" c.translate(inch, 8*inch) t = c.beginText() t.setTextOrigin(0,0) p = paragraphEngine() p.resetState(laststate) p.x = 0 p.y = 0 maxwidth = 7*inch maxheight = 500 (formattedprogram, remainder, laststate, height) = p.format(maxwidth, maxheight, remainder) if debug: pprint( formattedprogram )#; return laststate = p.runOpCodes(formattedprogram, c, t) c.drawText(t) c.showPage() print "="*30, "x=", laststate["x"], "y=", laststate["y"] c.save() print fn
4,528
def __init__(self): self.objects = [] self.objectPositions = {} self.fonts = MakeType1Fonts()
def __init__(self): self.objects = [] self.objectPositions = {} self.fonts = MakeType1Fonts()
4,529
def add(self, key, obj): self.objectPositions[key] = len(self.objects) # its position self.objects.append(obj) #obj.doc = self return len(self.objects) - 1 # give its position
def add(self, key, obj): self.objectPositions[key] = len(self.objects)+1 # its position self.objects.append(obj) #obj.doc = self return len(self.objects) - 1 # give its position
4,530
def add(self, key, obj): self.objectPositions[key] = len(self.objects) # its position self.objects.append(obj) #obj.doc = self return len(self.objects) - 1 # give its position
def add(self, key, obj): self.objectPositions[key] = len(self.objects) # its position self.objects.append(obj) #obj.doc = self return self.getPosition(key) # give its position
4,531
def addPage(self, page): """adds page and stream at end. Maintains pages list""" #page.buildstream() pos = len(self.objects) # work out where added page.ParentPos = 3 #pages collection page.info = { 'parentpos':3, 'fontdict':self.fontdict, 'contentspos':pos + 2, } self.PageCol.PageList.append(pos+1) self.add('Page%06d'% len(self.PageCol.PageList), page) #self.objects.append(page) self.add('PageStream%06d'% len(self.PageCol.PageList), page.stream) #self.objects.append(page.stream)
def addPage(self, page): """adds page and stream at end. Maintains pages list""" #page.buildstream() pos = len(self.objects) # work out where added page.ParentPos = self.getPosition("PagesTreeRoot") #pages collection page.info = { 'parentpos':3, 'fontdict':self.fontdict, 'contentspos':pos + 2, } self.PageCol.PageList.append(pos+1) self.add('Page%06d'% len(self.PageCol.PageList), page) #self.objects.append(page) self.add('PageStream%06d'% len(self.PageCol.PageList), page.stream) #self.objects.append(page.stream)
4,532
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text,' ') if S[-1]=='': del S[-1] if W!=[] and text[0] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')]) if W!=[]: W.insert(0,n) R.append(W) return R
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text) if S[-1]=='': del S[-1] if W!=[] and text[0] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')]) if W!=[]: W.insert(0,n) R.append(W) return R
4,533
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text,' ') if S[-1]=='': del S[-1] if W!=[] and text[0] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')]) if W!=[]: W.insert(0,n) R.append(W) return R
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text,' ') if S[-1]=='': del S[-1] if W!=[] and text[0] in whitespace: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')]) if W!=[]: W.insert(0,n) R.append(W) return R
4,534
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text,' ') if S[-1]=='': del S[-1] if W!=[] and text[0] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')]) if W!=[]: W.insert(0,n) R.append(W) return R
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text,' ') if S[-1]=='': del S[-1] if W!=[] and text[0] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in whitespace: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')]) if W!=[]: W.insert(0,n) R.append(W) return R
4,535
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text,' ') if S[-1]=='': del S[-1] if W!=[] and text[0] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')]) if W!=[]: W.insert(0,n) R.append(W) return R
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this until we sort out splitting # of paragraphs if text!='': S = split(text,' ') if S[-1]=='': del S[-1] if W!=[] and text[0] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 for w in S[:-1]: W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) W.insert(0,n) R.append(W) W = [] n = 0 w = S[-1] W.append((f,w)) n = n + stringWidth(w, f.fontName, f.fontSize) if text[-1] in [' ','\t']: W.insert(0,n) R.append(W) W = [] n = 0 elif hasattr(f,'cbDefn'): W.append((f,'')) if W!=[]: W.insert(0,n) R.append(W) return R
4,536
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
4,537
def handle_pageEnd(self): ''' show the current page check the next page template hang a page begin ''' #detect infinite loops... if self._curPageFlowableCount == 0: self._emptyPages = self._emptyPages + 1 else: self._emptyPages = 0 if self._emptyPages >= self._emptyPagesAllowed: if 1: raise LayoutError("More than %d pages generated without content - halting layout. Likely that a flowable is too large for any frame." % self._emptyPagesAllowed) else: pass #attempt to restore to good state else: if self._onProgress: self._onProgress('PAGE', self.canv.getPageNumber()) self.pageTemplate.afterDrawPage(self.canv, self) self.pageTemplate.onPageEnd(self.canv, self) self.afterPage() self.canv.showPage()
def handle_pageEnd(self): ''' show the current page check the next page template hang a page begin ''' #detect infinite loops... if self._curPageFlowableCount == 0: self._emptyPages = self._emptyPages + 1 else: self._emptyPages = 0 if self._emptyPages >= self._emptyPagesAllowed: if 1: ident = "More than %d pages generated without content - halting layout. Likely that a flowable is too large for any frame." % self._emptyPagesAllowed raise LayoutError(ident) else: pass #attempt to restore to good state else: if self._onProgress: self._onProgress('PAGE', self.canv.getPageNumber()) self.pageTemplate.afterDrawPage(self.canv, self) self.pageTemplate.onPageEnd(self.canv, self) self.afterPage() self.canv.showPage()
4,538
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.'''
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.'''
4,539
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.'''
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.'''
4,540
def __init__(self,filename,pagesize=(595.27,841.89), bottomup = 1, pageCompression=0 ): """Most of the attributes are private - we will use set/get methods as the preferred interface. Default page size is A4.""" self._filename = filename self._doc = pdfdoc.PDFDocument() self._pagesize = pagesize #self._currentPageHasImages = 0 self._pageTransitionString = '' self._destinations = {} # dictionary of destinations for cross indexing.
def __init__(self,filename,pagesize=(595.27,841.89), bottomup = 1, pageCompression=0 ): """Most of the attributes are private - we will use set/get methods as the preferred interface. Default page size is A4.""" self._filename = filename self._doc = pdfdoc.PDFDocument() self._pagesize = pagesize #self._currentPageHasImages = 0 self._pageTransitionString = '' self._destinations = {} # dictionary of destinations for cross indexing.
4,541
def showPage(self): """This is where the fun happens""" page = pdfdoc.PDFPage() page.pagewidth = self._pagesize[0] page.pageheight = self._pagesize[1] page.hasImages = self._currentPageHasImages page.pageTransitionString = self._pageTransitionString page.setCompression(self._pageCompression) #print stream page.setStream([self._preamble] + self._code) self.setXObjects(page) self.setAnnotations(page) self._doc.addPage(page) #now get ready for the next one self._pageNumber = self._pageNumber + 1 self.restartAccumulators()
def showPage(self): """This is where the fun happens""" page = pdfdoc.PDFPage() page.pagewidth = self._pagesize[0] page.pageheight = self._pagesize[1] page.hasImages = self._currentPageHasImages page.pageTransitionString = self._pageTransitionString page.setCompression(self._pageCompression) #print stream page.setStream([self._preamble] + self._code) self._setXObjects(page) self._setAnnotations(page) self._doc.addPage(page) #now get ready for the next one self._pageNumber = self._pageNumber + 1 self.restartAccumulators()
4,542
def showPage(self): """This is where the fun happens""" page = pdfdoc.PDFPage() page.pagewidth = self._pagesize[0] page.pageheight = self._pagesize[1] page.hasImages = self._currentPageHasImages page.pageTransitionString = self._pageTransitionString page.setCompression(self._pageCompression) #print stream page.setStream([self._preamble] + self._code) self.setXObjects(page) self.setAnnotations(page) self._doc.addPage(page) #now get ready for the next one self._pageNumber = self._pageNumber + 1 self.restartAccumulators()
def showPage(self): """This is where the fun happens""" page = pdfdoc.PDFPage() page.pagewidth = self._pagesize[0] page.pageheight = self._pagesize[1] page.hasImages = self._currentPageHasImages page.pageTransitionString = self._pageTransitionString page.setCompression(self._pageCompression) #print stream page.setStream([self._preamble] + self._code) self.setXObjects(page) self.setAnnotations(page) self._doc.addPage(page) #now get ready for the next one self._pageNumber = self._pageNumber + 1 self.restartAccumulators()
4,543
def setXObjects(self, thing): """for pages and forms, define the XObject dictionary for resources, if needed""" forms = self._formsinuse if forms: xobjectsdict = self._doc.xobjDict(forms) thing.XObjects = xobjectsdict else: thing.XObjects = None
def _setXObjects(self, thing): """for pages and forms, define the XObject dictionary for resources, if needed""" forms = self._formsinuse if forms: xobjectsdict = self._doc.xobjDict(forms) thing.XObjects = xobjectsdict else: thing.XObjects = None
4,544
def bookmarkReference(self, name): """get a reference to a (possibly undefined, possibly unbound) bookmark""" d = self._destinations try: return d[name] except: result = d[name] = pdfdoc.Destination(name) # newly defined, unbound return result
def _bookmarkReference(self, name): """get a reference to a (possibly undefined, possibly unbound) bookmark""" d = self._destinations try: return d[name] except: result = d[name] = pdfdoc.Destination(name) # newly defined, unbound return result
4,545
def bookmarkPage(self, name): """bind a bookmark (destination) to the current page""" # XXXX there are a lot of other ways a bookmark destination can be bound: should be implemented. # XXXX the other ways require tracking of the graphics state.... dest = self.bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fit() dest.setPageRef(pageref) return dest
def bookmarkPage(self, name): """bind a bookmark (destination) to the current page""" # XXXX there are a lot of other ways a bookmark destination can be bound: should be implemented. # XXXX the other ways require tracking of the graphics state.... dest = self._bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fit() dest.setPageRef(pageref) return dest
4,546
def bookmarkHorizontalInPageAbsolute(self, name, yhorizontal): """bind a bookmark (destination to the current page at a horizontal position""" dest = self.bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fith(yhorizontal) dest.setPageRef(pageref) return dest
def bookmarkHorizontalAbsolute(self, name, yhorizontal): """bind a bookmark (destination to the current page at a horizontal position""" dest = self.bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fith(yhorizontal) dest.setPageRef(pageref) return dest
4,547
def bookmarkHorizontalInPageAbsolute(self, name, yhorizontal): """bind a bookmark (destination to the current page at a horizontal position""" dest = self.bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fith(yhorizontal) dest.setPageRef(pageref) return dest
def bookmarkHorizontalInPageAbsolute(self, name, yhorizontal): """bind a bookmark (destination to the current page at a horizontal position""" dest = self._bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fith(yhorizontal) dest.setPageRef(pageref) return dest
4,548
def restartAccumulators(self): self._code = [] # ready for more... self._currentPageHasImages = 1 # for safety... self._formsinuse = [] self._annotationrefs = []
def _restartAccumulators(self): self._code = [] # ready for more... self._currentPageHasImages = 1 # for safety... self._formsinuse = [] self._annotationrefs = []
4,549
def makeForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): """Like showpage, but make a form using accumulated operations instead""" (w,h) = self._pagesize if upperx is None: upperx=w if uppery is None: uppery=h form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery) form.compression = self._pageCompression form.setStreamList([self._preamble] + self._code) # ??? minus preamble (seems to be needed!) self.setXObjects(form) self.setAnnotations(form) self._doc.addForm(name, form) self.restartAccumulators()
def makeForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): """Like showpage, but make a form using accumulated operations instead""" (w,h) = self._pagesize if upperx is None: upperx=w if uppery is None: uppery=h form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery) form.compression = self._pageCompression form.setStreamList([self._preamble] + self._code) # ??? minus preamble (seems to be needed!) self._setXObjects(form) self._setAnnotations(form) self._doc.addForm(name, form) self.restartAccumulators()
4,550
def makeForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): """Like showpage, but make a form using accumulated operations instead""" (w,h) = self._pagesize if upperx is None: upperx=w if uppery is None: uppery=h form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery) form.compression = self._pageCompression form.setStreamList([self._preamble] + self._code) # ??? minus preamble (seems to be needed!) self.setXObjects(form) self.setAnnotations(form) self._doc.addForm(name, form) self.restartAccumulators()
def makeForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): """Like showpage, but make a form using accumulated operations instead""" (w,h) = self._pagesize if upperx is None: upperx=w if uppery is None: uppery=h form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery) form.compression = self._pageCompression form.setStreamList([self._preamble] + self._code) # ??? minus preamble (seems to be needed!) self.setXObjects(form) self.setAnnotations(form) self._doc.addForm(name, form) self._restartAccumulators()
4,551
def textAnnotation(self, contents, Rect=None, addtopage=1, name=None, **kw): if not Rect: (w,h) = self._pagesize# default to whole page (?) Rect = (0,0,w,h) annotation = apply(pdfdoc.TextAnnotation, (Rect, contents), kw) self.addAnnotation(annotation, name, addtopage)
def textAnnotation(self, contents, Rect=None, addtopage=1, name=None, **kw): if not Rect: (w,h) = self._pagesize# default to whole page (?) Rect = (0,0,w,h) annotation = apply(pdfdoc.TextAnnotation, (Rect, contents), kw) self._addAnnotation(annotation, name, addtopage)
4,552
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) kw["Rect"] = Rect kw["Contents"] = contents kw["Destination"] = destination annotation = apply(pdfdoc.LinkAnnotation, (), kw) self.addAnnotation(annotation, name, addtopage)
def linkAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) kw["Rect"] = Rect kw["Contents"] = contents kw["Destination"] = destination annotation = apply(pdfdoc.LinkAnnotation, (), kw) self.addAnnotation(annotation, name, addtopage)
4,553
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) kw["Rect"] = Rect kw["Contents"] = contents kw["Destination"] = destination annotation = apply(pdfdoc.LinkAnnotation, (), kw) self.addAnnotation(annotation, name, addtopage)
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self._bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) kw["Rect"] = Rect kw["Contents"] = contents kw["Destination"] = destination annotation = apply(pdfdoc.LinkAnnotation, (), kw) self.addAnnotation(annotation, name, addtopage)
4,554
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) kw["Rect"] = Rect kw["Contents"] = contents kw["Destination"] = destination annotation = apply(pdfdoc.LinkAnnotation, (), kw) self.addAnnotation(annotation, name, addtopage)
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) kw["Rect"] = Rect kw["Contents"] = contents kw["Destination"] = destination annotation = apply(pdfdoc.LinkAnnotation, (), kw) self._addAnnotation(annotation, name, addtopage)
4,555
def addAnnotation(self, annotation, name=None, addtopage=1): count = self.annotationCount = self.annotationCount+1 if not name: name="NUMBER"+repr(count) self._doc.addAnnotation(name, annotation) if addtopage: self.annotatePage(name)
def _addAnnotation(self, annotation, name=None, addtopage=1): count = self._annotationCount = self._annotationCount+1 if not name: name="NUMBER"+repr(count) self._doc.addAnnotation(name, annotation) if addtopage: self.annotatePage(name)
4,556
def addAnnotation(self, annotation, name=None, addtopage=1): count = self.annotationCount = self.annotationCount+1 if not name: name="NUMBER"+repr(count) self._doc.addAnnotation(name, annotation) if addtopage: self.annotatePage(name)
def addAnnotation(self, annotation, name=None, addtopage=1): count = self.annotationCount = self.annotationCount+1 if not name: name="NUMBER"+repr(count) self._doc.addAnnotation(name, annotation) if addtopage: self._annotatePage(name)
4,557
def annotatePage(self, name): ref = self._doc.refAnnotation(name) self._annotationrefs.append(ref)
def _annotatePage(self, name): ref = self._doc.refAnnotation(name) self._annotationrefs.append(ref)
4,558
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser()("<a/>",%s=%d)' % (k,v)) print >>_logf,'Parser().parse keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser().parse keywords BAD' _dot('E') goodTest('<a></a>',('a', None, [], None)) goodTest('<a></a>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a></a>',['a', None, [], None],MakeMutableTree=1) goodTest('<a/>',('a', None, None, None)) goodTest('<a/>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a/>',['a', None, None, None],MakeMutableTree=1) goodTest('<a/>',['a', {}, [], None],ExpandEmpty=1,MakeMutableTree=1) failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n") goodTest('<a>A<!--comment--></a>',('a', None, ['A'], None)) goodTest('<a>A<!--comment--></a>',('a', {}, ['A'], None),ExpandEmpty=1) goodTest('<a>A<!--comment--></a>', ('a', None, ['A', ('<!--', None, ['comment'], None)], None), ReturnComments=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A<&>'], None)) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A', '<', '&', '>'], None), MergePCData=0) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) goodTest('<!--comment--><a/>',[('<!--',None,['comment'],None),('a', None, None, None)],ReturnComments=1,ReturnList=1) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"Error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n") goodTest('<?work version="1.0" encoding="utf-8"?><a/>',[('<?',{'name':'work'}, ['version="1.0" encoding="utf-8"'],None), ('a', None, None, None)],IgnorePlacementErrors=1,ReturnList=1,ReturnProcessingInstructions=1,ReturnComments=1) goodTest('<a>\nHello\n<b>cruel\n</b>\nWorld\n</a>',('a', None, ['\nHello\n', ('b', None, ['cruel\n'], (('aaa', 2, 3), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 3), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a aname="ANAME" aother="AOTHER">\nHello\n<b bname="BNAME" bother="BOTHER">cruel\n</b>\nWorld\n</a>',('a', {"aname": "ANAME", "aother": "AOTHER"}, ['\nHello\n', ('b', {"bname": "BNAME", "bother": "BOTHER"}, ['cruel\n'], (('aaa', 2, 33), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 33), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a><![CDATA[<a>]]></a>',('a', None, ['<a>'], None)) goodTest('<a><![CDATA[<a>]]></a>',('a', None, [('<![CDATA[', None, ['<a>'], None)], None),ReturnCDATASectionsAsTuples=1) goodTest('''<foo:A xmlns:foo="http://www.foo.org/"><foo:B><foo:C xmlns:foo="http://www.bar.org/"><foo:D>abcd</foo:D></foo:C></foo:B><foo:B/><A>bare A<C>bare C</C><B>bare B</B></A><A xmlns="http://default.reportlab.com/" xmlns:bongo="http://bongo.reportlab.com/">default ns A<bongo:A>bongo A</bongo:A><B>default NS B</B></A></foo:A>''',('{http://www.foo.org/}A', {'xmlns:foo': 'http://www.foo.org/'}, [('{http://www.foo.org/}B', None, [('{http://www.bar.org/}C', {'xmlns:foo': 'http://www.bar.org/'}, [('{http://www.bar.org/}D', None, ['abcd'], None)], None)], None), ('{http://www.foo.org/}B', None, None, None), ('A', None, ['bare A', ('C', None, ['bare C'], None), ('B', None, ['bare B'], None)], None), ('{http://default.reportlab.com/}A', {'xmlns': 'http://default.reportlab.com/', 'xmlns:bongo': 'http://bongo.reportlab.com/'}, ['default ns A', ('{http://bongo.reportlab.com/}A', None, ['bongo A'], None), ('{http://default.reportlab.com/}B', None, ['default NS B'], None)], None)], None),XMLNamespaces=1,ReturnNamespaceAttributes=1) failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1)
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser()("<a/>",%s=%d)' % (k,v)) print >>_logf,'Parser().parse keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser().parse keywords BAD' _dot('E') goodTest('<a></a>',('a', None, [], None)) goodTest('<a></a>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a></a>',['a', None, [], None],MakeMutableTree=1) goodTest('<a/>',('a', None, None, None)) goodTest('<a/>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a/>',['a', None, None, None],MakeMutableTree=1) goodTest('<a/>',['a', {}, [], None],ExpandEmpty=1,MakeMutableTree=1) failTest('</a>',"error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n") goodTest('<a>A<!--comment--></a>',('a', None, ['A'], None)) goodTest('<a>A<!--comment--></a>',('a', {}, ['A'], None),ExpandEmpty=1) goodTest('<a>A<!--comment--></a>', ('a', None, ['A', ('<!--', None, ['comment'], None)], None), ReturnComments=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A<&>'], None)) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A', '<', '&', '>'], None), MergePCData=0) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) goodTest('<!--comment--><a/>',[('<!--',None,['comment'],None),('a', None, None, None)],ReturnComments=1,ReturnList=1) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"Error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n") goodTest('<?work version="1.0" encoding="utf-8"?><a/>',[('<?',{'name':'work'}, ['version="1.0" encoding="utf-8"'],None), ('a', None, None, None)],IgnorePlacementErrors=1,ReturnList=1,ReturnProcessingInstructions=1,ReturnComments=1) goodTest('<a>\nHello\n<b>cruel\n</b>\nWorld\n</a>',('a', None, ['\nHello\n', ('b', None, ['cruel\n'], (('aaa', 2, 3), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 3), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a aname="ANAME" aother="AOTHER">\nHello\n<b bname="BNAME" bother="BOTHER">cruel\n</b>\nWorld\n</a>',('a', {"aname": "ANAME", "aother": "AOTHER"}, ['\nHello\n', ('b', {"bname": "BNAME", "bother": "BOTHER"}, ['cruel\n'], (('aaa', 2, 33), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 33), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a><![CDATA[<a>]]></a>',('a', None, ['<a>'], None)) goodTest('<a><![CDATA[<a>]]></a>',('a', None, [('<![CDATA[', None, ['<a>'], None)], None),ReturnCDATASectionsAsTuples=1) goodTest('''<foo:A xmlns:foo="http://www.foo.org/"><foo:B><foo:C xmlns:foo="http://www.bar.org/"><foo:D>abcd</foo:D></foo:C></foo:B><foo:B/><A>bare A<C>bare C</C><B>bare B</B></A><A xmlns="http://default.reportlab.com/" xmlns:bongo="http://bongo.reportlab.com/">default ns A<bongo:A>bongo A</bongo:A><B>default NS B</B></A></foo:A>''',('{http://www.foo.org/}A', {'xmlns:foo': 'http://www.foo.org/'}, [('{http://www.foo.org/}B', None, [('{http://www.bar.org/}C', {'xmlns:foo': 'http://www.bar.org/'}, [('{http://www.bar.org/}D', None, ['abcd'], None)], None)], None), ('{http://www.foo.org/}B', None, None, None), ('A', None, ['bare A', ('C', None, ['bare C'], None), ('B', None, ['bare B'], None)], None), ('{http://default.reportlab.com/}A', {'xmlns': 'http://default.reportlab.com/', 'xmlns:bongo': 'http://bongo.reportlab.com/'}, ['default ns A', ('{http://bongo.reportlab.com/}A', None, ['bongo A'], None), ('{http://default.reportlab.com/}B', None, ['default NS B'], None)], None)], None),XMLNamespaces=1,ReturnNamespaceAttributes=1) failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1)
4,559
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser()("<a/>",%s=%d)' % (k,v)) print >>_logf,'Parser().parse keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser().parse keywords BAD' _dot('E') goodTest('<a></a>',('a', None, [], None)) goodTest('<a></a>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a></a>',['a', None, [], None],MakeMutableTree=1) goodTest('<a/>',('a', None, None, None)) goodTest('<a/>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a/>',['a', None, None, None],MakeMutableTree=1) goodTest('<a/>',['a', {}, [], None],ExpandEmpty=1,MakeMutableTree=1) failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n") goodTest('<a>A<!--comment--></a>',('a', None, ['A'], None)) goodTest('<a>A<!--comment--></a>',('a', {}, ['A'], None),ExpandEmpty=1) goodTest('<a>A<!--comment--></a>', ('a', None, ['A', ('<!--', None, ['comment'], None)], None), ReturnComments=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A<&>'], None)) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A', '<', '&', '>'], None), MergePCData=0) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) goodTest('<!--comment--><a/>',[('<!--',None,['comment'],None),('a', None, None, None)],ReturnComments=1,ReturnList=1) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"Error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n") goodTest('<?work version="1.0" encoding="utf-8"?><a/>',[('<?',{'name':'work'}, ['version="1.0" encoding="utf-8"'],None), ('a', None, None, None)],IgnorePlacementErrors=1,ReturnList=1,ReturnProcessingInstructions=1,ReturnComments=1) goodTest('<a>\nHello\n<b>cruel\n</b>\nWorld\n</a>',('a', None, ['\nHello\n', ('b', None, ['cruel\n'], (('aaa', 2, 3), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 3), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a aname="ANAME" aother="AOTHER">\nHello\n<b bname="BNAME" bother="BOTHER">cruel\n</b>\nWorld\n</a>',('a', {"aname": "ANAME", "aother": "AOTHER"}, ['\nHello\n', ('b', {"bname": "BNAME", "bother": "BOTHER"}, ['cruel\n'], (('aaa', 2, 33), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 33), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a><![CDATA[<a>]]></a>',('a', None, ['<a>'], None)) goodTest('<a><![CDATA[<a>]]></a>',('a', None, [('<![CDATA[', None, ['<a>'], None)], None),ReturnCDATASectionsAsTuples=1) goodTest('''<foo:A xmlns:foo="http://www.foo.org/"><foo:B><foo:C xmlns:foo="http://www.bar.org/"><foo:D>abcd</foo:D></foo:C></foo:B><foo:B/><A>bare A<C>bare C</C><B>bare B</B></A><A xmlns="http://default.reportlab.com/" xmlns:bongo="http://bongo.reportlab.com/">default ns A<bongo:A>bongo A</bongo:A><B>default NS B</B></A></foo:A>''',('{http://www.foo.org/}A', {'xmlns:foo': 'http://www.foo.org/'}, [('{http://www.foo.org/}B', None, [('{http://www.bar.org/}C', {'xmlns:foo': 'http://www.bar.org/'}, [('{http://www.bar.org/}D', None, ['abcd'], None)], None)], None), ('{http://www.foo.org/}B', None, None, None), ('A', None, ['bare A', ('C', None, ['bare C'], None), ('B', None, ['bare B'], None)], None), ('{http://default.reportlab.com/}A', {'xmlns': 'http://default.reportlab.com/', 'xmlns:bongo': 'http://bongo.reportlab.com/'}, ['default ns A', ('{http://bongo.reportlab.com/}A', None, ['bongo A'], None), ('{http://default.reportlab.com/}B', None, ['default NS B'], None)], None)], None),XMLNamespaces=1,ReturnNamespaceAttributes=1) failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1)
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser()("<a/>",%s=%d)' % (k,v)) print >>_logf,'Parser().parse keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser().parse keywords BAD' _dot('E') goodTest('<a></a>',('a', None, [], None)) goodTest('<a></a>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a></a>',['a', None, [], None],MakeMutableTree=1) goodTest('<a/>',('a', None, None, None)) goodTest('<a/>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a/>',['a', None, None, None],MakeMutableTree=1) goodTest('<a/>',['a', {}, [], None],ExpandEmpty=1,MakeMutableTree=1) failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n") goodTest('<a>A<!--comment--></a>',('a', None, ['A'], None)) goodTest('<a>A<!--comment--></a>',('a', {}, ['A'], None),ExpandEmpty=1) goodTest('<a>A<!--comment--></a>', ('a', None, ['A', ('<!--', None, ['comment'], None)], None), ReturnComments=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A<&>'], None)) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A', '<', '&', '>'], None), MergePCData=0) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) goodTest('<!--comment--><a/>',[('<!--',None,['comment'],None),('a', None, None, None)],ReturnComments=1,ReturnList=1) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n") goodTest('<?work version="1.0" encoding="utf-8"?><a/>',[('<?',{'name':'work'}, ['version="1.0" encoding="utf-8"'],None), ('a', None, None, None)],IgnorePlacementErrors=1,ReturnList=1,ReturnProcessingInstructions=1,ReturnComments=1) goodTest('<a>\nHello\n<b>cruel\n</b>\nWorld\n</a>',('a', None, ['\nHello\n', ('b', None, ['cruel\n'], (('aaa', 2, 3), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 3), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a aname="ANAME" aother="AOTHER">\nHello\n<b bname="BNAME" bother="BOTHER">cruel\n</b>\nWorld\n</a>',('a', {"aname": "ANAME", "aother": "AOTHER"}, ['\nHello\n', ('b', {"bname": "BNAME", "bother": "BOTHER"}, ['cruel\n'], (('aaa', 2, 33), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 33), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a><![CDATA[<a>]]></a>',('a', None, ['<a>'], None)) goodTest('<a><![CDATA[<a>]]></a>',('a', None, [('<![CDATA[', None, ['<a>'], None)], None),ReturnCDATASectionsAsTuples=1) goodTest('''<foo:A xmlns:foo="http://www.foo.org/"><foo:B><foo:C xmlns:foo="http://www.bar.org/"><foo:D>abcd</foo:D></foo:C></foo:B><foo:B/><A>bare A<C>bare C</C><B>bare B</B></A><A xmlns="http://default.reportlab.com/" xmlns:bongo="http://bongo.reportlab.com/">default ns A<bongo:A>bongo A</bongo:A><B>default NS B</B></A></foo:A>''',('{http://www.foo.org/}A', {'xmlns:foo': 'http://www.foo.org/'}, [('{http://www.foo.org/}B', None, [('{http://www.bar.org/}C', {'xmlns:foo': 'http://www.bar.org/'}, [('{http://www.bar.org/}D', None, ['abcd'], None)], None)], None), ('{http://www.foo.org/}B', None, None, None), ('A', None, ['bare A', ('C', None, ['bare C'], None), ('B', None, ['bare B'], None)], None), ('{http://default.reportlab.com/}A', {'xmlns': 'http://default.reportlab.com/', 'xmlns:bongo': 'http://bongo.reportlab.com/'}, ['default ns A', ('{http://bongo.reportlab.com/}A', None, ['bongo A'], None), ('{http://default.reportlab.com/}B', None, ['default NS B'], None)], None)], None),XMLNamespaces=1,ReturnNamespaceAttributes=1) failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1)
4,560
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser()("<a/>",%s=%d)' % (k,v)) print >>_logf,'Parser().parse keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser().parse keywords BAD' _dot('E') goodTest('<a></a>',('a', None, [], None)) goodTest('<a></a>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a></a>',['a', None, [], None],MakeMutableTree=1) goodTest('<a/>',('a', None, None, None)) goodTest('<a/>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a/>',['a', None, None, None],MakeMutableTree=1) goodTest('<a/>',['a', {}, [], None],ExpandEmpty=1,MakeMutableTree=1) failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n") goodTest('<a>A<!--comment--></a>',('a', None, ['A'], None)) goodTest('<a>A<!--comment--></a>',('a', {}, ['A'], None),ExpandEmpty=1) goodTest('<a>A<!--comment--></a>', ('a', None, ['A', ('<!--', None, ['comment'], None)], None), ReturnComments=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A<&>'], None)) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A', '<', '&', '>'], None), MergePCData=0) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) goodTest('<!--comment--><a/>',[('<!--',None,['comment'],None),('a', None, None, None)],ReturnComments=1,ReturnList=1) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"Error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n") goodTest('<?work version="1.0" encoding="utf-8"?><a/>',[('<?',{'name':'work'}, ['version="1.0" encoding="utf-8"'],None), ('a', None, None, None)],IgnorePlacementErrors=1,ReturnList=1,ReturnProcessingInstructions=1,ReturnComments=1) goodTest('<a>\nHello\n<b>cruel\n</b>\nWorld\n</a>',('a', None, ['\nHello\n', ('b', None, ['cruel\n'], (('aaa', 2, 3), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 3), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a aname="ANAME" aother="AOTHER">\nHello\n<b bname="BNAME" bother="BOTHER">cruel\n</b>\nWorld\n</a>',('a', {"aname": "ANAME", "aother": "AOTHER"}, ['\nHello\n', ('b', {"bname": "BNAME", "bother": "BOTHER"}, ['cruel\n'], (('aaa', 2, 33), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 33), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a><![CDATA[<a>]]></a>',('a', None, ['<a>'], None)) goodTest('<a><![CDATA[<a>]]></a>',('a', None, [('<![CDATA[', None, ['<a>'], None)], None),ReturnCDATASectionsAsTuples=1) goodTest('''<foo:A xmlns:foo="http://www.foo.org/"><foo:B><foo:C xmlns:foo="http://www.bar.org/"><foo:D>abcd</foo:D></foo:C></foo:B><foo:B/><A>bare A<C>bare C</C><B>bare B</B></A><A xmlns="http://default.reportlab.com/" xmlns:bongo="http://bongo.reportlab.com/">default ns A<bongo:A>bongo A</bongo:A><B>default NS B</B></A></foo:A>''',('{http://www.foo.org/}A', {'xmlns:foo': 'http://www.foo.org/'}, [('{http://www.foo.org/}B', None, [('{http://www.bar.org/}C', {'xmlns:foo': 'http://www.bar.org/'}, [('{http://www.bar.org/}D', None, ['abcd'], None)], None)], None), ('{http://www.foo.org/}B', None, None, None), ('A', None, ['bare A', ('C', None, ['bare C'], None), ('B', None, ['bare B'], None)], None), ('{http://default.reportlab.com/}A', {'xmlns': 'http://default.reportlab.com/', 'xmlns:bongo': 'http://bongo.reportlab.com/'}, ['default ns A', ('{http://bongo.reportlab.com/}A', None, ['bongo A'], None), ('{http://default.reportlab.com/}B', None, ['default NS B'], None)], None)], None),XMLNamespaces=1,ReturnNamespaceAttributes=1) failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1)
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser()("<a/>",%s=%d)' % (k,v)) print >>_logf,'Parser().parse keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser().parse keywords BAD' _dot('E') goodTest('<a></a>',('a', None, [], None)) goodTest('<a></a>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a></a>',['a', None, [], None],MakeMutableTree=1) goodTest('<a/>',('a', None, None, None)) goodTest('<a/>',('a', {}, [], None),ExpandEmpty=1) goodTest('<a/>',['a', None, None, None],MakeMutableTree=1) goodTest('<a/>',['a', {}, [], None],ExpandEmpty=1,MakeMutableTree=1) failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n") goodTest('<a>A<!--comment--></a>',('a', None, ['A'], None)) goodTest('<a>A<!--comment--></a>',('a', {}, ['A'], None),ExpandEmpty=1) goodTest('<a>A<!--comment--></a>', ('a', None, ['A', ('<!--', None, ['comment'], None)], None), ReturnComments=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A<&>'], None)) goodTest('<a>A&lt;&amp;&gt;</a>',('a', None, ['A', '<', '&', '>'], None), MergePCData=0) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) goodTest('<!--comment--><a/>',[('<!--',None,['comment'],None),('a', None, None, None)],ReturnComments=1,ReturnList=1) goodTest('<!--comment--><a/>',('a', None, None, None),ReturnComments=1) failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"Error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n") goodTest('<?work version="1.0" encoding="utf-8"?><a/>',[('<?',{'name':'work'}, ['version="1.0" encoding="utf-8"'],None), ('a', None, None, None)],IgnorePlacementErrors=1,ReturnList=1,ReturnProcessingInstructions=1,ReturnComments=1) goodTest('<a>\nHello\n<b>cruel\n</b>\nWorld\n</a>',('a', None, ['\nHello\n', ('b', None, ['cruel\n'], (('aaa', 2, 3), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 3), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a aname="ANAME" aother="AOTHER">\nHello\n<b bname="BNAME" bother="BOTHER">cruel\n</b>\nWorld\n</a>',('a', {"aname": "ANAME", "aother": "AOTHER"}, ['\nHello\n', ('b', {"bname": "BNAME", "bother": "BOTHER"}, ['cruel\n'], (('aaa', 2, 33), ('aaa', 3, 4))), '\nWorld\n'], (('aaa', 0, 33), ('aaa', 5, 4))),fourth=pyRXP.recordLocation,srcName='aaa') goodTest('<a><![CDATA[<a>]]></a>',('a', None, ['<a>'], None)) goodTest('<a><![CDATA[<a>]]></a>',('a', None, [('<![CDATA[', None, ['<a>'], None)], None),ReturnCDATASectionsAsTuples=1) goodTest('''<foo:A xmlns:foo="http://www.foo.org/"><foo:B><foo:C xmlns:foo="http://www.bar.org/"><foo:D>abcd</foo:D></foo:C></foo:B><foo:B/><A>bare A<C>bare C</C><B>bare B</B></A><A xmlns="http://default.reportlab.com/" xmlns:bongo="http://bongo.reportlab.com/">default ns A<bongo:A>bongo A</bongo:A><B>default NS B</B></A></foo:A>''',('{http://www.foo.org/}A', {'xmlns:foo': 'http://www.foo.org/'}, [('{http://www.foo.org/}B', None, [('{http://www.bar.org/}C', {'xmlns:foo': 'http://www.bar.org/'}, [('{http://www.bar.org/}D', None, ['abcd'], None)], None)], None), ('{http://www.foo.org/}B', None, None, None), ('A', None, ['bare A', ('C', None, ['bare C'], None), ('B', None, ['bare B'], None)], None), ('{http://default.reportlab.com/}A', {'xmlns': 'http://default.reportlab.com/', 'xmlns:bongo': 'http://bongo.reportlab.com/'}, ['default ns A', ('{http://bongo.reportlab.com/}A', None, ['bongo A'], None), ('{http://default.reportlab.com/}B', None, ['default NS B'], None)], None)], None),XMLNamespaces=1,ReturnNamespaceAttributes=1) failTest(bigDepth(257),"""error Internal error, stack limit reached!\n""", inOnly=1)
4,561
def getDifferences(self, otherEnc): """Return a compact list of the code points differing between two encodings
def getDifferences(self, otherEnc): """Return a compact list of the code points differing between two encodings
4,562
def getDifferences(self, otherEnc): """Return a compact list of the code points differing between two encodings
def getDifferences(self, otherEnc): """Return a compact list of the code points differing between two encodings
4,563
def testStringWidthAlgorithms(): rawdata = open('../../rlextra/rml2pdf/doc/rml_user_guide.rml').read() print 'rawdata length %d' % len(rawdata) print 'test one huge string...' test3widths([rawdata]) print words = string.split(rawdata) print 'test %d shorter strings (average length %0.2f chars)...' % (len(words), 1.0*len(rawdata)/len(words)) test3widths(words)
def testStringWidthAlgorithms(): rawdata = open('../../rlextra/rml2pdf/doc/rml_user_guide.prep').read() print 'rawdata length %d' % len(rawdata) print 'test one huge string...' test3widths([rawdata]) print words = string.split(rawdata) print 'test %d shorter strings (average length %0.2f chars)...' % (len(words), 1.0*len(rawdata)/len(words)) test3widths(words)
4,564
def __init__(self): self.strokeWidth = 0 self.fillColor = None self.strokeColor = STATE_DEFAULTS["strokeColor"] self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"] self.popout = 0 self.fontName = STATE_DEFAULTS["fontName"] self.fontSize = STATE_DEFAULTS["fontSize"] self.fontColor = STATE_DEFAULTS["fillColor"] self.labelRadius = 1.2
def __init__(self): self.strokeWidth = 0 self.fillColor = None self.strokeColor = STATE_DEFAULTS["strokeColor"] self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"] self.popout = 0 self.fontName = STATE_DEFAULTS["fontName"] self.fontSize = STATE_DEFAULTS["fontSize"] self.fontColor = STATE_DEFAULTS["fillColor"] self.labelRadius = 1.2
4,565
def sample0a(): "Make a degenerated pie chart with only one slice." d = Drawing(400, 200) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [10] pc.labels = ['a'] pc.defaultStyles.strokeWidth=1#0.5 d.add(pc) return d
def sample0a(): "Make a degenerated pie chart with only one slice." d = Drawing(400, 200) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [10] pc.labels = ['a'] pc.defaultStyles.strokeWidth=1#0.5 d.add(pc) return d
4,566
def sample0b(): "Make a degenerated pie chart with only one slice." d = Drawing(400, 200) pc = Pie() pc.x = 150 pc.y = 50 pc.width = 120 pc.height = 100 pc.data = [10] pc.labels = ['a'] pc.defaultStyles.strokeWidth=1#0.5 d.add(pc) return d
def sample0b(): "Make a degenerated pie chart with only one slice." d = Drawing(400, 200) pc = Pie() pc.x = 150 pc.y = 50 pc.width = 120 pc.height = 100 pc.data = [10] pc.labels = ['a'] pc.defaultStyles.strokeWidth=1#0.5 d.add(pc) return d
4,567
def sample1(): "Make a typical pie chart with with one slice treated in a special way." d = Drawing(400, 200) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.defaultStyles.strokeWidth=1#0.5 pc.defaultStyles[3].popout = 20 pc.defaultStyles[3].strokeWidth = 2 pc.defaultStyles[3].strokeDashArray = [2,2] pc.defaultStyles[3].labelRadius = 1.75 pc.defaultStyles[3].fontColor = colors.red d.add(pc) return d
def sample1(): "Make a typical pie chart with with one slice treated in a special way." d = Drawing(400, 200) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.defaultStyles.strokeWidth=1#0.5 pc.defaultStyles[3].popout = 20 pc.defaultStyles[3].strokeWidth = 2 pc.defaultStyles[3].strokeDashArray = [2,2] pc.defaultStyles[3].labelRadius = 1.75 pc.defaultStyles[3].fontColor = colors.red d.add(pc) return d
4,568
def sample2(): "Make a pie chart with nine slices." d = Drawing(400, 200) pc = Pie() pc.x = 125 pc.y = 25 pc.data = [0.31, 0.148, 0.108, 0.076, 0.033, 0.03, 0.019, 0.126, 0.15] pc.labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'X'] pc.width = 150 pc.height = 150 pc.defaultStyles.strokeWidth=1#0.5 pc.defaultStyles[0].fillColor = colors.steelblue pc.defaultStyles[1].fillColor = colors.thistle pc.defaultStyles[2].fillColor = colors.cornflower pc.defaultStyles[3].fillColor = colors.lightsteelblue pc.defaultStyles[4].fillColor = colors.aquamarine pc.defaultStyles[5].fillColor = colors.cadetblue pc.defaultStyles[6].fillColor = colors.lightcoral pc.defaultStyles[7].fillColor = colors.tan pc.defaultStyles[8].fillColor = colors.darkseagreen d.add(pc) return d
def sample2(): "Make a pie chart with nine slices." d = Drawing(400, 200) pc = Pie() pc.x = 125 pc.y = 25 pc.data = [0.31, 0.148, 0.108, 0.076, 0.033, 0.03, 0.019, 0.126, 0.15] pc.labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'X'] pc.width = 150 pc.height = 150 pc.defaultStyles.strokeWidth=1#0.5 pc.defaultStyles[0].fillColor = colors.steelblue pc.defaultStyles[1].fillColor = colors.thistle pc.defaultStyles[2].fillColor = colors.cornflower pc.defaultStyles[3].fillColor = colors.lightsteelblue pc.defaultStyles[4].fillColor = colors.aquamarine pc.defaultStyles[5].fillColor = colors.cadetblue pc.defaultStyles[6].fillColor = colors.lightcoral pc.defaultStyles[7].fillColor = colors.tan pc.defaultStyles[8].fillColor = colors.darkseagreen d.add(pc) return d
4,569
def sample3(): "Make a pie chart with a very slim slice." d = Drawing(400, 200) pc = Pie() pc.x = 125 pc.y = 25 pc.data = [74, 1, 25] pc.width = 150 pc.height = 150 pc.defaultStyles.strokeWidth=1#0.5 pc.defaultStyles[0].fillColor = colors.steelblue pc.defaultStyles[1].fillColor = colors.thistle pc.defaultStyles[2].fillColor = colors.cornflower d.add(pc) return d
def sample3(): "Make a pie chart with a very slim slice." d = Drawing(400, 200) pc = Pie() pc.x = 125 pc.y = 25 pc.data = [74, 1, 25] pc.width = 150 pc.height = 150 pc.defaultStyles.strokeWidth=1#0.5 pc.defaultStyles[0].fillColor = colors.steelblue pc.defaultStyles[1].fillColor = colors.thistle pc.defaultStyles[2].fillColor = colors.cornflower d.add(pc) return d
4,570
def provideNode(self): return self.draw()
def provideNode(self): return self.draw()
4,571
def __getitem__(self, index): try: return self._children[index] except KeyError: Klass = self._prototype if Klass in _ElementWrapper.keys(): WKlass = _ElementWrapper[Klass] else: class WKlass(Klass): def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name)
def __getitem__(self, index): try: return self._children[index] except KeyError: Klass = self._prototype if Klass in _ItemWrapper.keys(): WKlass = _ItemWrapper[Klass] else: class WKlass(Klass): def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name)
4,572
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0, compression=rl_config.pageCompression, invariant=rl_config.invariant): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'WinAnsiEncoding', 'MacRoman', 'WinAnsi'], 'Unsupported encoding %s' % encoding if encoding[-8:] <> 'Encoding': encoding = encoding + 'Encoding'
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0, compression=rl_config.pageCompression, invariant=rl_config.invariant): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'WinAnsiEncoding', 'MacRoman', 'WinAnsi'], 'Unsupported encoding %s' % encoding if encoding[-8:] <> 'Encoding': encoding = encoding + 'Encoding'
4,573
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0, compression=rl_config.pageCompression, invariant=rl_config.invariant): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'WinAnsiEncoding', 'MacRoman', 'WinAnsi'], 'Unsupported encoding %s' % encoding if encoding[-8:] <> 'Encoding': encoding = encoding + 'Encoding'
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0, compression=rl_config.pageCompression, invariant=rl_config.invariant): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'WinAnsiEncoding', 'MacRoman', 'WinAnsi'], 'Unsupported encoding %s' % encoding if encoding[-8:] <> 'Encoding': encoding = encoding + 'Encoding'
4,574
def __init__(self): self.invariant = 1 self.title = "untitled" self.author = "anonymous" self.subject = "unspecified" #now = time.localtime(time.time()) #self.datestr = '%04d%02d%02d%02d%02d%02d' % tuple(now[0:6])
def __init__(self): self.invariant = rl_config.invariant self.title = "untitled" self.author = "anonymous" self.subject = "unspecified" #now = time.localtime(time.time()) #self.datestr = '%04d%02d%02d%02d%02d%02d' % tuple(now[0:6])
4,575
def __init__(self): self.invariant = 1 self.title = "untitled" self.author = "anonymous" self.subject = "unspecified" #now = time.localtime(time.time()) #self.datestr = '%04d%02d%02d%02d%02d%02d' % tuple(now[0:6])
def __init__(self): self.invariant = 1 self.title = "untitled" self.author = "anonymous" self.subject = "unspecified" #now = time.localtime(time.time()) #self.datestr = '%04d%02d%02d%02d%02d%02d' % tuple(now[0:6])
4,576
def format(self, document): D = {} D["Title"] = PDFString(self.title) D["Author"] = PDFString(self.author) if self.invariant: D["CreationDate"] = PDFString('19001231000000') else: D["CreationDate"] = PDFDate() D["Producer"] = PDFString("ReportLab http://www.reportlab.com") D["Subject"] = PDFString(self.subject) PD = PDFDictionary(D) return PD.format(document)
def format(self, document): D = {} D["Title"] = PDFString(self.title) D["Author"] = PDFString(self.author) D["CreationDate"] = PDFDate(invariant=self.invariant) D["Producer"] = PDFString("ReportLab http://www.reportlab.com") D["Subject"] = PDFString(self.subject) PD = PDFDictionary(D) return PD.format(document)
4,577
def format(self, document): A = PDFArray([self.llx, self.lly, self.ulx, self.ury]) return format(A, document)
def format(self, document): A = PDFArray([self.llx, self.lly, self.ulx, self.ury]) return format(A, document)
4,578
def __init__(self, yyyy=nowyyyy, mm=nowmm, dd=nowdd, hh=nowhh, m=nowm, s=nows): self.yyyy=yyyy; self.mm=mm; self.dd=dd; self.hh=hh; self.m=m; self.s=s
def __init__(self, yyyy=None, mm=None, dd=None, hh=None, m=None, s=None, invariant=rl_config.invariant): if None in (yyyy, mm, dd, hh, m, s): if invariant: now = 1900,01,01,00,00,00,0 else: global _NOW if _NOW is None: import time _NOW = tuple(time.localtime(time.time())[:6]) now = _NOW if yyyy is None: yyyy=now[0] if mm is None: mm=now[1] if dd is None: dd=now[2] if hh is None: hh=now[3] if m is None: m=now[4] if s is None: s=now[5] self.yyyy=yyyy; self.mm=mm; self.dd=dd; self.hh=hh; self.m=m; self.s=s
4,579
def format(self, doc): S = PDFString(DATEFMT % (self.yyyy, self.mm, self.dd, self.hh, self.m, self.s)) return format(S, doc)
def format(self, doc): S = PDFString('%04d%02d%02d%02d%02d%02d' % (self.yyyy, self.mm, self.dd, self.hh, self.m, self.s)) return format(S, doc)
4,580
def __init__(self, fileName): if isinstance(fileName,ImageReader): self.__dict__ = fileName.__dict__ #borgize return if not haveImages: raise RuntimeError('Imaging Library not available, unable to import bitmaps') #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileName self._image = None self._width = None self._height = None self._transparent = None self._data = None if _isPILImage(fileName): self._image = fileName self.fp = fileName.fp try: self.fileName = fileName except AttributeError: self.fileName = 'PILIMAGE_%d' % id(self) else: try: self.fp = open_for_read(fileName,'b') #detect which library we are using and open the image if sys.platform[0:4] == 'java': from javax.imageio import ImageIO self._image = ImageIO.read(self.fp) else: import PIL.Image self._image = PIL.Image.open(self.fp) if self._image=='JPEG': self.jpeg_fh = self._jpeg_fp except: et,ev,tb = sys.exc_info() if hasattr(ev,'args'): a = str(ev.args[-1])+(' fileName='+fileName) ev.args= ev.args[:-1]+(a,) raise et,ev,tb else: raise
def __init__(self, fileName): if isinstance(fileName,ImageReader): self.__dict__ = fileName.__dict__ #borgize return if not haveImages: raise RuntimeError('Imaging Library not available, unable to import bitmaps') #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = self._image.fileName self._image = None self._width = None self._height = None self._transparent = None self._data = None if _isPILImage(fileName): self._image = fileName self.fp = fileName.fp try: self.fileName = self._image.fileName except AttributeError: self.fileName = 'PILIMAGE_%d' % id(self) else: try: self.fp = open_for_read(fileName,'b') #detect which library we are using and open the image if sys.platform[0:4] == 'java': from javax.imageio import ImageIO self._image = ImageIO.read(self.fp) else: import PIL.Image self._image = PIL.Image.open(self.fp) if self._image=='JPEG': self.jpeg_fh = self._jpeg_fp except: et,ev,tb = sys.exc_info() if hasattr(ev,'args'): a = str(ev.args[-1])+(' fileName='+fileName) ev.args= ev.args[:-1]+(a,) raise et,ev,tb else: raise
4,581
def _calc(self): if hasattr(self,'_width'): return
def _calc(self): if hasattr(self,'_width'): return
4,582
def _calc(self): if hasattr(self,'_width'): return
def_calc(self):ifhasattr(self,'_width'):return
4,583
def _calc(self): if hasattr(self,'_width'): return
def _calc(self): if hasattr(self,'_width'): return
4,584
def _calc(self): if hasattr(self,'_width'): return
def _calc(self): if hasattr(self,'_width'): return
4,585
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
4,586
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
4,587
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
4,588
def __init__(self, fileName): if not haveImages: warnOnce('Imaging Library not available, unable to import bitmaps') return #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileName self._image = None self._width = None self._height = None self._transparent = None self._data = None
def __init__(self, fileName): if not haveImages: warnOnce('Imaging Library not available, unable to import bitmaps') return #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileName self._image = None self._width = None self._height = None self._transparent = None self._data = None
4,589
def makeMarker(name): if Marker._attrMap['kind'].validate(name): m = Marker() m.kind = name elif Flag._attrMap['kind'].validate(name): m = Flag() m.kind = name m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m
def makeMarker(name): if Marker._attrMap['kind'].validate(name): m = Marker() m.kind = name elif name[-5:]=='_Flag' and Flag._attrMap['kind'].validate(name[:-5]): m = Flag() m.kind = name m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m
4,590
def makeMarker(name): if Marker._attrMap['kind'].validate(name): m = Marker() m.kind = name elif Flag._attrMap['kind'].validate(name): m = Flag() m.kind = name m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m
def makeMarker(name): if Marker._attrMap['kind'].validate(name): m = Marker() m.kind = name[:-5] elif Flag._attrMap['kind'].validate(name): m = Flag() m.kind = name[:-5] m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m
4,591
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
4,592
def drawOn(self, canvas): canvas.saveState() canvas.setFont('Helvetica-Bold',24) canvas.drawString(100,700,'A Custom Shape')
def drawOn(self, canvas): canvas.saveState() canvas.setFont('Helvetica-Bold',24) canvas.drawString(100,700,'A Custom Shape')
4,593
def getKeepWithNext(self): """returns boolean determining whether the next flowabel should stay with this one""" if hasattr(self,'keepWithNext'): return self.keepWithNext elif hasattr(self,'style') and hasattr(self.style,'keepWithNext'): return self.style.keepWithNext else: return 0
def getKeepWithNext(self): """returns boolean determining whether the next flowable should stay with this one""" if hasattr(self,'keepWithNext'): return self.keepWithNext elif hasattr(self,'style') and hasattr(self.style,'keepWithNext'): return self.style.keepWithNext else: return 0
4,594
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=None, mode=0, id=None): '''mode describes the action to take when overflowing 0 raise an error in the normal way 1 ignore ie just draw it and report maxWidth, maxHeight 2 shrinkToFit ''' self.id = id self.maxWidth = maxWidth self.maxHeight = maxHeight self.mode = mode assert mode in (0,1,2), '%s invalid mode value %s' % (self.identity(),mode) if mergeSpace is None: mergeSpace = overlapAttachedSpace self.mergespace = mergeSpace self._content = content
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=1, mode=0, name=None): '''mode describes the action to take when overflowing 0 raise an error in the normal way 1 ignore ie just draw it and report maxWidth, maxHeight 2 shrinkToFit ''' self.id = id self.maxWidth = maxWidth self.maxHeight = maxHeight self.mode = mode assert mode in (0,1,2), '%s invalid mode value %s' % (self.identity(),mode) if mergeSpace is None: mergeSpace = overlapAttachedSpace self.mergespace = mergeSpace self._content = content
4,595
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=None, mode=0, id=None): '''mode describes the action to take when overflowing 0 raise an error in the normal way 1 ignore ie just draw it and report maxWidth, maxHeight 2 shrinkToFit ''' self.id = id self.maxWidth = maxWidth self.maxHeight = maxHeight self.mode = mode assert mode in (0,1,2), '%s invalid mode value %s' % (self.identity(),mode) if mergeSpace is None: mergeSpace = overlapAttachedSpace self.mergespace = mergeSpace self._content = content
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=None, mode=0, id=None): '''mode describes the action to take when overflowing 0 raise an error in the normal way 1 ignore ie just draw it and report maxWidth, maxHeight 2 shrinkToFit ''' self.name = name or str(id(self)) self.maxWidth = maxWidth self.maxHeight = maxHeight self.mode = mode assert mode in (0,1,2), '%s invalid mode value %s' % (self.identity(),mode) if mergeSpace is None: mergeSpace = overlapAttachedSpace self.mergespace = mergeSpace self._content = content
4,596
def identity(self, maxLen=None): return "<%s at %d%s> size=%sx%s" % (self.__class__.__name__, id(self), self.id and ' id="%s"'%self.id, fp_str(self.maxWidth),fp_str(self.maxHeight))
def identity(self, maxLen=None): return "<%s at %d%s> size=%sx%s" % (self.__class__.__name__, id(self), self.id and ' id="%s"'%self.id, fp_str(self.maxWidth),fp_str(self.maxHeight))
4,597
def wrap(self,availWidth,availHeight): mode = self.mode maxWidth = float(self.maxWidth) maxHeight = float(self.maxHeight) W, H = _listWrapOn(self._content,availWidth,self.canv) if mode==0 or (W<=maxWidth and H<=maxHeight): self.width = W #we take what we get self.height = H elif mode==1: #we lie self.width = min(maxWidth,W)-_FUZZ self.height = min(maxHeight,H)-_FUZZ else: def func(x): W, H = _listWrapOn(self._content,x*availWidth,self.canv) W /= x H /= x return W, H W0 = W H0 = H s0 = 1 if W>maxWidth: #squeeze out the excess width s1 = W/maxWidth W, H = func(s1) if H<=maxHeight: self.width = W self.height = H self._scale = s1 return W,H s0 = s1 H0 = H W0 = W s1 = H/maxHeight W, H = func(s1) self.width = W self.height = H self._scale = s1 if H<min(0.95*maxHeight,maxHeight-10): #the standard case W should be OK, H is short we want #to find the smallest s with H<=maxHeight H1 = H for f in 0, 0.01, 0.05, 0.10, 0.15: #apply the quadratic model s = _qsolve(maxHeight*(1-f),_hmodel(s0,s1,H0,H1)) W, H = func(s) if H<=maxHeight: self.width = W self.height = H self._scale = s break
def wrap(self,availWidth,availHeight): mode = self.mode maxWidth = float(self.maxWidth or availWidth) maxHeight = float(self.maxHeight) W, H = _listWrapOn(self._content,availWidth,self.canv) if mode==0 or (W<=maxWidth and H<=maxHeight): self.width = W #we take what we get self.height = H elif mode==1: #we lie self.width = min(maxWidth,W)-_FUZZ self.height = min(maxHeight,H)-_FUZZ else: def func(x): W, H = _listWrapOn(self._content,x*availWidth,self.canv) W /= x H /= x return W, H W0 = W H0 = H s0 = 1 if W>maxWidth: #squeeze out the excess width s1 = W/maxWidth W, H = func(s1) if H<=maxHeight: self.width = W self.height = H self._scale = s1 return W,H s0 = s1 H0 = H W0 = W s1 = H/maxHeight W, H = func(s1) self.width = W self.height = H self._scale = s1 if H<min(0.95*maxHeight,maxHeight-10): #the standard case W should be OK, H is short we want #to find the smallest s with H<=maxHeight H1 = H for f in 0, 0.01, 0.05, 0.10, 0.15: #apply the quadratic model s = _qsolve(maxHeight*(1-f),_hmodel(s0,s1,H0,H1)) W, H = func(s) if H<=maxHeight: self.width = W self.height = H self._scale = s break
4,598
def _getFragLines(frags): lines = [] cline = [] W = frags[:] while W != []: w = W[0] t = w.text del W[0] i = string.find(t,'\n') if i>=0: tleft = t[i+1:] w.text = t[:i] cline.append(w) lines.append(cline) cline = [] if tleft!='': W.insert(0,w.clone(text=tleft)) else: cline.append(w) if cline!=[]: lines.append(cline) return lines
def _getFragLines(frags): lines = [] cline = [] W = frags[:] while W != []: w = W[0] t = w.text del W[0] i = string.find(t,'\n') if i>=0: tleft = t[i+1:] cline.append(w.clone(text=t[:i])) lines.append(cline) cline = [] if tleft!='': W.insert(0,w.clone(text=tleft)) else: cline.append(w) if cline!=[]: lines.append(cline) return lines
4,599