bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def demo(self): """Shows basic use of a bar chart"""
def demo(self): """Shows basic use of a bar chart"""
5,800
def demo(self): """Shows basic use of a bar chart"""
def demo(self): """Shows basic use of a bar chart"""
5,801
def calcBarPositions(self): """Works out where they go.
def _findMinMaxValues(self): """Find the minimum and maximum value of the data we have.""" data = self.data m, M = Auto, Auto for row in data: for val in row: if val < m: m = val if val > M: M = val return m, M def calcBarPositions0(self): """Works out where they go.
5,802
def sample4a(): "Make a bar chart showing value axis region staring at *exactly* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
def sample4a(): "Make a bar chart showing value axis region starting at *exactly* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
5,803
def sample4a(): "Make a bar chart showing value axis region staring at *exactly* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
def sample4a(): "Make a bar chart showing value axis region staring at *exactly* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
5,804
def sample4b(): "Make a bar chart showing value axis region staring *below* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = -10 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
def sample4b(): "Make a bar chart showing value axis region starting *below* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = -10 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
5,805
def sample4b(): "Make a bar chart showing value axis region staring *below* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = -10 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
def sample4b(): "Make a bar chart showing value axis region staring *below* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = -10 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
5,806
def sample4c(): "Make a bar chart showing value axis region staring *above* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 10 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
def sample4c(): "Make a bar chart showing value axis region staring *above* zero." drawing = Drawing(400, 200) data = [(13, 20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 10 ### bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
5,807
def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1): """If size to draw at not specified, get it from the image.""" self.hAlign = 'CENTER' self._mask = mask # if it is a JPEG, will be inlined within the file - # but we still need to know its size now fp = hasattr(filename,'read') if fp: self._file = filename self.filename = `filename` else: self._file = self.filename = filename if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']: from reportlab.lib.utils import open_for_read f = open_for_read(filename, 'b') info = pdfutils.readJPEGInfo(f) f.close() self.imageWidth = info[0] self.imageHeight = info[1] self._setup(width,height,kind,0) self._img = None elif fp: self._setup(width,height,kind,0) else: self._setup(width,height,kind,lazy)
def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1): """If size to draw at not specified, get it from the image.""" self.hAlign = 'CENTER' self._mask = mask # if it is a JPEG, will be inlined within the file - # but we still need to know its size now fp = hasattr(filename,'read') if fp: self._file = filename self.filename = `filename` else: self._file = self.filename = filename if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']: from reportlab.lib.utils import open_for_read f = open_for_read(filename, 'b') info = pdfutils.readJPEGInfo(f) f.close() self.imageWidth = info[0] self.imageHeight = info[1] self._setup(width,height,kind,0) elif fp: self._setup(width,height,kind,0) else: self._setup(width,height,kind,lazy)
5,808
def _setup_inner(self): width = self._width height = self._height kind = self._kind (self.imageWidth, self.imageHeight) = self._img.getSize() if self._lazy>=2: del self._img if kind in ['direct','absolute']: self.drawWidth = width or self.imageWidth self.drawHeight = height or self.imageHeight elif kind in ['percentage','%']: self.drawWidth = self.imageWidth*width*0.01 self.drawHeight = self.imageHeight*height*0.01 elif kind in ['bound','proportional']: factor = min(float(width)/self.imageWidth,float(height)/self.imageHeight) self.drawWidth = self.imageWidth*factor self.drawHeight = self.imageHeight*factor
def _setup_inner(self): width = self._width height = self._height kind = self._kind img = self._img if img: self.imageWidth, self.imageHeight = img.getSize() if self._lazy>=2: del self._img if kind in ['direct','absolute']: self.drawWidth = width or self.imageWidth self.drawHeight = height or self.imageHeight elif kind in ['percentage','%']: self.drawWidth = self.imageWidth*width*0.01 self.drawHeight = self.imageHeight*height*0.01 elif kind in ['bound','proportional']: factor = min(float(width)/self.imageWidth,float(height)/self.imageHeight) self.drawWidth = self.imageWidth*factor self.drawHeight = self.imageHeight*factor
5,809
def linearlyInterpolatedColor(c0, c1, x0, x1, x): """ Linearly interpolates colors. Can handle RGB, CMYK and PCMYK colors - give ValueError if colours aren't the same. Doesn't currently handle 'Spot Color Interpolation'. """ if c0.__class__ != c1.__class__: raise ValueError, "Color classes must be the same for interpolation!" if x1<x0: x0,x1,c0,c1 = x1,x0,c1,c0 # normalized so x1>x0 if x<x0-1e-8 or x>x1+1e-8: # fudge factor for numerical problems raise ValueError, "Can't interpolate: x=%f is not between %f and %f!" % (x,x0,x1) if x<=x0: return c0 elif x>=x1: return c1 cname = c0.__class__.__name__ dx = float(x1-x0) x = x-x0 if cname == 'Color': # RGB r = c0.red+x*(c1.red - c0.red)/dx g = c0.green+x*(c1.green- c0.green)/dx b = c0.blue+x*(c1.blue - c0.blue)/dx return Color(r,g,b) elif cname == 'CMYKColor': c = c0.cyan+x*(c1.cyan - c0.cyan)/dx m = c0.magenta+x*(c1.magenta - c0.magenta)/dx y = c0.yellow+x*(c1.yellow - c0.yellow)/dx k = c0.black+x*(c1.black - c0.black)/dx d = c0.density+x*(c1.density - c0.density)/dx return CMYKColor(c,m,y,k, density=d) elif cname == 'PCMYKColor': if cmykDistance(c0,c1)<1e-8: #colors same do density and preserve spotName if any assert c0.spotName == c1.spotName, "Identical cmyk, but different spotName" c = c0.cyan m = c0.magenta y = c0.yellow k = c0.black d = c0.density+x*(c1.density - c0.density)/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c0.spotName) elif cmykDistance(c0,_CMYK_white)<1e-8: #special c0 is white c = c1.cyan m = c1.magenta y = c1.yellow k = c1.black d = x*c1.density/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c1.spotName) elif cmykDistance(c1,_CMYK_white)<1e-8: #special c1 is white c = c0.cyan m = c0.magenta y = c0.yellow k = c0.black d = x*c0.density/dx d = c0.density*(1-x/dx) return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c0.spotName) else: c = c0.cyan+x*(c1.cyan - c0.cyan)/dx m = c0.magenta+x*(c1.magenta - c0.magenta)/dx y = c0.yellow+x*(c1.yellow - c0.yellow)/dx k = c0.black+x*(c1.black - c0.black)/dx d = c0.density+x*(c1.density - c0.density)/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100) else: raise ValueError, "Can't interpolate: Unknown color class %s!" % cname
def linearlyInterpolatedColor(c0, c1, x0, x1, x): """ Linearly interpolates colors. Can handle RGB, CMYK and PCMYK colors - give ValueError if colours aren't the same. Doesn't currently handle 'Spot Color Interpolation'. """ if c0.__class__ != c1.__class__: raise ValueError, "Color classes must be the same for interpolation!" if x1<x0: x0,x1,c0,c1 = x1,x0,c1,c0 # normalized so x1>x0 if x<x0-1e-8 or x>x1+1e-8: # fudge factor for numerical problems raise ValueError, "Can't interpolate: x=%f is not between %f and %f!" % (x,x0,x1) if x<=x0: return c0 elif x>=x1: return c1 cname = c0.__class__.__name__ dx = float(x1-x0) x = x-x0 if cname == 'Color': # RGB r = c0.red+x*(c1.red - c0.red)/dx g = c0.green+x*(c1.green- c0.green)/dx b = c0.blue+x*(c1.blue - c0.blue)/dx return Color(r,g,b) elif cname == 'CMYKColor': c = c0.cyan+x*(c1.cyan - c0.cyan)/dx m = c0.magenta+x*(c1.magenta - c0.magenta)/dx y = c0.yellow+x*(c1.yellow - c0.yellow)/dx k = c0.black+x*(c1.black - c0.black)/dx d = c0.density+x*(c1.density - c0.density)/dx return CMYKColor(c,m,y,k, density=d) elif cname == 'PCMYKColor': if cmykDistance(c0,c1)<1e-8: #colors same do density and preserve spotName if any assert c0.spotName == c1.spotName, "Identical cmyk, but different spotName" c = c0.cyan m = c0.magenta y = c0.yellow k = c0.black d = c0.density+x*(c1.density - c0.density)/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c0.spotName) elif cmykDistance(c0,_CMYK_white)<1e-8: #special c0 is white c = c1.cyan m = c1.magenta y = c1.yellow k = c1.black d = x*c1.density/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c1.spotName) elif cmykDistance(c1,_CMYK_white)<1e-8: #special c1 is white c = c0.cyan m = c0.magenta y = c0.yellow k = c0.black d = x*c0.density/dx d = c0.density*(1-x/dx) return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c0.spotName) else: c = c0.cyan+x*(c1.cyan - c0.cyan)/dx m = c0.magenta+x*(c1.magenta - c0.magenta)/dx y = c0.yellow+x*(c1.yellow - c0.yellow)/dx k = c0.black+x*(c1.black - c0.black)/dx d = c0.density+x*(c1.density - c0.density)/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100) else: raise ValueError, "Can't interpolate: Unknown color class %s!" % cname
5,810
def calcBarPositions(self): """Works out where they go. default vertical.
def calcBarPositions(self): """Works out where they go. default vertical.
5,811
def calcBarPositions(self): """Works out where they go. default vertical.
def calcBarPositions(self): """Works out where they go. default vertical.
5,812
def draw(self): g = Group() ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize if self.background: x,y = self._getDrawingDimensions() g.add(Rect(-self.leftPadding,-ys,x,y, strokeColor=None, strokeWidth=0, fillColor=self.background))
def draw(self): g = Group() ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize if self.background: x,y = self._getDrawingDimensions() g.add(Rect(-self.leftPadding,-ys,x,y, strokeColor=None, strokeWidth=0, fillColor=self.background))
5,813
def getAttributes(self,attr,attrMap): A = {} for k, v in attr.items(): k = string.lower(k) if k in attrMap.keys(): j = attrMap[k] func = j[1] try: A[j[0]] = (func is None) and v or apply(func,(v,)) except: self.syntax_error('%s: invalid value %s'%(k,v)) else: self.syntax_error('invalid attribute name %s'%k) return A
def getAttributes(self,attr,attrMap): A = {} for k, v in attr.items(): k = string.lower(k) if k in attrMap.keys(): j = attrMap[k] func = j[1] try: A[j[0]] = (func is None) and v or apply(func,(v,)) except: self._syntax_error('%s: invalid value %s'%(k,v)) else: self.syntax_error('invalid attribute name %s'%k) return A
5,814
def getAttributes(self,attr,attrMap): A = {} for k, v in attr.items(): k = string.lower(k) if k in attrMap.keys(): j = attrMap[k] func = j[1] try: A[j[0]] = (func is None) and v or apply(func,(v,)) except: self.syntax_error('%s: invalid value %s'%(k,v)) else: self.syntax_error('invalid attribute name %s'%k) return A
def getAttributes(self,attr,attrMap): A = {} for k, v in attr.items(): k = string.lower(k) if k in attrMap.keys(): j = attrMap[k] func = j[1] try: A[j[0]] = (func is None) and v or apply(func,(v,)) except: self.syntax_error('%s: invalid value %s'%(k,v)) else: self._syntax_error('invalid attribute name %s'%k) return A
5,815
def _reset(self, style): '''reset the parser''' xmllib.XMLParser.reset(self)
def _reset(self, style): '''reset the parser''' xmllib.XMLParser.reset(self)
5,816
def _AsciiHexTest(text='What is the average velocity of a sparrow?'): "Do the obvious test for whether Ascii Hex encoding works" print 'Plain text:', text encoded = _AsciiHexEncode(text) print 'Encoded:', encoded decoded = _AsciiHexDecode(encoded) print 'Decoded:', decoded if decoded == text: print 'Passed' else: print 'Failed!'
def _AsciiHexTest(text='What is the average velocity of a sparrow?'): "Do the obvious test for whether Ascii Hex encoding works" print 'Plain text:', text encoded = _AsciiHexEncode(text) print 'Encoded:', encoded decoded = _AsciiHexDecode(encoded) print 'Decoded:', decoded if decoded == text: print 'Passed' else: print 'Failed!'
5,817
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
5,818
def beforeBuild(self): # keep track of the last run self._lastEntries = self._entries[:] self.clearEntries()
def beforeBuild(self): # keep track of the last run self._lastEntries = self._entries[:] self.clearEntries()
5,819
def notify(self, kind, stuff): """DocTemplate framework can call this with all kinds of events; we say we are interested in 'TOCEntry' events.""" if kind == 'TOCEntry': (level, text, pageNum) = stuff self.addEntry(level, text, pageNum) #print 'TOC notified of ', stuff
def notify(self, kind, stuff): """DocTemplate framework can call this with all kinds of events; we say we are interested in 'TOCEntry' events.""" if kind == 'TOCEntry': (level, text, pageNum) = stuff self.addEntry(level, text, pageNum) #print 'TOC notified of ', stuff
5,820
def addEntries(self, listOfEntries): """Bulk creation. If you knew the titles but not the page numbers, you could supply them to get sensible output on the first run.""" for (level, text, pageNum) in listOfEntries: self.addEntry(level, text, pageNum)
def addEntries(self, listOfEntries): """Bulk creation. If you knew the titles but not the page numbers, you could supply them to get sensible output on the first run.""" for (level, text, pageNum) in listOfEntries: self.addEntry(level, text, pageNum)
5,821
def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object""" self._table.drawOn(canvas, x, y, _sW)
def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object""" self._table.drawOn(canvas, x, y, _sW)
5,822
def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object""" self._table.drawOn(canvas, x, y, _sW)
def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home!The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object""" self._table.drawOn(canvas, x, y, _sW)
5,823
def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object""" self._table.drawOn(canvas, x, y, _sW)
def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object""" self._table.drawOn(canvas, x, y, _sW)
5,824
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append((0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
5,825
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum)) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
5,826
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append((1, 'Chapter %d Section %d' % (chapter, section), pgNum)) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
5,827
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data
5,828
def getSampleStory(depth=3): """Makes a story with lots of paragraphs. Uses the random TOC data and makes paragraphs to correspond to each.""" from reportlab.platypus.doctemplate import randomText from random import randint styles = getSampleStyleSheet() TOCData = getSampleTOCData(depth) story = [Paragraph("This is a demo of the table of contents object", styles['Heading1'])] toc = TableOfContents0() # empty on first pass #toc.addEntries(TOCData) # init with random page numbers story.append(toc) # the next full page should switch to internal page style story.append(NextPageTemplate("Body")) # now make some paragraphs to correspond to it for (level, text, pageNum) in TOCData: if level == 0: #page break before chapter story.append(PageBreak()) headingStyle = (styles['Heading1'], styles['Heading2'], styles['Heading3'])[level] headingPara = Paragraph(text, headingStyle) story.append(headingPara) # now make some body text for i in range(randint(1,6)): bodyPara = Paragraph(randomText(), styles['Normal']) story.append(bodyPara) return story
def getSampleStory(depth=3): """Makes a story with lots of paragraphs. Uses the random TOC data and makes paragraphs to correspond to each.""" from reportlab.platypus.doctemplate import randomText from random import randint styles = getSampleStyleSheet() TOCData = getSampleTOCData(depth) story = [Paragraph("This is a demo of the table of contents object", styles['Heading1'])] toc = TableOfContents0() # empty on first pass #toc.addEntries(TOCData) # init with random page numbers story.append(toc) # the next full page should switch to internal page style story.append(NextPageTemplate("Body")) # now make some paragraphs to correspond to it for (level, text, pageNum) in TOCData: if level == 0: #page break before chapter story.append(PageBreak()) headingStyle = (styles['Heading1'], styles['Heading2'], styles['Heading3'])[level] headingPara = Paragraph(text, headingStyle) story.append(headingPara) # now make some body text for i in range(randint(1,6)): bodyPara = Paragraph(randomText(), styles['Normal']) story.append(bodyPara) return story
5,829
def afterInit(self): """Set up the page templates""" frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([PageTemplate(id='Front',frames=frameT), PageTemplate(id='Body',frames=frameT) ]) # just need a unique key generator for outline entries; # easiest is to count all flowables in afterFlowable # and set up a counter variable here self._uniqueKey = 0
def afterInit(self): """Set up the page templates""" frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([PageTemplate(id='Front',frames=frameT), PageTemplate(id='Body',frames=frameT) ]) # just need a unique key generator for outline entries; # easiest is to count all flowables in afterFlowable # and set up a counter variable here self._uniqueKey = 0
5,830
def afterFlowable(self, flowable): """Our rule for the table of contents is simply to take the text of H1, H2 and H3 elements. We broadcast a notification to the DocTemplate, which should inform the TOC and let it pull them out. Also build an outline""" self._uniqueKey = self._uniqueKey + 1 if hasattr(flowable, 'style'): if flowable.style.name == 'Heading1': self.notify0('TOCEntry', (0, flowable.getPlainText(), self.page)) self.canv.bookmarkPage(str(self._uniqueKey)) self.canv.addOutlineEntry(flowable.getPlainText()[0:10], str(self._uniqueKey), 0)
def afterFlowable(self, flowable): """Our rule for the table of contents is simply to take the text of H1, H2 and H3 elements. We broadcast a notification to the DocTemplate, which should inform the TOC and let it pull them out. Also build an outline""" self._uniqueKey = self._uniqueKey + 1 if hasattr(flowable, 'style'): if flowable.style.name == 'Heading1': self.notify0('TOCEntry', (0, flowable.getPlainText(), self.page)) self.canv.bookmarkPage(str(self._uniqueKey)) self.canv.addOutlineEntry(flowable.getPlainText()[0:10], str(self._uniqueKey), 0)
5,831
def afterFlowable(self, flowable): """Our rule for the table of contents is simply to take the text of H1, H2 and H3 elements. We broadcast a notification to the DocTemplate, which should inform the TOC and let it pull them out. Also build an outline""" self._uniqueKey = self._uniqueKey + 1 if hasattr(flowable, 'style'): if flowable.style.name == 'Heading1': self.notify0('TOCEntry', (0, flowable.getPlainText(), self.page)) self.canv.bookmarkPage(str(self._uniqueKey)) self.canv.addOutlineEntry(flowable.getPlainText()[0:10], str(self._uniqueKey), 0)
def afterFlowable(self, flowable): """Our rule for the table of contents is simply to take the text of H1, H2 and H3 elements. We broadcast a notification to the DocTemplate, which should inform the TOC and let it pull them out. Also build an outline""" self._uniqueKey = self._uniqueKey + 1 if hasattr(flowable, 'style'): if flowable.style.name == 'Heading1': self.notify0('TOCEntry', (0, flowable.getPlainText(), self.page)) self.canv.bookmarkPage(str(self._uniqueKey)) self.canv.addOutlineEntry(flowable.getPlainText()[0:10], str(self._uniqueKey), 0)
5,832
def afterFlowable(self, flowable): """Our rule for the table of contents is simply to take the text of H1, H2 and H3 elements. We broadcast a notification to the DocTemplate, which should inform the TOC and let it pull them out. Also build an outline""" self._uniqueKey = self._uniqueKey + 1 if hasattr(flowable, 'style'): if flowable.style.name == 'Heading1': self.notify0('TOCEntry', (0, flowable.getPlainText(), self.page)) self.canv.bookmarkPage(str(self._uniqueKey)) self.canv.addOutlineEntry(flowable.getPlainText()[0:10], str(self._uniqueKey), 0)
defafterFlowable(self,flowable):"""OurruleforthetableofcontentsissimplytotakethetextofH1,H2andH3elements.WebroadcastanotificationtotheDocTemplate,whichshouldinformtheTOCandletitpullthemout.Alsobuildanoutline"""self._uniqueKey=self._uniqueKey+1ifhasattr(flowable,'style'):ifflowable.style.name=='Heading1':self.notify0('TOCEntry',(0,flowable.getPlainText(),self.page))self.canv.bookmarkPage(str(self._uniqueKey))self.canv.addOutlineEntry(flowable.getPlainText()[0:10],str(self._uniqueKey),0)
5,833
def beforePage(self): """decorate the page""" self.canv.saveState() self.canv.setStrokeColor(colors.red) self.canv.setLineWidth(5) self.canv.line(66,72,66,PAGE_HEIGHT-72) self.canv.setFont('Times-Roman',12) self.canv.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page) self.canv.restoreState()
def beforePage(self): """decorate the page""" self.canv.saveState() self.canv.setStrokeColor(colors.red) self.canv.setLineWidth(5) self.canv.line(66,72,66,PAGE_HEIGHT-72) self.canv.setFont('Times-Roman',12) self.canv.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page) self.canv.restoreState()
5,834
def beforePage(self): """decorate the page""" self.canv.saveState() self.canv.setStrokeColor(colors.red) self.canv.setLineWidth(5) self.canv.line(66,72,66,PAGE_HEIGHT-72) self.canv.setFont('Times-Roman',12) self.canv.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page) self.canv.restoreState()
def beforePage(self): """decorate the page""" self.canv.saveState() self.canv.setStrokeColor(colors.red) self.canv.setLineWidth(5) self.canv.line(66,72,66,PAGE_HEIGHT-72) self.canv.setFont('Times-Roman',12) self.canv.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page) self.canv.restoreState()
5,835
def loadImageFromSRC(self, im): "Extracts the stream, width and height" if im._image.format=='JPEG': fp=image.fp fp.seek(0) self.loadImageFromJPEG(fp) else: zlib = import_zlib() if not zlib: return self.width, self.height = im.getSize() raw = im.getRGBData() assert(len(raw) == self.width*self.height, "Wrong amount of data for image") self.streamContent = pdfutils._AsciiBase85Encode(zlib.compress(raw)) self.colorSpace = 'DeviceRGB' self.bitsPerComponent = 8 self._filters = 'ASCII85Decode','FlateDecode' #'A85','Fl' self._checkTransparency(im)
def loadImageFromSRC(self, im): "Extracts the stream, width and height" if im._image.format=='JPEG': fp=im._image.fp fp.seek(0) self.loadImageFromJPEG(fp) else: zlib = import_zlib() if not zlib: return self.width, self.height = im.getSize() raw = im.getRGBData() assert(len(raw) == self.width*self.height, "Wrong amount of data for image") self.streamContent = pdfutils._AsciiBase85Encode(zlib.compress(raw)) self.colorSpace = 'DeviceRGB' self.bitsPerComponent = 8 self._filters = 'ASCII85Decode','FlateDecode' #'A85','Fl' self._checkTransparency(im)
5,836
def toColor(arg,default=None): '''try to map an arbitrary arg to a color instance''' if isinstance(arg,Color): return arg tArg = type(arg) if tArg in _SeqTypes: return Color(arg[0],arg[1],arg[2]) elif tArg == StringType: C = getAllNamedColors() s = string.lower(arg) if C.has_key(s): return C[s] try: s = eval(arg) if isinstance(s,Color): return s except: pass try: return HexColor(arg) except: if default is None: raise 'Invalid color value', str(arg) return default
def toColor(arg,default=None): '''try to map an arbitrary arg to a color instance''' if isinstance(arg,Color): return arg tArg = type(arg) if tArg in _SeqTypes: assert 3<=len(arg)<=4, 'Can only convert 3 and 4 sequences to color' assert 0<=min(arg) and max(arg)<=1 return len(arg)==3 and Color(arg[0],arg[1],arg[2]) or CMYKColor(arg[0],arg[1],arg[2],arg[3]) elif tArg == StringType: C = getAllNamedColors() s = string.lower(arg) if C.has_key(s): return C[s] try: s = eval(arg) if isinstance(s,Color): return s except: pass try: return HexColor(arg) except: if default is None: raise 'Invalid color value', str(arg) return default
5,837
def toColor(arg,default=None): '''try to map an arbitrary arg to a color instance''' if isinstance(arg,Color): return arg tArg = type(arg) if tArg in _SeqTypes: return Color(arg[0],arg[1],arg[2]) elif tArg == StringType: C = getAllNamedColors() s = string.lower(arg) if C.has_key(s): return C[s] try: s = eval(arg) if isinstance(s,Color): return s except: pass try: return HexColor(arg) except: if default is None: raise 'Invalid color value', str(arg) return default
def toColor(arg,default=None): '''try to map an arbitrary arg to a color instance''' if isinstance(arg,Color): return arg tArg = type(arg) if tArg in _SeqTypes: return Color(arg[0],arg[1],arg[2]) elif tArg == StringType: C = getAllNamedColors() s = string.lower(arg) if C.has_key(s): return C[s] try: return toColor(eval(arg)) except: pass try: return HexColor(arg) except: if default is None: raise 'Invalid color value', str(arg) return default
5,838
def expandUserNodes0(self): """Return a new drawing which only contains primitive shapes."""
def expandUserNodes0(self): """Return a new drawing which only contains primitive shapes."""
5,839
def __init__(self,filename, pagesize=None, bottomup = 1, pageCompression=None, encoding = None, invariant = None, verbosity=0): """Create a canvas of a given size. etc. Most of the attributes are private - we will use set/get methods as the preferred interface. Default page size is A4.""" if pagesize is None: pagesize rl_config.defaultPageSize if encoding is None: encoding = rl_config.defaultEncoding if invariant is None: invariant = rl_config.invariant self._filename = filename self._encodingName = encoding self._doc = pdfdoc.PDFDocument(encoding, compression=pageCompression, invariant=invariant)
def __init__(self,filename, pagesize=None, bottomup = 1, pageCompression=None, encoding = None, invariant = None, verbosity=0): """Create a canvas of a given size. etc. Most of the attributes are private - we will use set/get methods as the preferred interface. Default page size is A4.""" if pagesize is None: pagesize = rl_config.defaultPageSize if encoding is None: encoding = rl_config.defaultEncoding if invariant is None: invariant = rl_config.invariant self._filename = filename self._encodingName = encoding self._doc = pdfdoc.PDFDocument(encoding, compression=pageCompression, invariant=invariant)
5,840
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp != dp: if sp: canv.setPageSize(self.pagesize) else: canv.setPageSize(doc.pagesize)
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp!=sp: if sp: canv.setPageSize(self.pagesize) else: canv.setPageSize(doc.pagesize)
5,841
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp != dp: if sp: canv.setPageSize(self.pagesize) else: canv.setPageSize(doc.pagesize)
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp != dp: if sp: canv.setPageSize(self.pagesize) elif cp!=dp: canv.setPageSize(doc.pagesize)
5,842
def SaveToFile(self, filename,canvas): """Open a file, and ask each object in turn to write itself to the file. Keep track of the file position at each point for use in the index at the end""" f = open(filename, 'wb') i = 1 self.xref = [] f.write("%PDF-1.2" + LINEEND) # for CID support f.write("%\355\354\266\276" + LINEEND) # do preprocessing as needed # prepare outline outline = self.outline outline.prepare(self, canvas) for obj in self.objects: pos = f.tell() self.xref.append(pos) f.write(str(i) + ' 0 obj' + LINEEND) obj.save(f) f.write('endobj' + LINEEND) i = i + 1 self.writeXref(f) self.writeTrailer(f) f.write('%%EOF') # no lineend needed on this one! f.close() # with the Mac, we need to tag the file in a special #way so the system knows it is a PDF file. #This supplied by Joe Strout if os.name == 'mac': import macfs try: macfs.FSSpec(filename).SetCreatorType('CARO','PDF ') except: pass
def SaveToFile(self, filename,canvas): """Open a file, and ask each object in turn to write itself to the file. Keep track of the file position at each point for use in the index at the end""" if type(f)==type(''): f = open(filename, 'wb') else: f = filename i = 1 self.xref = [] f.write("%PDF-1.2" + LINEEND) # for CID support f.write("%\355\354\266\276" + LINEEND) # do preprocessing as needed # prepare outline outline = self.outline outline.prepare(self, canvas) for obj in self.objects: pos = f.tell() self.xref.append(pos) f.write(str(i) + ' 0 obj' + LINEEND) obj.save(f) f.write('endobj' + LINEEND) i = i + 1 self.writeXref(f) self.writeTrailer(f) f.write('%%EOF') # no lineend needed on this one! f.close() # with the Mac, we need to tag the file in a special #way so the system knows it is a PDF file. #This supplied by Joe Strout if os.name == 'mac': import macfs try: macfs.FSSpec(filename).SetCreatorType('CARO','PDF ') except: pass
5,843
def recursiveImport(modulename, baseDir=None, noCWD=0, debug=0): """Dynamically imports possible packagized module, or raises ImportError""" import imp parts = string.split(modulename, '.') name = parts[0] if baseDir is None: path = sys.path[:] else: if type(baseDir) not in SeqTypes path = [baseDir] else: path = list(baseDir) path = filter(None,basDir) if noCWD: if '.' in path: path.remove('.') abspath = os.path.abspath('.') if abspath in path: path.remove(abspath) else: if '.' not in path: path.insert(0,'.') if debug: import pprint pp = pprint.pprint print 'path=',pp(path) #make import errors a bit more informative fullName = name try: (file, pathname, description) = imp.find_module(name, path) childModule = parentModule = imp.load_module(name, file, pathname, description) if debug: print 'imported module = %s' % parentModule for name in parts[1:]: fullName = fullName + '.' + name if debug: print 'trying part %s' % name (file, pathname, description) = imp.find_module(name, [os.path.dirname(parentModule.__file__)]) childModule = imp.load_module(fullName, file, pathname, description) if debug: print 'imported module = %s' % childModule setattr(parentModule, name, childModule) parentModule = childModule except ImportError: msg = "cannot import '%s' while attempting recursive import of '%s'" % (fullName, modulename) if baseDir: msg = msg + " under paths '%s'" % `path` raise ImportError, msg return childModule
def recursiveImport(modulename, baseDir=None, noCWD=0, debug=0): """Dynamically imports possible packagized module, or raises ImportError""" import imp parts = string.split(modulename, '.') name = parts[0] if baseDir is None: path = sys.path[:] else: if type(baseDir) not in SeqTypes: path = [baseDir] else: path = list(baseDir) path = filter(None,basDir) if noCWD: if '.' in path: path.remove('.') abspath = os.path.abspath('.') if abspath in path: path.remove(abspath) else: if '.' not in path: path.insert(0,'.') if debug: import pprint pp = pprint.pprint print 'path=',pp(path) #make import errors a bit more informative fullName = name try: (file, pathname, description) = imp.find_module(name, path) childModule = parentModule = imp.load_module(name, file, pathname, description) if debug: print 'imported module = %s' % parentModule for name in parts[1:]: fullName = fullName + '.' + name if debug: print 'trying part %s' % name (file, pathname, description) = imp.find_module(name, [os.path.dirname(parentModule.__file__)]) childModule = imp.load_module(fullName, file, pathname, description) if debug: print 'imported module = %s' % childModule setattr(parentModule, name, childModule) parentModule = childModule except ImportError: msg = "cannot import '%s' while attempting recursive import of '%s'" % (fullName, modulename) if baseDir: msg = msg + " under paths '%s'" % `path` raise ImportError, msg return childModule
5,844
def process(datafilename): parser = stdparser.PPMLParser() rawdata = open(datafilename).read() parser.feed(rawdata) pres = parser.getPresentation() pres.save() parser.close()
def process(datafilename): parser = stdparser.PPMLParser() rawdata = open(datafilename).read() parser.feed(rawdata) pres = parser.getPresentation() pres.save() parser.close()
5,845
def __init__(self, encoding=DEFAULT_ENCODING): self.encoding = encoding # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages outlines = self.Outlines = self.outline = PDFOutlines() cat.Outlines = outlines self.info = self.Info = PDFInfo() self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional self.fontMapping = {} MakeStandardEnglishFontObjects(self, encoding)
def __init__(self, encoding=DEFAULT_ENCODING, dummyoutline=0): self.encoding = encoding # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages outlines = self.Outlines = self.outline = PDFOutlines() cat.Outlines = outlines self.info = self.Info = PDFInfo() self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional self.fontMapping = {} MakeStandardEnglishFontObjects(self, encoding)
5,846
def __init__(self, encoding=DEFAULT_ENCODING): self.encoding = encoding # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages outlines = self.Outlines = self.outline = PDFOutlines() cat.Outlines = outlines self.info = self.Info = PDFInfo() self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional self.fontMapping = {} MakeStandardEnglishFontObjects(self, encoding)
def __init__(self, encoding=DEFAULT_ENCODING): self.encoding = encoding # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages if dummyoutline: outlines = PDFOutlines0() else: outlines = PDFOutlines() self.Outlines = self.outline = outlines cat.Outlines = outlines self.info = self.Info = PDFInfo() self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional self.fontMapping = {} MakeStandardEnglishFontObjects(self, encoding)
5,847
def format(self): # register the Catalog/INfo and then format the objects one by one until exhausted # (possible infinite loop if there is a bug that continually makes new objects/refs...) # prepare outline outline = self.outline outline.prepare(self, canvas) cat = self.Catalog info = self.Info self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional counter = 0 # start at first object (object 1 after preincrement) ids = [] # the collection of object ids in object number order numbertoid = self.numberToId idToNV = self.idToObjectNumberAndVersion idToOb = self.idToObject idToOf = self.idToOffset ### note that new entries may be "appended" DURING FORMATTING done = None File = PDFFile() # output collector while done is None: counter = counter+1 # do next object... if numbertoid.has_key(counter): id = numbertoid[counter] #printidToOb obj = idToOb[id] IO = PDFIndirectObject(id, obj) IOf = IO.format(self) # add a comment to the PDF output if DoComments: File.add("%% %s %s %s" % (repr(id), repr(repr(obj)[:50]), LINEEND)) offset = File.add(IOf) idToOf[id] = offset ids.append(id) else: done = 1 # sanity checks (must happen AFTER formatting) lno = len(numbertoid) if counter-1!=lno: raise ValueError, "counter %s doesn't match number to id dictionary %s" %(counter, lno) # now add the xref xref = PDFCrossReferenceTable() xref.addsection(0, ids) xreff = xref.format(self) xrefoffset = File.add(xreff) # now add the trailer trailer = PDFTrailer( startxref = xrefoffset, Size = lno, Root = self.Reference(cat), Info = self.Reference(info) ) trailerf = trailer.format(self) File.add(trailerf) # return string format for pdf file return File.format(self)
def format(self): # register the Catalog/INfo and then format the objects one by one until exhausted # (possible infinite loop if there is a bug that continually makes new objects/refs...) # prepare outlinecat = self.Catalog info = self.Info self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional counter = 0 # start at first object (object 1 after preincrement) ids = [] # the collection of object ids in object number order numbertoid = self.numberToId idToNV = self.idToObjectNumberAndVersion idToOb = self.idToObject idToOf = self.idToOffset ### note that new entries may be "appended" DURING FORMATTING done = None File = PDFFile() # output collector while done is None: counter = counter+1 # do next object... if numbertoid.has_key(counter): id = numbertoid[counter] #printidToOb obj = idToOb[id] IO = PDFIndirectObject(id, obj) IOf = IO.format(self) # add a comment to the PDF output if DoComments: File.add("%% %s %s %s" % (repr(id), repr(repr(obj)[:50]), LINEEND)) offset = File.add(IOf) idToOf[id] = offset ids.append(id) else: done = 1 # sanity checks (must happen AFTER formatting) lno = len(numbertoid) if counter-1!=lno: raise ValueError, "counter %s doesn't match number to id dictionary %s" %(counter, lno) # now add the xref xref = PDFCrossReferenceTable() xref.addsection(0, ids) xreff = xref.format(self) xrefoffset = File.add(xreff) # now add the trailer trailer = PDFTrailer( startxref = xrefoffset, Size = lno, Root = self.Reference(cat), Info = self.Reference(info) ) trailerf = trailer.format(self) File.add(trailerf) # return string format for pdf file return File.format(self)
5,848
def testpage(document): P = PDFPage() P.Contents = teststream() pages = document.Pages P.Parent = document.Reference(pages) P.MediaBox = PDFArray([0, 0, 595, 841]) resources = PDFResourceDictionary() resources.allProcs() # enable all procsets resources.basicFonts() P.Resources = resources pages.addPage(P)
def testpage(document): P = PDFPage() P.Contents = teststream() pages = document.Pages P.Parent = document.Reference(pages) P.MediaBox = PDFArray([0, 0, 595, 841]) resources = PDFResourceDictionary() resources.allProcs() # enable all procsets resources.basicFonts() P.Resources = resources pages.addPage(P)
5,849
def testpage(document): P = PDFPage() P.Contents = teststream() pages = document.Pages P.Parent = document.Reference(pages) P.MediaBox = PDFArray([0, 0, 595, 841]) resources = PDFResourceDictionary() resources.allProcs() # enable all procsets resources.basicFonts() P.Resources = resources pages.addPage(P)
def testpage(document): P = PDFPage() P.Contents = teststream() pages = document.Pages P.Parent = document.Reference(pages) P.MediaBox = PDFArray([0, 0, 595, 841]) resources = PDFResourceDictionary() resources.allProcs() # enable all procsets resources.basicFonts() P.Resources = resources pages.addPage(P)
5,850
def format(self, document): return self.text '''
def format(self, document): return self.text '''
5,851
def format(self, document): self.BBox = self.BBox or PDFArray([self.lowerx, self.lowery, self.upperx, self.uppery]) self.Matrix = self.Matrix or PDFArray([1, 0, 0, 1, 0, 0]) if not self.Annots: self.Annots = None else: raise ValueError, "annotations not reimplemented yet" if not self.Contents: stream = self.stream if not stream: self.Contents = teststream() else: S = PDFStream() S.content = stream # need to add filter stuff (?) S.__Comment__ = "xobject form stream" self.Contents = S if not self.Resources: resources = PDFResourceDictionary() # fonts! resources.basicFonts() if self.hasImages: resources.allProcs() else: resources.basicProcs() sdict = self.Contents.dictionary sdict["Type"] = PDFName("XObject") sdict["Subtype"] = PDFName("Form") sdict["FormType"] = 1 sdict["BBox"] = self.BBox sdict["Matrix"] = self.Matrix sdict["Resources"] = resources return self.Contents.format(document)
def format(self, document): self.BBox = self.BBox or PDFArray([self.lowerx, self.lowery, self.upperx, self.uppery]) self.Matrix = self.Matrix or PDFArray([1, 0, 0, 1, 0, 0]) if not self.Annots: self.Annots = None else: raise ValueError, "annotations not reimplemented yet" if not self.Contents: stream = self.stream if not stream: self.Contents = teststream() else: S = PDFStream() S.content = stream # need to add filter stuff (?) S.__Comment__ = "xobject form stream" self.Contents = S if not self.Resources: resources = PDFResourceDictionary() # fonts! resources.basicFonts() if self.hasImages: resources.allProcs() else: resources.basicProcs() sdict = self.Contents.dictionary sdict["Type"] = PDFName("XObject") sdict["Subtype"] = PDFName("Form") sdict["FormType"] = 1 sdict["BBox"] = self.BBox sdict["Matrix"] = self.Matrix sdict["Resources"] = resources return self.Contents.format(document)
5,852
def format(self, document): strings = map(str, self.strings) # final conversion, in case of lazy objects return string.join(self.strings, "")
def format(self, document): strings = map(str, self.strings) # final conversion, in case of lazy objects return string.join(self.strings, "")
5,853
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
5,854
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
5,855
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
5,856
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
5,857
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
5,858
def handle_charref(self, name): try: if name[0] == 'x': n = string.atoi(name[1:], 16) else: n = string.atoi(name) except string.atoi_error: self.unknown_charref(name) return if 0 <=n<=255: self.handle_data(chr(n)) else: try: c = symenc[n] except KeyError: self.unknown_charref(name) return self._push(greek=1) self.handle_data(c) self._pop(greek=1)
def handle_charref(self, name): try: if name[0] == 'x': n = string.atoi(name[1:], 16) else: n = string.atoi(name) except string.atoi_error: self.unknown_charref(name) return if 0 <=n<=255: self.handle_data(chr(n)) else: try: c = symenc[n] except KeyError: self.unknown_charref(name) return self._push(greek=1) self.handle_data(c) self._pop(greek=1)
5,859
def _copyNamedContents(self,obj): self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
def _copyContents(self,obj): for child in self.contents: obj.contents.append(child) def _copyNamedContents(self,obj,aKeys=None,noCopy=('contents',)): from copy import copy self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
5,860
def _copyNamedContents(self,obj): self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
def _copyNamedContents(self,obj): self_contents = self.contents if not aKeys: aKeys = self._attrMap.keys() for (k, v) in self.__dict__.items(): if k in self_contents: pos = self_contents.index(v) setattr(obj, oldKey, obj.contents[pos])
5,861
def _copyNamedContents(self,obj): self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
def _copyNamedContents(self,obj): self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
5,862
def _copy(self,obj): """copies to obj""" obj._attrMap = self._attrMap.clone()
def _copy(self,obj): """copies to obj""" obj._attrMap = self._attrMap.clone()
5,863
def __init__(self, page, left, top, zoom): self.page = page; self.top=top; self.zoom=zoom
def __init__(self, page, left, top, zoom): self.page = page; self.top=top; self.zoom=zoom
5,864
def cvs_checkout(d): os.chdir(d) cvsdir = os.path.join(groupdir,projdir) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s %s' % (tagname,projdir)), 'the export phase') else: do_exec(cvs+' co %s' % projdir, 'the checkout phase') if py2pdf: # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("mv reportlab/demos/py2pdf/idle_print.py %s" % dst, "mv idle_print.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt reportlab/pdfgen/test", "rm") do_exec("mv %s %s" % (projdir,dst), "moving %s to %s" %(projdir,py2pdf_dir)) do_exec("chmod a+x %s/py2pdf.py %s/idle_print.py" % (dst, dst), "chmod") CVS_remove(dst)
def cvs_checkout(d): os.chdir(d) cvsdir = os.path.join(d,projdir) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s %s' % (tagname,projdir)), 'the export phase') else: do_exec(cvs+' co %s' % projdir, 'the checkout phase') if py2pdf: # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("mv reportlab/demos/py2pdf/idle_print.py %s" % dst, "mv idle_print.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt reportlab/pdfgen/test", "rm") do_exec("mv %s %s" % (projdir,dst), "moving %s to %s" %(projdir,py2pdf_dir)) do_exec("chmod a+x %s/py2pdf.py %s/idle_print.py" % (dst, dst), "chmod") CVS_remove(dst)
5,865
def setUp(self): from time import time from reportlab.lib.utils import get_rl_tempdir self._tempdir = get_rl_tempdir('reportlab_test','tmp_%d' % time()) _testmodulename = os.path.join(self._tempdir,'test_module_%d.py' % time()) f = open(_testmodulename,'w') f.write('__all__=[]\n') f.close() self._testmodulename = os.path.splitext(os.path.basename(_testmodulename))[0]
def setUp(self): from time import time from reportlab.lib.utils import get_rl_tempdir s = `int(time())` + `self.count` self.count += 1 self._tempdir = get_rl_tempdir('reportlab_test','tmp_%s' % s) _testmodulename = os.path.join(self._tempdir,'test_module_%s.py' % s) f = open(_testmodulename,'w') f.write('__all__=[]\n') f.close() self._testmodulename = os.path.splitext(os.path.basename(_testmodulename))[0]
5,866
def test(): #grab all drawings from the test module and write out. #make a page of links in HTML to assist viewing. import os from reportlab.graphics.testshapes import getAllTestDrawings drawings = [] if not os.path.isdir('pmout'): os.mkdir('pmout') htmlTop = """<html><head><title>renderGD output results</title></head> <body> <h1>renderPM results of output</h1> """ htmlBottom = """</body> </html> """ html = [htmlTop]
def test(): #grab all drawings from the test module and write out. #make a page of links in HTML to assist viewing. import os from reportlab.graphics.testshapes import getAllTestDrawings drawings = [] if not os.path.isdir('pmout'): os.mkdir('pmout') htmlTop = """<html><head><title>renderPM output results</title></head> <body> <h1>renderPM results of output</h1> """ htmlBottom = """</body> </html> """ html = [htmlTop]
5,867
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),**kw): import time, socket self.fn = fn if mode!='w': return self.store = store = {} if sys.exc_info() != (None,None,None): import traceback s = getStringIO() traceback.print_exc(None,s) store['__traceback'] = s.getvalue() cwd=os.getcwd() lcwd = os.listdir(cwd) exed = os.path.abspath(os.path.dirname(sys.argv[0])) store.update({ 'gmt': time.asctime(time.gmtime(time.time())), 'platform': sys.platform, 'version': sys.version, 'executable': sys.executable, 'prefix': sys.prefix, 'path': sys.path, 'argv': sys.argv, 'cwd': cwd, 'hostname': socket.gethostname(), 'lcwd': lcwd, }) if exed!=cwd: store.update({'exed': exed, 'lexed': os.listdir(exed), }) if hasattr(os,'uname'): store.update({ 'uname': os.uname(), 'ctermid': os.ctermid(), 'getgid': os.getgid(), 'getuid': os.getuid(), 'getegid': os.getegid(), 'geteuid': os.geteuid(), 'getlogin': os.getlogin(), 'getgroups': os.getgroups(), 'getpgrp': os.getpgrp(), 'getpid': os.getpid(), 'getppid': os.getppid(), }) if getScript: fn = os.path.abspath(sys.argv[0]) if os.path.isfile(fn): store['__script'] = open(fn,'r').read() module_versions = {} for n,m in sys.modules.items(): if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.': v = getattr(m,'__version__',None) if v: module_versions[n] = v store['__module_versions'] = module_versions self.store['__payload'] = {} self._add(kw)
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),capture_traceback=1, **kw): import time, socket self.fn = fn if mode!='w': return self.store = store = {} if sys.exc_info() != (None,None,None): import traceback s = getStringIO() traceback.print_exc(None,s) store['__traceback'] = s.getvalue() cwd=os.getcwd() lcwd = os.listdir(cwd) exed = os.path.abspath(os.path.dirname(sys.argv[0])) store.update({ 'gmt': time.asctime(time.gmtime(time.time())), 'platform': sys.platform, 'version': sys.version, 'executable': sys.executable, 'prefix': sys.prefix, 'path': sys.path, 'argv': sys.argv, 'cwd': cwd, 'hostname': socket.gethostname(), 'lcwd': lcwd, }) if exed!=cwd: store.update({'exed': exed, 'lexed': os.listdir(exed), }) if hasattr(os,'uname'): store.update({ 'uname': os.uname(), 'ctermid': os.ctermid(), 'getgid': os.getgid(), 'getuid': os.getuid(), 'getegid': os.getegid(), 'geteuid': os.geteuid(), 'getlogin': os.getlogin(), 'getgroups': os.getgroups(), 'getpgrp': os.getpgrp(), 'getpid': os.getpid(), 'getppid': os.getppid(), }) if getScript: fn = os.path.abspath(sys.argv[0]) if os.path.isfile(fn): store['__script'] = open(fn,'r').read() module_versions = {} for n,m in sys.modules.items(): if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.': v = getattr(m,'__version__',None) if v: module_versions[n] = v store['__module_versions'] = module_versions self.store['__payload'] = {} self._add(kw)
5,868
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),**kw): import time, socket self.fn = fn if mode!='w': return self.store = store = {} if sys.exc_info() != (None,None,None): import traceback s = getStringIO() traceback.print_exc(None,s) store['__traceback'] = s.getvalue() cwd=os.getcwd() lcwd = os.listdir(cwd) exed = os.path.abspath(os.path.dirname(sys.argv[0])) store.update({ 'gmt': time.asctime(time.gmtime(time.time())), 'platform': sys.platform, 'version': sys.version, 'executable': sys.executable, 'prefix': sys.prefix, 'path': sys.path, 'argv': sys.argv, 'cwd': cwd, 'hostname': socket.gethostname(), 'lcwd': lcwd, }) if exed!=cwd: store.update({'exed': exed, 'lexed': os.listdir(exed), }) if hasattr(os,'uname'): store.update({ 'uname': os.uname(), 'ctermid': os.ctermid(), 'getgid': os.getgid(), 'getuid': os.getuid(), 'getegid': os.getegid(), 'geteuid': os.geteuid(), 'getlogin': os.getlogin(), 'getgroups': os.getgroups(), 'getpgrp': os.getpgrp(), 'getpid': os.getpid(), 'getppid': os.getppid(), }) if getScript: fn = os.path.abspath(sys.argv[0]) if os.path.isfile(fn): store['__script'] = open(fn,'r').read() module_versions = {} for n,m in sys.modules.items(): if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.': v = getattr(m,'__version__',None) if v: module_versions[n] = v store['__module_versions'] = module_versions self.store['__payload'] = {} self._add(kw)
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),**kw): import time, socket self.fn = fn if mode!='w': return self.store = store = {} if capture_traceback and sys.exc_info() != (None,None,None): import traceback s = getStringIO() traceback.print_exc(None,s) store['__traceback'] = s.getvalue() cwd=os.getcwd() lcwd = os.listdir(cwd) exed = os.path.abspath(os.path.dirname(sys.argv[0])) store.update({ 'gmt': time.asctime(time.gmtime(time.time())), 'platform': sys.platform, 'version': sys.version, 'executable': sys.executable, 'prefix': sys.prefix, 'path': sys.path, 'argv': sys.argv, 'cwd': cwd, 'hostname': socket.gethostname(), 'lcwd': lcwd, }) if exed!=cwd: store.update({'exed': exed, 'lexed': os.listdir(exed), }) if hasattr(os,'uname'): store.update({ 'uname': os.uname(), 'ctermid': os.ctermid(), 'getgid': os.getgid(), 'getuid': os.getuid(), 'getegid': os.getegid(), 'geteuid': os.geteuid(), 'getlogin': os.getlogin(), 'getgroups': os.getgroups(), 'getpgrp': os.getpgrp(), 'getpid': os.getpid(), 'getppid': os.getppid(), }) if getScript: fn = os.path.abspath(sys.argv[0]) if os.path.isfile(fn): store['__script'] = open(fn,'r').read() module_versions = {} for n,m in sys.modules.items(): if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.': v = getattr(m,'__version__',None) if v: module_versions[n] = v store['__module_versions'] = module_versions self.store['__payload'] = {} self._add(kw)
5,869
def split(self, aW, aH): S = self._CPage and [CondPageBreak(aH+1)] or [] for f in self._flowables: S.append(f) return S
def split(self, aW, aH): S = getattr(self,'_CPage',1) and [CondPageBreak(aH+1)] or [] for f in self._flowables: S.append(f) return S
5,870
def writeXref(self, f): self.startxref = f.tell() f.write('xref' + LINEEND) f.write('0 %d' % (len(self.objects) + 1) + LINEEND) f.write('0000000000 65535 f' + LINEEND) for pos in self.xref: f.write('%0.10d 00000 n' % pos + LINEEND)
defwriteXref(self,f):self.startxref=f.tell()f.write('xref'+LINEEND)f.write('0%d'%(len(self.objects)+1)+LINEEND)f.write('000000000065535f'+LINEEND)forposinself.xref:f.write('%0.10d00000n'%pos+LINEEND)
5,871
def writeTrailer(self, f): f.write('trailer' + LINEEND) f.write('<< /Size %d /Root %d 0 R /Info %d 0 R>>' % (len(self.objects) + 1, 1, self.infopos) + LINEEND) f.write('startxref' + LINEEND) f.write(str(self.startxref) + LINEEND)
def writeTrailer(self, f): f.write('trailer' + LINEEND) f.write('<< /Size %d /Root %d 0 R /Info %d 0 R>>' % (len(self.objects) + 1, 1, self.infopos) + LINEEND) f.write('startxref' + LINEEND) f.write(str(self.startxref) + LINEEND)
5,872
def centroid(P): '''compute average point of a set of points''' fn = float(len(P)) return reduce(lambda x,y: (x[0]+y[0]/fn,x[1]+y[1]/fn),P,(0,0))
def centroid(P): '''compute average point of a set of points''' return reduce(lambda x,y, fn=float(len(P)): (x[0]+y[0]/fn,x[1]+y[1]/fn),P,(0,0))
5,873
def goodTest(x,t,tb=0,**kw): try: P=_pyRXP.Parser(**kw) r = P(x) rb = 0 except: et, ev, _unused = sys.exc_info() r = '%s %s' % (et.__name__, str(ev)) rb = 1 s = '' for k,v in kw.items(): s = s+', %s=%s' % (k,str(v)) if type(t) is type(''): t = t.replace('\r','\\r') t = t.replace('\n','\\n') if type(r) is type(''): r = r.replace('\r','\\r') r = r.replace('\n','\\n') print >>_logf, '%s.Parser(%s)(%s)'%(_pyRXP.__name__,s[2:],repr(x)), if r==t and rb==tb: print >>_logf, 'OK' _dot('.') else: _dot('E') print >>_logf,'\nBAD got ', r print >>_logf,'Expected', t
def goodTest(x,t,tb=0,inOnly=0,**kw): try: P=_pyRXP.Parser(**kw) r = P(x) rb = 0 except: et, ev, _unused = sys.exc_info() r = '%s %s' % (et.__name__, str(ev)) rb = 1 s = '' for k,v in kw.items(): s = s+', %s=%s' % (k,str(v)) if type(t) is type(''): t = t.replace('\r','\\r') t = t.replace('\n','\\n') if type(r) is type(''): r = r.replace('\r','\\r') r = r.replace('\n','\\n') print >>_logf, '%s.Parser(%s)(%s)'%(_pyRXP.__name__,s[2:],repr(x)), if r==t and rb==tb: print >>_logf, 'OK' _dot('.') else: _dot('E') print >>_logf,'\nBAD got ', r print >>_logf,'Expected', t
5,874
def goodTest(x,t,tb=0,**kw): try: P=_pyRXP.Parser(**kw) r = P(x) rb = 0 except: et, ev, _unused = sys.exc_info() r = '%s %s' % (et.__name__, str(ev)) rb = 1 s = '' for k,v in kw.items(): s = s+', %s=%s' % (k,str(v)) if type(t) is type(''): t = t.replace('\r','\\r') t = t.replace('\n','\\n') if type(r) is type(''): r = r.replace('\r','\\r') r = r.replace('\n','\\n') print >>_logf, '%s.Parser(%s)(%s)'%(_pyRXP.__name__,s[2:],repr(x)), if r==t and rb==tb: print >>_logf, 'OK' _dot('.') else: _dot('E') print >>_logf,'\nBAD got ', r print >>_logf,'Expected', t
def goodTest(x,t,tb=0,**kw): try: P=_pyRXP.Parser(**kw) r = P(x) rb = 0 except: et, ev, _unused = sys.exc_info() r = '%s %s' % (et.__name__, str(ev)) rb = 1 s = '' for k,v in kw.items(): s = s+', %s=%s' % (k,str(v)) if type(t) is type(''): t = t.replace('\r','\\r') t = t.replace('\n','\\n') if type(r) is type(''): r = r.replace('\r','\\r') r = r.replace('\n','\\n') print >>_logf, '%s.Parser(%s)(%s)'%(_pyRXP.__name__,s[2:],repr(x)), if (inOnly and t in r) or (r==t) and rb==tb: print >>_logf, 'OK' _dot('.') else: _dot('E') print >>_logf,'\nBAD got ', r print >>_logf,'Expected', t
5,875
def failTest(x,t,tb=1,**kw): goodTest(x,t,tb,**kw)
def failTest(x,t,tb=1,inOnly=0,**kw): goodTest(x,t,tb,inOnly=inOnly,**kw) def bigDepth(n): return n and '<tag%d>%s</tag%d>' % (n,bigDepth(n-1),n) or 'middle'
5,876
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)
deffailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) _runTests(pyRXP):failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) globalfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) _pyRXPfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) _pyRXPfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) =failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) pyRXPfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) printfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) >>_logf,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) '#############failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) Testing',pyRXP.__name__failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) try:failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) forfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) k,vfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) infailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) pyRXP.parser_flags.items():failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) eval('pyRXP.Parser(%s=%d)'failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) %failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) (k,v))failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) printfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) >>_logf,'ParserfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) keywordsfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) OK'failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) _dot('.')failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) except:failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) traceback.print_exc()failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) printfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) >>_logf,'ParserfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) keywordsfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) BAD'failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) _dot('E')failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) try:failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) forfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) k,vfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) infailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) pyRXP.parser_flags.items():failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) eval('pyRXP.Parser()("<a/>",%s=%d)'failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) %failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) (k,v))failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) printfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) >>_logf,'Parser().parsefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) keywordsfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) OK'failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) _dot('.')failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) except:failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) traceback.print_exc()failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) printfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) >>_logf,'Parser().parsefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) keywordsfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) BAD'failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) _dot('E')failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a></a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None))failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a></a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),ExpandEmpty=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a></a>',['a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None],MakeMutableTree=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a/>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None))failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a/>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),ExpandEmpty=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a/>',['a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None],MakeMutableTree=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a/>',['a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None],ExpandEmpty=1,MakeMutableTree=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) failTest('</a>',"ErrorfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) Error:failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) EndfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) tagfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) </a>failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) outsidefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) offailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) anyfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) element\nfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) infailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) unnamedfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) entityfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) atfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) linefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 1failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) charfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 4failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) offailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [unknown]\nEndfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) tagfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) </a>failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) outsidefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) offailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) anyfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) element\nParsefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) Failed!\n")failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a>A<!--comment--></a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['A'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None))failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a>A<!--comment--></a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['A'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),ExpandEmpty=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a>A<!--comment--></a>',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('<!--',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['comment'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ReturnComments=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['A<&>'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None))failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a>A&lt;&amp;&gt;</a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) '<',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) '&',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) '>'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) MergePCData=0)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<!--comment--><a/>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),ReturnComments=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<!--comment--><a/>',[('<!--',None,['comment'],None),('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],ReturnComments=1,ReturnList=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<!--comment--><a/>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),ReturnComments=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) failTest('<?xmlfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) version="1.0"failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) encoding="LATIN-1"?></a>',"ErrorfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) UnknownfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) declaredfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) encodingfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) LATIN-1\nInternalfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) error,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ParserPushfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) failed!\n")failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<?workfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) version="1.0"failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) encoding="utf-8"?><a/>',[('<?',{'name':'work'},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['version="1.0"failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) encoding="utf-8"'],None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],IgnorePlacementErrors=1,ReturnList=1,ReturnProcessingInstructions=1,ReturnComments=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a>\nHello\n<b>cruel\n</b>\nWorld\n</a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['\nHello\n',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('b',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['cruel\n'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) (('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 2,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 3),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 3,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 4))),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) '\nWorld\n'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) (('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 0,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 3),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 5,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 4))),fourth=pyRXP.recordLocation,srcName='aaa')failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<afailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) aname="ANAME"failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) aother="AOTHER">\nHello\n<bfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) bname="BNAME"failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) bother="BOTHER">cruel\n</b>\nWorld\n</a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {"aname":failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) "ANAME",failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) "aother":failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) "AOTHER"},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['\nHello\n',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('b',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {"bname":failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) "BNAME",failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) "bother":failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) "BOTHER"},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['cruel\n'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) (('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 2,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 33),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 3,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 4))),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) '\nWorld\n'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) (('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 0,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 33),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('aaa',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 5,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 4))),fourth=pyRXP.recordLocation,srcName='aaa')failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a><![CDATA[<a>]]></a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['<a>'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None))failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('<a><![CDATA[<a>]]></a>',('a',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [('<![CDATA[',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['<a>'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),ReturnCDATASectionsAsTuples=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) goodTest('''<foo:AfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) xmlns:foo="http://www.foo.org/"><foo:B><foo:CfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) xmlns:foo="http://www.bar.org/"><foo:D>abcd</foo:D></foo:C></foo:B><foo:B/><A>barefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) A<C>barefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) C</C><B>barefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) B</B></A><AfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) xmlns="http://default.reportlab.com/"failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) xmlns:bongo="http://bongo.reportlab.com/">defaultfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) nsfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) A<bongo:A>bongofailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) A</bongo:A><B>defaultfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) NSfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) B</B></A></foo:A>''',('{http://www.foo.org/}A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {'xmlns:foo':failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 'http://www.foo.org/'},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [('{http://www.foo.org/}B',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [('{http://www.bar.org/}C',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {'xmlns:foo':failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 'http://www.bar.org/'},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) [('{http://www.bar.org/}D',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['abcd'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('{http://www.foo.org/}B',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['barefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('C',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['barefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) C'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('B',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['barefailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) B'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('{http://default.reportlab.com/}A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) {'xmlns':failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 'http://default.reportlab.com/',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 'xmlns:bongo':failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) 'http://bongo.reportlab.com/'},failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['defaultfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) nsfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('{http://bongo.reportlab.com/}A',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['bongofailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) A'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ('{http://default.reportlab.com/}B',failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None,failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) ['defaultfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) NSfailTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) B'],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None)],failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) None),XMLNamespaces=1,ReturnNamespaceAttributes=1)failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1) failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1)
5,877
def _calc(self):
def _calc(self):
5,878
def _calc(self):
def_calc(self):
5,879
def _drawLines(self): for op, (sc, sr), (ec, er), weight, color in self._linecmds: if sc < 0: sc = sc + self._ncols if ec < 0: ec = ec + self._ncols if sr < 0: sr = sr + self._nrows if er < 0: er = er + self._nrows if op == 'GRID': self._drawBox( (sc, sr), (ec, er), weight, color) self._drawInnerGrid( (sc, sr), (ec, er), weight, color) elif op in ('BOX', 'OUTLINE',): self._drawBox( (sc, sr), (ec, er), weight, color) elif op == 'INNERGRID': self._drawInnerGrid( (sc, sr), (ec, er), weight, color) elif op == 'LINEBELOW': self._drawHLines((sc, sr+1), (ec, er+1), weight, color) elif op == 'LINEABOVE': self._drawHLines((sc, sr), (ec, er), weight, color) elif op == 'LINEBEFORE': self._drawVLines((sc, sr), (ec, er), weight, color) elif op == 'LINEAFTER': self._drawVLines((sc+1, sr), (ec+1, er), weight, color) else: raise ValueError, "Unknown line style %s" % op self._curcolor = None
def _drawLines(self): for op, (sc, sr), (ec, er), weight, color in self._linecmds: if sc < 0: sc = sc + self._ncols if ec < 0: ec = ec + self._ncols if sr < 0: sr = sr + self._nrows if er < 0: er = er + self._nrows getattr(self,_LineOpMap.get(op, '_drawUnknown' ))( (sc, sr), (ec, er), weight, color) self._curcolor = None
5,880
def _splitRows(self,availHeight): self._calc() 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
5,881
def split(self, availWidth, availHeight): if self.splitByRow: if self._width>availWidth: return [] return self._splitRows(availHeight) else: raise NotImplementedError
def split(self, availWidth, availHeight): if self.splitByRow: if self._width>availWidth: return [] return self._splitRows(availHeight) else: raise NotImplementedError
5,882
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): #print "cellstyle is ", repr(cellstyle), id(cellstyle) if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: #print "setting cell color to %s" % `cellstyle.color` self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontname or cellstyle.fontsize != cur.fontsize: #print "setting font: %s, %s, %s" % (cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle #print "leading is ", cellstyle.leading, "size is", cellstyle.fontsize just = cellstyle.alignment #print "alignment is ", just if just == 'LEFT': draw = self.canv.drawString x = colpos + cellstyle.leftPadding elif just in ('CENTRE', 'CENTER'): draw = self.canv.drawCentredString x = colpos + colwidth * 0.5 elif just == 'RIGHT': draw = self.canv.drawRightString x = colpos + colwidth - cellstyle.rightPadding else: raise ValueError, 'Invalid justification %s' % just
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): #print "cellstyle is ", repr(cellstyle), id(cellstyle) if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: #print "setting cell color to %s" % `cellstyle.color` self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontname or cellstyle.fontsize != cur.fontsize: #print "setting font: %s, %s, %s" % (cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle #print "leading is ", cellstyle.leading, "size is", cellstyle.fontsize just = cellstyle.alignment #print "alignment is ", just if just == 'LEFT': draw = self.canv.drawString x = colpos + cellstyle.leftPadding elif just in ('CENTRE', 'CENTER'): draw = self.canv.drawCentredString x = colpos + colwidth * 0.5 elif just == 'RIGHT': draw = self.canv.drawRightString x = colpos + colwidth - cellstyle.rightPadding else: raise ValueError, 'Invalid justification %s' % just
5,883
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): #print "cellstyle is ", repr(cellstyle), id(cellstyle) if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: #print "setting cell color to %s" % `cellstyle.color` self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontname or cellstyle.fontsize != cur.fontsize: #print "setting font: %s, %s, %s" % (cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle #print "leading is ", cellstyle.leading, "size is", cellstyle.fontsize just = cellstyle.alignment #print "alignment is ", just if just == 'LEFT': draw = self.canv.drawString x = colpos + cellstyle.leftPadding elif just in ('CENTRE', 'CENTER'): draw = self.canv.drawCentredString x = colpos + colwidth * 0.5 elif just == 'RIGHT': draw = self.canv.drawRightString x = colpos + colwidth - cellstyle.rightPadding else: raise ValueError, 'Invalid justification %s' % just
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): #print "cellstyle is ", repr(cellstyle), id(cellstyle) if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: #print "setting cell color to %s" % `cellstyle.color` self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontname or cellstyle.fontsize != cur.fontsize: #print "setting font: %s, %s, %s" % (cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle #print "leading is ", cellstyle.leading, "size is", cellstyle.fontsize just = cellstyle.alignment #print "alignment is ", just if just == 'LEFT': draw = self.canv.drawString x = colpos + cellstyle.leftPadding elif just in ('CENTRE', 'CENTER'): draw = self.canv.drawCentredString x = colpos + colwidth * 0.5 elif just == 'RIGHT': draw = self.canv.drawRightString x = colpos + colwidth - cellstyle.rightPadding else: raise ValueError, 'Invalid justification %s' % just
5,884
def test(): from reportlab.lib.units import inch rowheights = (24, 16, 16, 16, 16) rowheights2 = (24, 16, 16, 16, 30) colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) data2 = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats\nLarge', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) styleSheet = getSampleStyleSheet() lst = [] lst.append(Paragraph("Tables", styleSheet['Heading1'])) lst.append(Paragraph(__doc__, styleSheet['BodyText'])) lst.append(Paragraph("The Tables (shown in different styles below) were created using the following code:", styleSheet['BodyText'])) lst.append(Preformatted(""" colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) rowheights = (24, 16, 16, 16, 16) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) t = Table(data, colwidths, rowheights) """, styleSheet['Code'], dedent=4)) lst.append(Paragraph(""" You can then give the Table a TableStyle object to control its format. The first TableStyle used was created as follows: """, styleSheet['BodyText'])) lst.append(Preformatted("""
def test(): from reportlab.lib.units import inch rowheights = (24, 16, 16, 16, 16) rowheights2 = (24, 16, 16, 16, 30) colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) data2 = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats\nLarge', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) styleSheet = getSampleStyleSheet() lst = [] lst.append(Paragraph("Tables", styleSheet['Heading1'])) lst.append(Paragraph(__doc__, styleSheet['BodyText'])) lst.append(Paragraph("The Tables (shown in different styles below) were created using the following code:", styleSheet['BodyText'])) lst.append(Preformatted(""" colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) rowheights = (24, 16, 16, 16, 16) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) t = Table(data, colwidths, rowheights) """, styleSheet['Code'], dedent=4)) lst.append(Paragraph(""" You can then give the Table a TableStyle object to control its format. The first TableStyle used was created as follows: """, styleSheet['BodyText'])) lst.append(Preformatted("""
5,885
def func(x): W, H = _listWrapOn(self._content,x*availWidth,self.canv) W /= x H /= x return W, H
def func(x): W, H = _listWrapOn(self._content,x*availWidth,self.canv) W /= x H /= x return W, H
5,886
def func(x): W, H = _listWrapOn(self._content,x*availWidth,self.canv) W /= x H /= x return W, H
def func(x): W, H = _listWrapOn(self._content,x*availWidth,self.canv) W /= x H /= x return W, H
5,887
def bruteForceSearchForAFM(faceName): """Looks in all AFM files on path for face with given name. Returns AFM file name or None. Ouch!""" import glob from reportlab.rl_config import T1SearchPath for dirname in T1SearchPath: if not rl_isdir(dirname): continue possibles = glob.glob(dirname + os.sep + '*.[aA][fF][mM]') for possible in possibles: (topDict, glyphDict) = parseAFMFile(possible) if topDict['FontName'] == faceName: return possible return None
def bruteForceSearchForAFM(faceName): """Looks in all AFM files on path for face with given name. Returns AFM file name or None. Ouch!""" from reportlab.rl_config import T1SearchPath for dirname in T1SearchPath: if not rl_isdir(dirname): continue possibles = glob.glob(dirname + os.sep + '*.[aA][fF][mM]') for possible in possibles: (topDict, glyphDict) = parseAFMFile(possible) if topDict['FontName'] == faceName: return possible return None
5,888
def bruteForceSearchForAFM(faceName): """Looks in all AFM files on path for face with given name. Returns AFM file name or None. Ouch!""" import glob from reportlab.rl_config import T1SearchPath for dirname in T1SearchPath: if not rl_isdir(dirname): continue possibles = glob.glob(dirname + os.sep + '*.[aA][fF][mM]') for possible in possibles: (topDict, glyphDict) = parseAFMFile(possible) if topDict['FontName'] == faceName: return possible return None
def bruteForceSearchForAFM(faceName): """Looks in all AFM files on path for face with given name. Returns AFM file name or None. Ouch!""" import glob from reportlab.rl_config import T1SearchPath for dirname in T1SearchPath: if not rl_isdir(dirname): continue possibles = rl_glob(dirname + os.sep + '*.[aA][fF][mM]') for possible in possibles: (topDict, glyphDict) = parseAFMFile(possible) if topDict['FontName'] == faceName: return possible return None
5,889
def draw(self): g = Group() ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize if self.background: x,y = self._getDrawingDimensions() g.add(Rect(-self.leftPadding,-ys,x,y, strokeColor=None, strokeWidth=0, fillColor=self.background))
def draw(self): g = Group() ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize if self.background: x,y = self._getDrawingDimensions() g.add(Rect(-self.leftPadding,-ys,x,y, strokeColor=None, strokeWidth=0, fillColor=self.background))
5,890
def draw(self): g = Group() ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize if self.background: x,y = self._getDrawingDimensions() g.add(Rect(-self.leftPadding,-ys,x,y, strokeColor=None, strokeWidth=0, fillColor=self.background))
def draw(self): g = Group() ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize if self.background: x,y = self._getDrawingDimensions() g.add(Rect(-self.leftPadding,-ys,x,y, strokeColor=None, strokeWidth=0, fillColor=self.background))
5,891
def do_exec(cmd, cmdname=None): i=os.popen(cmd,'r') print i.read() i = i.close() if i is not None: if cmdname is not None: print 'Error: %s '+ cmdname or cmd sys.exit(1)
def do_exec(cmd, cmdname=None): i=os.popen(cmd,'r') print i.read() i = i.close() if i is not None: if cmdname is not None: print 'Error: '+ cmdname or cmd sys.exit(1)
5,892
def getMacRomanWidths(self): #derive a MacRoman encoding vector MacRomanWidths = [0] * 256 for i in range(255): name = MacRomanNames[i] try: width = self.widthsByName[name] except: width = 0 MacRomanWidths[i] = width return MacRomanWidths
def getMacRomanWidths(self): #derive a MacRoman encoding vector MacRomanWidths = [0] * 256 for i in range(255): name = MacRomanNames[i] try: width = self.widthsByName[name] except: width = 0 MacRomanWidths[i] = width return MacRomanWidths
5,893
def registerFont(font): "Registers a font, including setting up info for accelerated stringWidth" #assert isinstance(font, Font), 'Not a Font: %s' % font _fonts[font.fontName] = font if not font._multiByte: if _stringWidth: _rl_accel.setFontInfo(string.lower(font.fontName), _dummyEncoding, font.face.ascent, font.face.descent, font.widths)
def registerFont(font): "Registers a font, including setting up info for accelerated stringWidth" #assert isinstance(font, Font), 'Not a Font: %s' % font fontName = str(font.fontName) _fonts[fontName] = font if not font._multiByte: if _stringWidth: _rl_accel.setFontInfo(string.lower(font.fontName), _dummyEncoding, font.face.ascent, font.face.descent, font.widths)
5,894
def registerFont(font): "Registers a font, including setting up info for accelerated stringWidth" #assert isinstance(font, Font), 'Not a Font: %s' % font _fonts[font.fontName] = font if not font._multiByte: if _stringWidth: _rl_accel.setFontInfo(string.lower(font.fontName), _dummyEncoding, font.face.ascent, font.face.descent, font.widths)
def registerFont(font): "Registers a font, including setting up info for accelerated stringWidth" #assert isinstance(font, Font), 'Not a Font: %s' % font _fonts[font.fontName] = font if not font._multiByte: if _stringWidth: _rl_accel.setFontInfo(string.lower(fontName), _dummyEncoding, font.face.ascent, font.face.descent, font.widths)
5,895
def test(): helv = TypeFace('Helvetica') registerTypeFace(helv) print helv.glyphNames[0:30] wombat = TypeFace('Wombat') print wombat.glyphNames registerTypeFace(wombat) dumpFontData()
def test(): helv = TypeFace('Helvetica') registerTypeFace(helv) print helv.glyphNames[0:30] wombat = TypeFace('Wombat') print wombat.glyphNames registerTypeFace(wombat) dumpFontData()
5,896
def draw(self): # normalize slice data g = self.makeBackground() or Group()
def draw(self): # normalize slice data g = self.makeBackground() or Group()
5,897
def _fillSide(self,L,i,angle,strokeColor,strokeWidth,fillColor): rd = self.rad_dist(angle) if rd<self.rad_dist(self._sl3d[i].mid): p = [self.CX(i,0),self.CY(i,0), self.CX(i,1),self.CY(i,1), self.OX(i,angle,1),self.OY(i,angle,1), self.OX(i,angle,0),self.OY(i,angle,0)] L.append((rd,Polygon(p, strokeColor=strokeColor, fillColor=fillColor,strokeWidth=strokeWidth,strokeLineJoin=1)))
def _fillSide(self,L,i,angle,strokeColor,strokeWidth,fillColor): rd = self.rad_dist(angle) if rd<self.rad_dist(self._sl3d[i].mid): p = [self.CX(i,0),self.CY(i,0), self.CX(i,1),self.CY(i,1), self.OX(i,angle,1),self.OY(i,angle,1), self.OX(i,angle,0),self.OY(i,angle,0)] L.append((rd,Polygon(p, strokeColor=strokeColor, fillColor=fillColor,strokeWidth=strokeWidth,strokeLineJoin=1)))
5,898
def demo(self): D = Drawing(100, 100)
def demo(self): D = Drawing(100, 100)
5,899