bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.''' #allow document a chance to look at, modify or ignore #the object(s) about to be processed self.filterFlowables(flowables) self.handle_breakBefore(flowables) self.handle_keepWithNext(flowables) f = flowables[0] del flowables[0] if f is None: return
|
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.''' #allow document a chance to look at, modify or ignore #the object(s) about to be processed self.filterFlowables(flowables) self.handle_breakBefore(flowables) self.handle_keepWithNext(flowables) f = flowables[0] del flowables[0] if f is None: return
| 5,600
|
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.''' #allow document a chance to look at, modify or ignore #the object(s) about to be processed self.filterFlowables(flowables) self.handle_breakBefore(flowables) self.handle_keepWithNext(flowables) f = flowables[0] del flowables[0] if f is None: return
|
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.''' #allow document a chance to look at, modify or ignore #the object(s) about to be processed self.filterFlowables(flowables) self.handle_breakBefore(flowables) self.handle_keepWithNext(flowables) f = flowables[0] del flowables[0] if f is None: return
| 5,601
|
def _allSatisfied0(self): """Called by multi-build - are all cross-references resolved?""" allHappy = 1 for f in self._indexingFlowables: if not f.isSatisfied(): allHappy = 0 break return allHappy
|
def _allSatisfied0(self): """Called by multi-build - are all cross-references resolved?""" allHappy = 1 for f in self._indexingFlowables: if not f.isSatisfied(): allHappy = 0 break return allHappy
| 5,602
|
def notify0(self, kind, stuff): """"Forward to any listeners""" for l in self._indexingFlowables: l.notify(kind, stuff)
|
def notify0(self, kind, stuff): """"Forward to any listeners""" for l in self._indexingFlowables: l.notify(kind, stuff)
| 5,603
|
def pageRef0(self, label): """hook to register a page number""" if _verbose: print "pageRef called with label '%s' on page %d" % ( label, self.page) self._pageRefs[label] = self.page
|
def pageRef0(self, label): """hook to register a page number""" if _verbose: print "pageRef called with label '%s' on page %d" % ( label, self.page) self._pageRefs[label] = self.page
| 5,604
|
def multiBuild0(self, story, filename=None, canvasmaker=canvas.Canvas, maxPasses = 10): """Makes multiple passes until all indexing flowables are happy.""" self._indexingFlowables = [] #scan the story and keep a copy for thing in story: if thing.isIndexing(): self._indexingFlowables.append(thing) #print 'scanned story, found these indexing flowables:\n' #print self._indexingFlowables
|
def multiBuild0(self, story, filename=None, canvasmaker=canvas.Canvas, maxPasses = 10): """Makes multiple passes until all indexing flowables are happy.""" self._indexingFlowables = [] #scan the story and keep a copy for thing in story: if thing.isIndexing(): self._indexingFlowables.append(thing) #print 'scanned story, found these indexing flowables:\n' #print self._indexingFlowables
| 5,605
|
def filterFlowables(self,flowables): '''called to filter flowables at the start of the main handle_flowable method. Upon return if flowables[0] has been set to None it is discarded and the main method returns. ''' pass
|
def filterFlowables(self,flowables): '''called to filter flowables at the start of the main handle_flowable method. Upon return if flowables[0] has been set to None it is discarded and the main method returns. ''' pass
| 5,606
|
def afterFlowable(self, flowable): '''called after a flowable has been rendered''' pass
|
def afterFlowable(self, flowable): '''called after a flowable has been rendered''' pass
| 5,607
|
def afterFlowable(self, flowable): '''called after a flowable has been rendered''' pass
|
def afterFlowable(self, flowable): '''called after a flowable has been rendered''' pass
| 5,608
|
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing): """build the document using the flowables. Annotate the first page using the onFirstPage function and later pages using the onLaterPages function. The onXXX pages should follow the signature def myOnFirstPage(canvas, document): # do annotations and modify the document ... The functions can do things like draw logos, page numbers, footers, etcetera. They can use external variables to vary the look (for example providing page numbering or section names). """ self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize), PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)]) if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): self.pageTemplates[1].beforeDrawPage = self.onLaterPages BaseDocTemplate.build(self,flowables)
|
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing): """build the document using the flowables. Annotate the first page using the onFirstPage function and later pages using the onLaterPages function. The onXXX pages should follow the signature def myOnFirstPage(canvas, document): # do annotations and modify the document ... The functions can do things like draw logos, page numbers, footers, etcetera. They can use external variables to vary the look (for example providing page numbering or section names). """ self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize), PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)]) if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): self.pageTemplates[1].beforeDrawPage = self.onLaterPages BaseDocTemplate.build(self,flowables)
| 5,609
|
def myOnFirstPage(canvas, document): # do annotations and modify the document ...
|
def myOnFirstPage(canvas, document): # do annotations and modify the document ...
| 5,610
|
def ID(self): "A unique fingerprint for the file (unless in invariant mode)" if self._ID: return self._ID if self.invariant: s = PDFString('constantconstant') self._ID = PDFArray([s,s]) else: digest = self.signature.digest() doc = DummyDoc() ID = PDFString(digest) IDs = ID.format(doc) self._ID = "%s %% ReportLab generated PDF document -- digest (http://www.reportlab.com) %s [%s %s] %s" % ( LINEEND, LINEEND, IDs, IDs, LINEEND) return self._ID
|
def ID(self): "A unique fingerprint for the file (unless in invariant mode)" if self._ID: return self._ID digest = self.signature.digest() doc = DummyDoc() ID = PDFString(digest) IDs = ID.format(doc) self._ID = "%s %% ReportLab generated PDF document -- digest (http://www.reportlab.com) %s [%s %s] %s" % ( LINEEND, LINEEND, IDs, IDs, LINEEND) return self._ID
| 5,611
|
def _checkTransparency(self,PILImage): if self.mask=='auto': if PILImage.info.has_key("transparency") : transparency = PILImage.info["transparency"] * 3 (tred, tgreen, tblue) = map(ord, PILImage.palette.data[transparency:transparency+3]) self.mask = (tred, tred, tgreen, tgreen, tblue, tblue) else: self.mask = None elif hasattr(self.mask,'rgb'): self.mask = self.mask.rgb()+self.mask.rgb()
|
def _checkTransparency(self,PILImage): if self.mask=='auto': if PILImage.info.has_key("transparency") : transparency = PILImage.info["transparency"] * 3 palette = PILImage.palette try: palette = palette.palette except: palette = palette.data (tred, tgreen, tblue) = map(ord, palette[transparency:transparency+3]) self.mask = (tred, tred, tgreen, tgreen, tblue, tblue) else: self.mask = None elif hasattr(self.mask,'rgb'): self.mask = self.mask.rgb()+self.mask.rgb()
| 5,612
|
def package_home(globals_dict): __name__=globals_dict['__name__'] m=sys.modules[__name__] r=os.path.split(m.__path__[0])[0] return r
|
defpackage_home(globals_dict):__name__=globals_dict['__name__']m=sys.modules[__name__]r=os.path.split(m.__path__[0])[0]returnr
| 5,613
|
def run(): LIBS = [] setup( name="Reportlab", version="1.17", licence="BSD license (see license.txt for details), Copyright (c) 2000-2003, ReportLab Inc.", description="The Reportlab Toolkit", long_description="""The ReportLab Toolkit.
|
def run(): LIBS = [] setup( name="Reportlab", version=get_version(), licence="BSD license (see license.txt for details), Copyright (c) 2000-2003, ReportLab Inc.", description="The Reportlab Toolkit", long_description="""The ReportLab Toolkit.
| 5,614
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,615
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,616
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,617
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,618
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,619
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,620
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,621
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
|
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
| 5,622
|
def cacheImageFile(filename, returnInMemory=0): "Processes image as if for encoding, saves to a file with .a85 extension." from reportlab.lib.utils import PIL_Image import zlib img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgheight = img.size code = [] code.append('BI') # begin image # this describes what is in the image itself code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') #use a flate filter and Ascii Base 85 raw = img.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this isn't #write in blocks of 60 characters per line outstream = cStringIO.StringIO(encoded) dataline = outstream.read(60) while dataline <> "": code.append(dataline) dataline = outstream.read(60) code.append('EI') if returnInMemory: return code #save it to a file cachedname = os.path.splitext(filename)[0] + '.a85' f = open(cachedname,'wb') f.write(join(code, LINEEND)+LINEEND) f.close() if rl_config._verbose: print 'cached image as %s' % cachedname
|
def cacheImageFile(filename, returnInMemory=0): "Processes image as if for encoding, saves to a file with .a85 extension." from reportlab.lib.utils import PIL_Image import zlib img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgheight = img.size code = [] code.append('BI') # begin image # this describes what is in the image itself code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') #use a flate filter and Ascii Base 85 raw = img.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this isn't #write in blocks of 60 characters per line outstream = cStringIO.StringIO(encoded) dataline = outstream.read(60) while dataline <> "": code.append(dataline) dataline = outstream.read(60) code.append('EI') if returnInMemory: return code #save it to a file cachedname = os.path.splitext(filename)[0] + '.a85' f = open(cachedname,'wb') f.write(join(code, LINEEND)+LINEEND) f.close() if rl_config._verbose: print 'cached image as %s' % cachedname
| 5,623
|
def cacheImageFile(filename, returnInMemory=0): "Processes image as if for encoding, saves to a file with .a85 extension." from reportlab.lib.utils import PIL_Image import zlib img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgheight = img.size code = [] code.append('BI') # begin image # this describes what is in the image itself code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') #use a flate filter and Ascii Base 85 raw = img.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this isn't #write in blocks of 60 characters per line outstream = cStringIO.StringIO(encoded) dataline = outstream.read(60) while dataline <> "": code.append(dataline) dataline = outstream.read(60) code.append('EI') if returnInMemory: return code #save it to a file cachedname = os.path.splitext(filename)[0] + '.a85' f = open(cachedname,'wb') f.write(join(code, LINEEND)+LINEEND) f.close() if rl_config._verbose: print 'cached image as %s' % cachedname
|
def cacheImageFile(filename, returnInMemory=0): "Processes image as if for encoding, saves to a file with .a85 extension." from reportlab.lib.utils import PIL_Image import zlib img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgheight = img.size code = [] code.append('BI') # begin image # this describes what is in the image itself code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') #use a flate filter and Ascii Base 85 raw = img.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this isn't #write in blocks of 60 characters per line outstream = cStringIO.StringIO(encoded) dataline = outstream.read(60) while dataline <> "": code.append(dataline) dataline = outstream.read(60) code.append('EI') if returnInMemory: return code #save it to a file cachedname = os.path.splitext(filename)[0] + '.a85' f = open(cachedname,'wb') f.write(join(code, LINEEND)+LINEEND) f.close() if rl_config._verbose: print 'cached image as %s' % cachedname
| 5,624
|
def getPlainText(self,identify=None): """Convenience function for templates which want access to the raw text, without XML tags. """ frags = getattr(self,'frags',None) if frags: plains = [] for frag in frags: plains.append(frag.text) return join(plains, '') elif identify: text = getattr(self,'text',None) if text is None: text = repr(self) return text else: return ''
|
def getPlainText(self,identify=None): """Convenience function for templates which want access to the raw text, without XML tags. """ frags = getattr(self,'frags',None) if frags: plains = [] for frag in frags: if hasattr(frag, 'text'): plains.append(frag.text) return join(plains, '') elif identify: text = getattr(self,'text',None) if text is None: text = repr(self) return text else: return ''
| 5,625
|
def test1(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." import reportlab rlDir = os.path.dirname(reportlab.__file__) ppDir = os.path.join(rlDir, 'tools', 'pythonpoint') pdf = os.path.join(ppDir,'demos','pythonpoint.pdf') xml = os.path.join(ppDir,'demos','pythonpoint.xml') pp = os.path.join(ppDir,'pythonpoint.py') exe = os.path.abspath(os.path.join(rlDir,'..','pythonpoint.exe'))
|
def test1(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." import reportlab rlDir = os.path.dirname(reportlab.__file__) ppDir = os.path.join(rlDir, 'tools', 'pythonpoint') pdf = os.path.join(ppDir,'demos','pythonpoint.pdf') xml = os.path.join(ppDir,'demos','pythonpoint.xml') pp = os.path.join(ppDir,'pythonpoint.py') exe = os.path.abspath(os.path.join(rlDir,'..','pythonpoint.exe'))
| 5,626
|
def test1(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." import reportlab rlDir = os.path.dirname(reportlab.__file__) ppDir = os.path.join(rlDir, 'tools', 'pythonpoint') pdf = os.path.join(ppDir,'demos','pythonpoint.pdf') xml = os.path.join(ppDir,'demos','pythonpoint.xml') pp = os.path.join(ppDir,'pythonpoint.py') exe = os.path.abspath(os.path.join(rlDir,'..','pythonpoint.exe'))
|
def test1(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." import reportlab rlDir = os.path.dirname(reportlab.__file__) ppDir = os.path.join(rlDir, 'tools', 'pythonpoint') pdf = os.path.join(ppDir,'demos','pythonpoint.pdf') xml = os.path.join(ppDir,'demos','pythonpoint.xml') pp = os.path.join(ppDir,'pythonpoint.py') exe = os.path.abspath(os.path.join(rlDir,'..','pythonpoint.exe'))
| 5,627
|
def format(self, num): intPart, fracPart = divmod(num, 1.0) strInt = str(long(intPart)) if self.thousandSeparator is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.thousandSeparator + right + strNew strNew = right + strNew else: strNew = self.thousandSeparator + right + strNew strInt = left strInt = strNew pattern = '%0.' + str(self.decimalPlaces) + 'f' strFrac = (pattern % fracPart)[2:] strBody = strInt + self.decimalSeparator + strFrac if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody
|
def format(self, num): absNum = abs(num) if absNum == num: sign = 1 else: sign = -1 intPart, fracPart = divmod(absNum, 1.0) strInt = str(long(intPart)) if self.thousandSeparator is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.thousandSeparator + right + strNew strNew = right + strNew else: strNew = self.thousandSeparator + right + strNew strInt = left strInt = strNew pattern = '%0.' + str(self.decimalPlaces) + 'f' strFrac = (pattern % fracPart)[2:] strBody = strInt + self.decimalSeparator + strFrac if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody
| 5,628
|
def configure(self, multiSeries): self._catCount = len(multiSeries[0]) self._barWidth = self._length / self._catCount
|
def configure(self, multiSeries): self._catCount = len(multiSeries[0]) self._barWidth = self._length / self._catCount
| 5,629
|
def __init__(self,stream): self.stream = stream if _isJPython: import java.lang.System self.linesep = java.lang.System.getProperty("line.separator") else: self.linesep = os.linesep
|
def __init__(self,stream): self.stream = stream if _isJPython: import java.lang.System self.linesep = java.lang.System.getProperty("line.separator") else: self.linesep = os.linesep
| 5,630
|
def copy(self): """Returns a deep copy""" obj = self.Drawing(self.width, self.height) obj._attrMap = self._attrMap.clone()
|
def _copy(self,obj): """copies to obj""" obj._attrMap = self._attrMap.clone()
| 5,631
|
def getImageFromZODB(self, name) : """Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high. """ try : # try to get it from ZODB logo = getattr(self.parent.context, name) except AttributeError : # not found ! return None
|
def getImageFromZODB(self, name) : """Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high. """ try : # try to get it from ZODB logo = getattr(self.parent.context, name) except AttributeError : # not found ! return None
| 5,632
|
def drawToString(d,fmt='GIF', dpi=72, bg=0xfffffff, configPIL=None, showBoundary=rl_config.showBoundary): s = getStringIO() drawToFile(d,s,fmt=fmt, dpi=dpi, bg=bg, configPIL=configPIL) return s.getvalue()
|
def drawToString(d,fmt='GIF', dpi=72, bg=0xfffffff, configPIL=None, showBoundary=rl_config.showBoundary): s = getStringIO() drawToFile(d,s,fmt=fmt, dpi=dpi, bg=bg, configPIL=configPIL) return s.getvalue()
| 5,633
|
def ext(x): if x=='tiff': x='tif' return x
|
def ext(x): if x=='tiff': x='tif' return x
| 5,634
|
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]
|
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,635
|
def parseAFMFile(afmFileName): """Quick and dirty - gives back a top-level dictionary with top-level items, and a 'widths' key containing a dictionary of glyph names and widths. Just enough needed for embedding. A better parser would accept options for what data you wwanted, and preserve the order.""" lines = open_and_readlines(afmFileName, 'r') if len(lines)<=1: #likely to be a MAC file lines = string.split(lines,'\r') if len(lines)<=1: raise ValueError, 'AFM file %s hasn\'t enough data' % afmFileName topLevel = {} glyphLevel = [] lines = map(string.strip, lines) #pass 1 - get the widths inMetrics = 0 # os 'TOP', or 'CHARMETRICS' for line in lines: if line[0:16] == 'StartCharMetrics': inMetrics = 1 elif line[0:14] == 'EndCharMetrics': inMetrics = 0 elif inMetrics: chunks = string.split(line, ';') chunks = map(string.strip, chunks) cidChunk, widthChunk, nameChunk = chunks[0:3] # character ID l, r = string.split(cidChunk) assert l == 'C', 'bad line in font file %s' % line cid = string.atoi(r) # width l, r = string.split(widthChunk) assert l == 'WX', 'bad line in font file %s' % line width = string.atoi(r) # name l, r = string.split(nameChunk) assert l == 'N', 'bad line in font file %s' % line name = r glyphLevel.append((cid, width, name)) # pass 2 font info inHeader = 0 for line in lines: if line[0:16] == 'StartFontMetrics': inHeader = 1 if line[0:16] == 'StartCharMetrics': inHeader = 0 elif inHeader: if line[0:7] == 'Comment': pass try: left, right = string.split(line,' ',1) except: raise ValueError, "Header information error in afm %s: line='%s'" % (afmFileName, line) try: right = string.atoi(right) except: pass topLevel[left] = right return (topLevel, glyphLevel)
|
def parseAFMFile(afmFileName): """Quick and dirty - gives back a top-level dictionary with top-level items, and a 'widths' key containing a dictionary of glyph names and widths. Just enough needed for embedding. A better parser would accept options for what data you wwanted, and preserve the order.""" lines = open_and_readlines(afmFileName, 'r') if len(lines)<=1: #likely to be a MAC file if lines: lines = string.split(lines[0],'\r') if len(lines)<=1: raise ValueError, 'AFM file %s hasn\'t enough data' % afmFileName topLevel = {} glyphLevel = [] lines = map(string.strip, lines) #pass 1 - get the widths inMetrics = 0 # os 'TOP', or 'CHARMETRICS' for line in lines: if line[0:16] == 'StartCharMetrics': inMetrics = 1 elif line[0:14] == 'EndCharMetrics': inMetrics = 0 elif inMetrics: chunks = string.split(line, ';') chunks = map(string.strip, chunks) cidChunk, widthChunk, nameChunk = chunks[0:3] # character ID l, r = string.split(cidChunk) assert l == 'C', 'bad line in font file %s' % line cid = string.atoi(r) # width l, r = string.split(widthChunk) assert l == 'WX', 'bad line in font file %s' % line width = string.atoi(r) # name l, r = string.split(nameChunk) assert l == 'N', 'bad line in font file %s' % line name = r glyphLevel.append((cid, width, name)) # pass 2 font info inHeader = 0 for line in lines: if line[0:16] == 'StartFontMetrics': inHeader = 1 if line[0:16] == 'StartCharMetrics': inHeader = 0 elif inHeader: if line[0:7] == 'Comment': pass try: left, right = string.split(line,' ',1) except: raise ValueError, "Header information error in afm %s: line='%s'" % (afmFileName, line) try: right = string.atoi(right) except: pass topLevel[left] = right return (topLevel, glyphLevel)
| 5,636
|
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 os.path.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 = 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,637
|
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 os.path.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 T1SearchPathfor dirname in T1SearchPath: if not os.path.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,638
|
def hex32(i): return '0X%8.8X' % (long(i)&0xFFFFFFFFL)
|
def hex32(i): return '0X%8.8X' % (long(i)&0xFFFFFFFFL)
| 5,639
|
def add32(x, y): "Calculate (x + y) modulo 2**32" return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL
|
def add32(x, y): "Calculate (x + y) modulo 2**32" return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL
| 5,640
|
def calcChecksum(data): """Calculates TTF-style checksums""" if len(data)&3: data = data + (4-(len(data)&3))*"\0" sum = 0 for n in unpack(">%dl" % (len(data)>>2), data): sum = add32(sum,n) return sum
|
def calcChecksum(data): """Calculates TTF-style checksums""" if len(data)&3: data = data + (4-(len(data)&3))*"\0" sum = 0 for n in unpack(">%dl" % (len(data)>>2), data): sum = add32(sum,n) return sum
| 5,641
|
def test(self,x): return callable(x) or isinstance(x,Marker) or isinstance(x,Flag) \ or (type(uSymbol)==ClassType and issubclass(uSymbol,Widget))
|
def test(self,x): return callable(x) or isinstance(x,Marker) or isinstance(x,Flag) \ or (type(uSymbol)==ClassType and issubclass(uSymbol,Widget))
| 5,642
|
def asDrawing(self, width, height): """Convenience function to make a drawing from a group""" self.__class__ = Drawing self._attrMap.update(self._xtraAttrMap) self.width = width self.height = height
|
def asDrawing(self, width, height): """Convenience function to make a drawing from a group""" self.__class__ = Drawing self._attrMap.update(self._xtraAttrMap) self.width = width self.height = height
| 5,643
|
def read_tag(self): "Read a 4-character tag" self._pos = self._pos + 4 return self._ttf_data[self._pos - 4:self._pos]
|
def read_tag(self): "Read a 4-character tag" self._pos += 4 return self._ttf_data[self._pos - 4:self._pos]
| 5,644
|
def read_ushort(self): "Reads an unsigned short" self._pos = self._pos + 2 return (ord(self._ttf_data[self._pos - 2]) << 8) + \ (ord(self._ttf_data[self._pos - 1]))
|
def read_ushort(self): "Reads an unsigned short" self._pos = self._pos + 2 return (ord(self._ttf_data[self._pos - 2]) << 8) + \ (ord(self._ttf_data[self._pos - 1]))
| 5,645
|
def read_ulong(self): "Reads an unsigned long" self._pos = self._pos + 4 return unpack('>l',self._ttf_data[self._pos - 4:self._pos])[0]
|
def read_ulong(self): "Reads an unsigned long" self._pos += 4 return unpack('>l',self._ttf_data[self._pos - 4:self._pos])[0]
| 5,646
|
def read_short(self): "Reads a signed short" us = self.read_ushort() if us >= 0x8000: return us - 0x10000 else: return us
|
def read_short(self): "Reads a signed short" us = self.read_ushort() if us >= 0x8000: return us - 0x10000 else: return us
| 5,647
|
def get_ushort(self, pos): "Return an unsigned short at given position" return (ord(self._ttf_data[pos]) << 8) + \ (ord(self._ttf_data[pos + 1]))
|
def get_ushort(self, pos): "Return an unsigned short at given position" return (ord(self._ttf_data[pos]) << 8) + \ (ord(self._ttf_data[pos + 1]))
| 5,648
|
def get_table(self, tag): "Return the given TTF table" pos, length = self.get_table_pos(tag) return self._ttf_data[pos:pos+length]
|
defget_table(self,tag):"ReturnthegivenTTFtable"pos,length=self.get_table_pos(tag)returnself._ttf_data[pos:pos+length]
| 5,649
|
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
|
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
| 5,650
|
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
|
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
| 5,651
|
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
|
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
| 5,652
|
def addTick(i, xVals=xVals, formatter=formatter, ticks=ticks, labels=labels): ticks.insert(0,xVals[i]) labels.insert(0,formatter(xVals[i]))
|
def addTick(i, xVals=xVals, formatter=formatter, ticks=ticks, labels=labels): ticks.insert(0,xVals[i]) labels.insert(0,formatter(xVals[i]))
| 5,653
|
def configure(self, data): self._convertXV(data) xVals = map(lambda dv: dv[0], data[0]) if self.dailyFreq: xEOM = [] pm = 0 px = xVals[0] for x in xVals: m = x.month() if pm!=m: if pm: xEOM.append(px) pm = m px = x px = xVals[-1] if xEOM[-1]!=x: xEOM.append(px) steps, labels = self._xAxisTicker(xEOM) else: steps, labels = self._xAxisTicker(xVals) valueMin, valueMax = self.valueMin, self.valueMax if valueMin is None: valueMin = xVals[0] if valueMax is None: valueMax = xVals[-1] self._valueMin, self._valueMax = valueMin, valueMax self.valueSteps = steps self.labelTextFormat = labels
|
def configure(self, data): self._convertXV(data) xVals = map(lambda dv: dv[0], data[0]) if self.dailyFreq: xEOM = [] pm = 0 px = xVals[0] for x in xVals: m = x.month() if pm!=m: if pm: xEOM.append(px) pm = m px = x px = xVals[-1] if xEOM[-1]!=x: xEOM.append(px) steps, labels = self._xAxisTicker(xEOM) else: steps, labels = self._xAxisTicker(xVals) valueMin, valueMax = self.valueMin, self.valueMax if valueMin is None: valueMin = xVals[0] if valueMax is None: valueMax = xVals[-1] self._valueMin, self._valueMax = valueMin, valueMax self._tickValues = steps self.labelTextFormat = labels
| 5,654
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
| 5,655
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
| 5,656
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
| 5,657
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
|
def _rangeAdjust(self): "Adjusts the value range of the axis."
| 5,658
|
def test1(self):
|
def test1(self):
| 5,659
|
def test1(self):
|
def test1(self):
| 5,660
|
def test1(self):
|
def test1(self):
| 5,661
|
def test1(self):
|
def test1(self):
| 5,662
|
def test1(self):
|
def test1(self):
| 5,663
|
def test1(self):
|
def test1(self):
| 5,664
|
def test1(self):
|
def test1(self):
| 5,665
|
def test1(self):
|
def test1(self):
| 5,666
|
def test1(self):
|
def test1(self):
| 5,667
|
def __init__(self): self.strokeWidth = 0 self.fillColor = None self.strokeColor = STATE_DEFAULTS["strokeColor"] self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"]
|
def __init__(self): self.strokeWidth = 0 self.fillColor = None self.strokeColor = STATE_DEFAULTS["strokeColor"] self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"]
| 5,668
|
def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] self.labels = None # or list of strings self.startAngle = 90 self.direction = "clockwise"
|
def __init__(self): PlotArea.__init__(self) self.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] self.labels = None # or list of strings self.startAngle = 90 self.direction = "clockwise"
| 5,669
|
def normalizeData(self, outer = 0.0): """Turns data into normalized ones where each datum is < 1.0, and 1.0 = maximum radius. Adds 10% at outside edge by default""" data = self.data theMax = 0.0 for row in data: for element in row: assert element >=0, "Cannot do spider plots of negative numbers!" if element > theMax: theMax = element theMax = theMax * (1.0+outer)
|
def normalizeData(self, outer = 0.0): """Turns data into normalized ones where each datum is < 1.0, and 1.0 = maximum radius. Adds 10% at outside edge by default""" data = self.data theMax = 0.0 for row in data: for element in row: assert element >=0, "Cannot do spider plots of negative numbers!" if element > theMax: theMax = element theMax = theMax * (1.0+outer)
| 5,670
|
def polarToRect(self, r, theta): "Convert to rectangular based on current size" return (self._centerx + r * sin(theta),self._centery + r * cos(theta))
|
def polarToRect(self, r, theta): "Convert to rectangular based on current size" return (self._centerx + r * sin(theta),self._centery + r * cos(theta))
| 5,671
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,672
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,673
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,674
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,675
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,676
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,677
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,678
|
def draw(self): # normalize slice data g = Group()
|
def draw(self): # normalize slice data g = Group()
| 5,679
|
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
|
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,15],[7,8,17,4,12,8,3]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
| 5,680
|
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
|
defpc.strands[2].fillColor=colors.palegreen sample1():pc.strands[2].fillColor=colors.palegreen "Makepc.strands[2].fillColor=colors.palegreen apc.strands[2].fillColor=colors.palegreen simplepc.strands[2].fillColor=colors.palegreen spiderpc.strands[2].fillColor=colors.palegreen chart"pc.strands[2].fillColor=colors.palegreen pc.strands[2].fillColor=colors.palegreen dpc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen Drawing(400,pc.strands[2].fillColor=colors.palegreen 400)pc.strands[2].fillColor=colors.palegreen pc.strands[2].fillColor=colors.palegreen pcpc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen SpiderChart()pc.strands[2].fillColor=colors.palegreen pc.xpc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen 50pc.strands[2].fillColor=colors.palegreen pc.ypc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen 50pc.strands[2].fillColor=colors.palegreen pc.widthpc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen 300pc.strands[2].fillColor=colors.palegreen pc.heightpc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen 300pc.strands[2].fillColor=colors.palegreen pc.datapc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen [[10,12,14,16,14,12],pc.strands[2].fillColor=colors.palegreen [6,8,10,12,9,11]]pc.strands[2].fillColor=colors.palegreen pc.labelspc.strands[2].fillColor=colors.palegreen =pc.strands[2].fillColor=colors.palegreen ['a','b','c','d','e','f']pc.strands[2].fillColor=colors.palegreen pc.strands[2].fillColor=colors.palegreen d.add(pc)pc.strands[2].fillColor=colors.palegreen pc.strands[2].fillColor=colors.palegreen returnpc.strands[2].fillColor=colors.palegreen dpc.strands[2].fillColor=colors.palegreen pc.strands[2].fillColor=colors.palegreen
| 5,681
|
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
|
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
| 5,682
|
def run(verbose=1, outDir=None): import os, sys, shutil from reportlab.tools.docco import yaml2pdf from reportlab.lib.utils import _RL_DIR yaml2pdf.run('reference.yml','reference.pdf') if verbose: print 'Saved reference.pdf' docdir = os.path.join(_RL_DIR,'docs') if outDir: docDir = outDir destfn = docdir + os.sep + 'reference.pdf' shutil.copyfile('reference.pdf', destfn) if verbose: print 'copied to %s' % destfn
|
def run(verbose=None, outDir=None): import os, sys, shutil from reportlab.tools.docco import yaml2pdf from reportlab.lib.utils import _RL_DIR yaml2pdf.run('reference.yml','reference.pdf') if verbose: print 'Saved reference.pdf' docdir = os.path.join(_RL_DIR,'docs') if outDir: docDir = outDir destfn = docdir + os.sep + 'reference.pdf' shutil.copyfile('reference.pdf', destfn) if verbose: print 'copied to %s' % destfn
| 5,683
|
def makeSuite(): "standard test harness support - run self as separate process" from reportlab.test.utils import ScriptThatMakesFileTest return ScriptThatMakesFileTest('../docs/reference', 'genreference.py', 'reference.pdf')
|
def makeSuite(): "standard test harness support - run self as separate process" from reportlab.test.utils import ScriptThatMakesFileTest return ScriptThatMakesFileTest('../docs/reference', 'genreference.py', 'reference.pdf')
| 5,684
|
def handle_data(self,data): "Creates an intermediate representation of string segments."
|
def handle_data(self,data): "Creates an intermediate representation of string segments."
| 5,685
|
def handle_data(self,data): "Creates an intermediate representation of string segments."
|
def handle_data(self,data): "Creates an intermediate representation of string segments."
| 5,686
|
def parse(self, text, style): """Given a formatted string will return a list of ParaFrag objects with their calculated widths. If errors occur None will be returned and the self.errors holds a list of the error messages. """
|
def parse(self, text, style): """Given a formatted string will return a list of ParaFrag objects with their calculated widths. If errors occur None will be returned and the self.errors holds a list of the error messages. """
| 5,687
|
def parse(self, text, style): """Given a formatted string will return a list of ParaFrag objects with their calculated widths. If errors occur None will be returned and the self.errors holds a list of the error messages. """
|
def parse(self, text, style): """Given a formatted string will return a list of ParaFrag objects with their calculated widths. If errors occur None will be returned and the self.errors holds a list of the error messages. """
| 5,688
|
def wrap(self, availableWidth, availableHeight): if debug: print "WRAPPING", id(self), availableWidth, availableHeight print " ", self.formattedProgram print " ", self.program self.availableHeight = availableHeight self.myengine = p = paragraphEngine() p.baseindent = self.baseindent # for shifting bullets as needed parsedText = self.parsedText formattedProgram = self.formattedProgram state = self.state if state: leading = state["leading"] else: leading = self.style1.leading program = self.program self.cansplit = 1 # until proven otherwise if state: p.resetState(state) p.x = 0 p.y = 0 needatleast = state["leading"] else: needatleast = self.style1.leading if availableHeight<=needatleast: self.cansplit = 0 #if debug: # print "CANNOT COMPILE, NEED AT LEAST", needatleast, 'AVAILABLE', availableHeight return (availableHeight+1, availableWidth) # cannot split if parsedText is None and program is None: raise ValueError, "need parsedText for formatting" if not program: self.program = program = self.compileProgram(parsedText) if not self.formattedProgram: (formattedProgram, remainder, \ laststate, heightused) = p.format(availableWidth, availableHeight, program, leading) self.formattedProgram = formattedProgram self.height = heightused self.laststate = laststate self.remainderProgram = remainder else: heightused = self.height remainder = None # too big if there is a remainder if remainder: # lie about the height: it must be split anyway #if debug: # print "I need to split", self.formattedProgram # print "heightused", heightused, "available", availableHeight, "remainder", len(remainder) height = availableHeight + 1 #print "laststate is", laststate #print "saving remainder", remainder self.remainder = Para(self.style1, parsedText=None, bulletText=None, \ state=laststate, context=self.context) self.remainder.program = remainder self.remainder.spaceAfter = self.spaceAfter self.spaceAfter = 0 else: self.remainder = None # no extra height = heightused if height>availableHeight: height = availableHeight-0.1 #if debug: # print "giving height", height, "of", availableHeight, self.parsedText result = (availableWidth, height) if debug: (w, h) = result if abs(availableHeight-h)<0.2: print "exact match???" + repr(availableHeight, h) print "wrap is", (availableWidth, availableHeight), result return result
|
def wrap(self, availableWidth, availableHeight): if debug: print "WRAPPING", id(self), availableWidth, availableHeight print " ", self.formattedProgram print " ", self.program self.availableHeight = availableHeight self.myengine = p = paragraphEngine() p.baseindent = self.baseindent # for shifting bullets as needed parsedText = self.parsedText formattedProgram = self.formattedProgram state = self.state if state: leading = state["leading"] else: leading = self.style1.leading program = self.program self.cansplit = 1 # until proven otherwise if state: p.resetState(state) p.x = 0 p.y = 0 needatleast = state["leading"] else: needatleast = self.style1.leading if availableHeight < needatleast: self.cansplit = 0 #if debug: # print "CANNOT COMPILE, NEED AT LEAST", needatleast, 'AVAILABLE', availableHeight return (availableHeight+1, availableWidth) # cannot split if parsedText is None and program is None: raise ValueError, "need parsedText for formatting" if not program: self.program = program = self.compileProgram(parsedText) if not self.formattedProgram: (formattedProgram, remainder, \ laststate, heightused) = p.format(availableWidth, availableHeight, program, leading) self.formattedProgram = formattedProgram self.height = heightused self.laststate = laststate self.remainderProgram = remainder else: heightused = self.height remainder = None # too big if there is a remainder if remainder: # lie about the height: it must be split anyway #if debug: # print "I need to split", self.formattedProgram # print "heightused", heightused, "available", availableHeight, "remainder", len(remainder) height = availableHeight + 1 #print "laststate is", laststate #print "saving remainder", remainder self.remainder = Para(self.style1, parsedText=None, bulletText=None, \ state=laststate, context=self.context) self.remainder.program = remainder self.remainder.spaceAfter = self.spaceAfter self.spaceAfter = 0 else: self.remainder = None # no extra height = heightused if height>availableHeight: height = availableHeight-0.1 #if debug: # print "giving height", height, "of", availableHeight, self.parsedText result = (availableWidth, height) if debug: (w, h) = result if abs(availableHeight-h)<0.2: print "exact match???" + repr(availableHeight, h) print "wrap is", (availableWidth, availableHeight), result return result
| 5,689
|
def getClassDoc(self, modulename, classname, pathname=None): """Documents the class and its public methods""" docco = codegrab.getObjectsDefinedIn(modulename, pathname) found = 0 for cls in docco.classes: if cls.name == classname: found = 1 self._results.append(('Preformatted','FunctionHeader', 'Class %s:' % cls.name)) self._results.append(('Preformatted','DocString', cls.doc)) for mth in cls.methods: if mth.status == 'official': self._results.append(('Preformatted','FunctionHeader', mth.proto)) self._results.append(('Preformatted','DocStringIndent', mth.doc)) break assert found, 'No Classes Defined in ' + modulename
|
def getClassDoc(self, modulename, classname, pathname=None): """Documents the class and its public methods""" docco = codegrab.getObjectsDefinedIn(modulename, pathname) found = 0 for cls in docco.classes: if cls.name == classname: found = 1 self._results.append(('Preformatted','FunctionHeader', 'Class %s:' % cls.name)) self._results.append(('Preformatted','DocString', cls.doc)) for mth in cls.methods: if mth.status == 'official': self._results.append(('Preformatted','FunctionHeader', mth.proto)) self._results.append(('Preformatted','DocStringIndent', mth.doc)) break assert found, 'No Classes Defined in ' + modulename
| 5,690
|
def setDash(self, array=[], phase=0): """Two notations. pass two numbers, or an array and phase""" if type(array) == IntType or type(array) == FloatType: self._code.append('[%s %s] 0 d' % (array, phase)) elif type(array) == ListType or type(array) == TupleType: assert phase >= 0, "phase is a length in user space" textarray = join(map(str, array)) self._code.append('[%s] %s d' % (textarray, phase))
|
def setDash(self, array=[], phase=0): """Two notations. pass two numbers, or an array and phase""" if type(array) == IntType or type(array) == FloatType: self._code.append('[%s] %s d' % (array, phase)) elif type(array) == ListType or type(array) == TupleType: assert phase >= 0, "phase is a length in user space" textarray = join(map(str, array)) self._code.append('[%s] %s d' % (textarray, phase))
| 5,691
|
def setDash(self, array=[], phase=0): """Two notations. pass two numbers, or an array and phase""" if type(array) == IntType or type(array) == FloatType: self._code.append('[%s %s] 0 d' % (array, phase)) elif type(array) == ListType or type(array) == TupleType: assert phase >= 0, "phase is a length in user space" textarray = join(map(str, array)) self._code.append('[%s] %s d' % (textarray, phase))
|
def setDash(self, array=[], phase=0): """Two notations. pass two numbers, or an array and phase""" if type(array) == IntType or type(array) == FloatType: self._code.append('[%s %s] 0 d' % (array, phase)) elif type(array) == ListType or type(array) == TupleType: assert phase >= 0, "phase is a length in user space" textarray = ' '.join(map(str, array)) self._code.append('[%s] %s d' % (textarray, phase))
| 5,692
|
def _findMinMaxValue(V, x, default, func, special=None): if type(V[0][0]) in (TupleType,ListType): if special: f=lambda T,x=x,special=special: special(T,x,func) else: f=lambda T,x=x: T[x] V=map(lambda e,f=f: map(f,e),V) V = filter(len,map(lambda x: filter(lambda x: x is not None,x),V)) if len(V)==0: return default return func(map(func,V))
|
def _findMinMaxValue(V, x, default, func, special=None): if type(V[0][0]) in (TupleType,ListType): if special: f=lambda T,x=x,special=special,func=func: special(T,x,func) else: f=lambda T,x=x: T[x] V=map(lambda e,f=f: map(f,e),V) V = filter(len,map(lambda x: filter(lambda x: x is not None,x),V)) if len(V)==0: return default return func(map(func,V))
| 5,693
|
def getCodes(): """Returns a dict mapping code names to widgets""" from widgets import (BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State) #newer codes will typically get their own module from eanbc import Ean13BarcodeWidget, Ean8BarcodeWidget #the module exports a dictionary of names to widgets, to make it easy for #apps and doc tools to display information about them. codes = {} for widget in ( BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State, Ean13BarcodeWidget, Ean8BarcodeWidget, ): codeName = widget.codeName codes[codeName] = widget return codes
|
def getCodes(): """Returns a dict mapping code names to widgets""" from widgets import BarcodeI2of5, BarcodeCode128, BarcodeStandard93,\ BarcodeExtended93, BarcodeStandard39, BarcodeExtended39,\ BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM,\ BarcodePOSTNET, BarcodeUSPS_4State #newer codes will typically get their own module from eanbc import Ean13BarcodeWidget, Ean8BarcodeWidget #the module exports a dictionary of names to widgets, to make it easy for #apps and doc tools to display information about them. codes = {} for widget in ( BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State, Ean13BarcodeWidget, Ean8BarcodeWidget, ): codeName = widget.codeName codes[codeName] = widget return codes
| 5,694
|
def transform(self, a,b,c,d,e,f): """adjoin a mathematical transform to the current graphics state matrix. Not recommended for beginners.""" #"""How can Python track this?""" #a0,b0,c0,d0,e0,f0 = self._currentMatrix #self._currentMatrix = (a0*a+c0*b, b0*a+d0*b, # a0*c+c0*d, b0*c+d0*d, # a0*e+c0*f+e0, b0*e+d0*f+f0) if self._code[-1][-3:]==' cm': L = string.split(self._code[-1]) a0, b0, c0, d0, e0, f0 = map(float,L[-7:-1]) s = len(L)>7 and string.join(L)+ ' %s cm' or '%s cm' self._code[-1] = s % fp_str(a0*a+c0*b,b0*a+d0*b,a0*c+c0*d,b0*c+d0*d,a0*e+c0*f+e0,b0*e+d0*f+f0) else: self._code.append('%s cm' % fp_str(a,b,c,d,e,f))
|
def transform(self, a,b,c,d,e,f): """adjoin a mathematical transform to the current graphics state matrix. Not recommended for beginners.""" #"""How can Python track this?""" #a0,b0,c0,d0,e0,f0 = self._currentMatrix #self._currentMatrix = (a0*a+c0*b, b0*a+d0*b, # a0*c+c0*d, b0*c+d0*d, # a0*e+c0*f+e0, b0*e+d0*f+f0) if len(self._code) and self._code[-1][-3:]==' cm': L = string.split(self._code[-1]) a0, b0, c0, d0, e0, f0 = map(float,L[-7:-1]) s = len(L)>7 and string.join(L)+ ' %s cm' or '%s cm' self._code[-1] = s % fp_str(a0*a+c0*b,b0*a+d0*b,a0*c+c0*d,b0*c+d0*d,a0*e+c0*f+e0,b0*e+d0*f+f0) else: self._code.append('%s cm' % fp_str(a,b,c,d,e,f))
| 5,695
|
def comment(self,msg): self.code.append('%'+msg)
|
def comment(self,msg): self.code.append('%'+msg)
| 5,696
|
def sample1(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.lines.symbol = makeFilledDiamond lc.lineLabelFormat = '%2.0f' catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
|
def sample1(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.lines.symbol = makeMarker('FilledDiamond') lc.lineLabelFormat = '%2.0f' catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
| 5,697
|
def sample1a(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = SampleHorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.strokeColor = colors.white lc.fillColor = colors.HexColor(0xCCCCCC) lc.lines.symbol = makeFilledDiamond lc.lineLabelFormat = '%2.0f' catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
|
def sample1a(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = SampleHorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.strokeColor = colors.white lc.fillColor = colors.HexColor(0xCCCCCC) lc.lines.symbol = makeMarker('FilledDiamond') lc.lineLabelFormat = '%2.0f' catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
| 5,698
|
def sample2(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.lines.symbol = makeSmiley lc.lines.symbol = Marker() lc.lines.symbol.kind = 'Smiley' lc.lineLabelFormat = '%2.0f' lc.strokeColor = colors.black lc.fillColor = colors.lightblue catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
|
def sample2(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.lines.symbol = makeMarker('Smiley') lc.lineLabelFormat = '%2.0f' lc.strokeColor = colors.black lc.fillColor = colors.lightblue catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
| 5,699
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.