def MillerRabin(n, k=10): if n == 2: return True if not n & 1: return False # noinspection PyShadowingNames def check(a, s, d, n): x = pow(a, d, n) if x == 1: return True for i in xrange(s - 1): if x == n - 1: return True x = pow(x, 2, n) return x == n - 1 s = 0 d = n - 1 while d % 2 == 0: d >>= 1 s += 1 for i in xrange(k): a = randrange(2, n - 1) if not check(a, s, d, n): return False return True
def make_name_access_maps(bk): name_and_scope_map = {} # (name.lower(), scope): Name_object name_map = {} # name.lower() : list of Name_objects (sorted in scope order) num_names = len(bk.name_obj_list) for namex in xrange(num_names): nobj = bk.name_obj_list[namex] name_lcase = nobj.name.lower() key = (name_lcase, nobj.scope) if key in name_and_scope_map: msg = 'Duplicate entry %r in name_and_scope_map' % (key, ) if 0: raise XLRDError(msg) else: if bk.verbosity: print(msg, file=bk.logfile) name_and_scope_map[key] = nobj if name_lcase in name_map: name_map[name_lcase].append((nobj.scope, nobj)) else: name_map[name_lcase] = [(nobj.scope, nobj)] for key in name_map.keys(): alist = name_map[key] alist.sort() name_map[key] = [x[1] for x in alist] bk.name_and_scope_map = name_and_scope_map bk.name_map = name_map
def bezier_arc_from_centre(cx, cy, rx, ry, start_ang=0, extent=90): if abs(extent) <= 90: nfrag = 1 frag_angle = float(extent) else: nfrag = int(ceil(abs(extent) / 90.)) frag_angle = float(extent) / nfrag if abs(frag_angle) < 1e-10: return [] frag_rad = radians(frag_angle) half_rad = frag_rad * 0.5 kappa = abs(4. / 3. * (1. - cos(half_rad)) / sin(half_rad)) if frag_angle < 0: kappa = -kappa point_list = [] theta1 = radians(start_ang) start_rad = theta1 + frag_rad c1 = cos(theta1) s1 = sin(theta1) for i in xrange(nfrag): c0 = c1 s0 = s1 theta1 = start_rad + i * frag_rad c1 = cos(theta1) s1 = sin(theta1) point_list.append( (cx + rx * c0, cy - ry * s0, cx + rx * (c0 - kappa * s0), cy - ry * (s0 + kappa * c0), cx + rx * (c1 + kappa * s1), cy - ry * (s1 - kappa * c1), cx + rx * c1, cy - ry * s1)) return point_list
def _replaceNamedChildren(self, name, nodes, all=0): '''given some tuples use to populate equivalent nodes under here''' if type(nodes) is not type([]): nodes = [nodes] C = self._children if not nodes: i = -1 else: for i in xrange(len(C)): c = C[i] if c[0] == name: C[i] = nodes[0] del nodes[0] if not nodes: break if all: i = i + 1 while i < len(C): if C[i][0] == name: del C[i] else: i = i + 1 list(map(C.append, nodes)) p = self._parent if p: t = p[0][p[1]] n, a, c, o = t t = isinstance(t, tuple) and (n, self._attrs, self._children, o) or [ n, self._attrs, self._children, o ] p[0][p[1]] = t
def generate_verse(self, syllables, rhyme=".*", attempts=10, persistence=10): """ Generate a verse of given syllables and rhyme :param attempts: how many times will we try to rhyme :param syllables: Amount of syllables :param rhyme: regex for last word :param persistence: how many times it will try to find a verse matching both rhyme and syllable :return: string """ n = self._n s = self.grammar.get_start() grammar = self.grammar # as many attempts as we are allowed (attempts as words that rhyme that we will try to put in a sentence with # given amount of syllables for _ in xrange(attempts): # get me any word that rhymes and it will be the last word = self.get_word_that_matches(rhyme) # what's its token? token = self.tokens[word] # estimate the amount of words we will need to match the required syllables w = ceil(syllables / get_mean_syllable(self.model)) # around that much of words we will generate (it's clumsy) # we need to do this to choose how deep into our grammar to look for the token we have, the token can be # anywhere, it's useless to look for it in depth 1 given that the words has less than x syllables #### in case of i=4 we will try sentences of lenght 3, 4, 5 and 6 for i in range(w - 1, w + 2): # we get a list of all the possible productions that get will us to 'word''s token, given it's context # [token] means we are looking for producctions that return only token, and no NonTerminals # grammar.non_terminals_hierarchy[i] comes as "the nonterminal for i depth" possibilities = grammar.get_possible_produced( [token], grammar.non_terminals_hierarchy[i]) if not possibilities: # if it's empty then we have a token that can't be the last one break # any of those productions, we pick it's context alpha, as we ignore beta in this program. [:-1] because # we already have that one sentence_tokens = random.choice(possibilities).alpha[:-1] patience = persistence # let's match token to word, attempting to satisfy the syllables condition. # until we lose our patience as a poet while patience > 0: sentence = ["<s>"] for token in sentence_tokens: sentence.append( self.generate_word(tuple(sentence[i:i + n - 1]), token)) sentence.append(word) # does it comply with the requested sentences? if how_many_syllables_sent(' '.join( sentence[1:])) != syllables: patience -= 1 else: return ' '.join(sentence[1:]) return -1
def check(a, s, d, n): x = pow(a, d, n) if x == 1: return True for i in xrange(s - 1): if x == n - 1: return True x = pow(x, 2, n) return x == n - 1
def __init__(self, *args, **kwargs): n = kwargs.pop('n', int) values = kwargs.pop('values', list) super(DotacionForm, self).__init__(*args, **kwargs) for i in xrange(n): self.fields['cantidad%d' % i] = forms.IntegerField( min_value=0, initial=values[i]) self.fields['cantidad%d' % i].widget.attrs.update( {'class': 'input'})
def test_sqlalchemy_core(n=100000): init_sqlalchemy() t0 = time.time() engine.execute( Customer.__table__.insert(), [{"name": 'NAME ' + str(i)} for i in xrange(n)] ) print( "SQLAlchemy Core: Total time for " + str(n) + " records " + str(time.time() - t0) + " secs")
def test_sqlite3(n=100000, dbname='sqlite3.db'): conn = init_sqlite3(dbname) c = conn.cursor() t0 = time.time() for i in xrange(n): row = ('NAME ' + str(i),) c.execute("INSERT INTO customer (name) VALUES (?)", row) conn.commit() print( "sqlite3: Total time for " + str(n) + " records " + str(time.time() - t0) + " sec")
def testAsciiBase85(self): "Test if the obvious test for whether ASCII-Base85 encoding works." msg = "Round-trip AsciiBase85 encoding failed." plain = 'What is the average velocity of a sparrow?' #the remainder block can be absent or from 1 to 4 bytes for i in xrange(256): encoded = asciiBase85Encode(plain) decoded = asciiBase85Decode(encoded) assert decoded == asBytes(plain, 'latin1'), msg plain += chr(i)
def testAsciiBase85(self): "Test if the obvious test for whether ASCII-Base85 encoding works." msg = "Round-trip AsciiBase85 encoding failed." plain = 'What is the average velocity of a sparrow?' #the remainder block can be absent or from 1 to 4 bytes for i in xrange(256): encoded = asciiBase85Encode(plain) decoded = asciiBase85Decode(encoded) assert decoded == asBytes(plain,'latin1'), msg plain += chr(i)
def test_sqlalchemy_orm_pk_given(n=100000): init_sqlalchemy() t0 = time.time() for i in xrange(n): customer = Customer(id=i + 1, name="NAME " + str(i)) DBSession.add(customer) if i % 1000 == 0: DBSession.flush() DBSession.commit() print( "SQLAlchemy ORM pk given: Total time for " + str(n) + " records " + str(time.time() - t0) + " secs")
def test_sqlalchemy_orm(n=100000): init_sqlalchemy() t0 = time.time() for i in xrange(n): customer = Customer() customer.name = 'NAME ' + str(i) DBSession.add(customer) if i % 1000 == 0: DBSession.flush() DBSession.commit() print( "SQLAlchemy ORM: Total time for " + str(n) + " records " + str(time.time() - t0) + " secs")
def test_sqlalchemy_orm_bulk_save_objects(n=100000): init_sqlalchemy() t0 = time.time() for chunk in range(0, n, 10000): DBSession.bulk_save_objects( [ Customer(name="NAME " + str(i)) for i in xrange(chunk, min(chunk + 10000, n)) ] ) DBSession.commit() print( "SQLAlchemy ORM bulk_save_objects(): Total time for " + str(n) + " records " + str(time.time() - t0) + " secs")
def initialise_colour_map(book): book.colour_map = {} book.colour_indexes_used = {} if not book.formatting_info: return # Add the 8 invariant colours for i in xrange(8): book.colour_map[i] = excel_default_palette_b8[i] # Add the default palette depending on the version dpal = default_palette[book.biff_version] ndpal = len(dpal) for i in xrange(ndpal): book.colour_map[i + 8] = dpal[i] # Add the specials -- None means the RGB value is not known # System window text colour for border lines book.colour_map[ndpal + 8] = None # System window background colour for pattern background book.colour_map[ndpal + 8 + 1] = None # for ci in ( 0x51, # System ToolTip text colour (used in note objects) 0x7FFF, # 32767, system window text colour for fonts ): book.colour_map[ci] = None
def plotConfusionMatrix(confmat): import seaborn seaborn.set_context('poster') #seaborn.set_style("white") seaborn.set_style("ticks") plt.style.use(['seaborn-paper']) font = {'family': 'serif', #'weight': 'bold', 'size': 12} matplotlib.rc("font", **font) fig, ax = plt.subplots() labels = ['','Regular','AS Leak',' Code Red I','Nimda','Slammer'] #labels = ['a','b','c','d','e'] #ticks=np.linspace(0, 5,num=5) #res = plt.imshow(confmat, interpolation='none') #res = ax.imshow(np.array(confmat), cmap=plt.cm.jet,interpolation='nearest') res = ax.imshow(np.array(confmat), interpolation='nearest') #plt.xlabel('kkk') width, height = confmat.shape #plt.xticks(labels) #plt.tick_params(labelbottom=labels,labelleft=labels) for x in xrange(width): for y in xrange(height): ax.annotate(str(confmat[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center') ax.set_xticklabels(labels) ax.set_yticklabels(labels) plt.tick_params(labelsize=10) plt.colorbar(res,shrink=1, pad=.01, aspect=10) plt.savefig("Fig_10.pdf",dpi=400) #plt.show() print(confmat.shape)
def scaledRender(self,size,ds=0): ''' >>> print(cbmarks['check'].scaledRender(20)) 12.97075 14.68802 m 15.00139 17.16992 l 15.9039 18.1727 17.93454 18.67409 19.2883 18.67409 c 19.46379 18.27298 l 17.13231 15.51532 l 11.91783 8.62117 l 8.307799 3.030641 l 7.430362 1.526462 l 7.305014 1.275766 7.154596 .97493 6.9039 .824513 c 6.577994 .674095 5.825905 .674095 5.47493 .674095 c 4.672702 .674095 4.497214 .674095 4.321727 .799443 c 4.071031 .97493 3.945682 1.325905 3.770195 1.67688 c 3.218663 2.830084 2.240947 5.337047 2.240947 6.590529 c 2.240947 7.016713 2.491643 7.21727 2.817549 7.442897 c 3.344011 7.818942 4.0961 8.245125 4.747911 8.245125 c 5.249304 8.245125 5.299443 7.818942 5.449861 7.417827 c 5.951253 6.239554 l 6.026462 6.038997 6.252089 5.337047 6.527855 5.337047 c 6.778552 5.337047 7.079387 5.913649 7.179666 6.089136 c 12.97075 14.68802 l h f >>> print(cbmarks['cross'].scaledRender(20)) 19.9104 17.43931 m 12.41908 10 l 19.9104 2.534682 l 18.37572 1 l 10.9104 8.491329 l 3.445087 1 l 1.910405 2.534682 l 9.427746 10 l 1.910405 17.46532 l 3.445087 19 l 10.9104 11.50867 l 18.37572 19 l 19.9104 17.43931 l h f >>> print(cbmarks['circle'].scaledRender(20)) 1.872576 9.663435 m 1.872576 14.64958 5.936288 18.61357 10.89751 18.61357 c 15.8338 18.61357 19.87258 14.59972 19.87258 9.663435 c 19.87258 4.727147 15.8338 .688366 10.89751 .688366 c 5.936288 .688366 1.872576 4.677285 1.872576 9.663435 c h f >>> print(cbmarks['star'].scaledRender(20)) 10.85542 18.3253 m 12.90361 11.84337 l 19.84337 11.84337 l 14.25301 7.650602 l 16.42169 1 l 10.85542 5.096386 l 5.289157 1 l 7.481928 7.650602 l 1.843373 11.84337 l 8.759036 11.84337 l 10.85542 18.3253 l h f >>> print(cbmarks['diamond'].scaledRender(20)) 17.43533 9.662031 m 15.63282 7.484006 l 10.85118 .649513 l 8.422809 4.329624 l 5.919332 7.659249 l 4.267038 9.662031 l 6.16968 12.0153 l 10.85118 18.64951 l 12.75382 15.4701 15.00695 12.49096 17.43533 9.662031 c h f ''' #work out the scale and translation W = H = size - 2*ds xmin = self.xmin ymin = self.ymin w = self.xmax-xmin h = self.ymax-ymin slack = self.slack*min(W,H) sx = (W - 2*slack)/float(w) sy = (H - 2*slack)/float(h) sx = sy = min(sx,sy) w *= sx h *= sy dx = ds+(W - w)*0.5 dy = ds+(H - h)*0.5 xsc = lambda v: fp_str((v-xmin)*sx+dx) ysc = lambda v: fp_str((v-ymin)*sy+dy) opNames = self.opNames opCount = self.opCount C = [].append i = 0 points = self.points for op in self.ops: c = opCount[op] for _ in xrange(c): C(xsc(points[i])) C(ysc(points[i+1])) i += 2 C(opNames[op]) C('f') return ' '.join(C.__self__)
def test0(self): ''' Test case for Indexes. This will draw an index %sat the end of the document with dots seperating the indexing terms from the page numbers. Index terms are grouped by their first 2, and first 3 characters. The page numbers should be clickable and link to the indexed word. ''' # Build story. for headers in False, True: path = outputfile('test_platypus_index%s.pdf' % (headers and '_headers' or '')) doc = MyDocTemplate(path) story = [] styleSheet = getSampleStyleSheet() bt = styleSheet['BodyText'] description = '<font color=red>%s</font>' % (self.test0.__doc__ % (headers and 'with alphabetic headers ' or '')) story.append(Paragraph(description, bt)) index = SimpleIndex(dot=' . ', headers=headers) def addParas(words): words = [asUnicode(w) for w in words] txt = u' '.join([(len(w) > 5 and u'<index item=%s/>%s' % (quoteattr(commajoin([w[:2], w[:3], w])), w) or w) for w in words]) para = Paragraph(txt, makeBodyStyle()) story.append(para) for i in xrange(20): addParas(randomtext.randomText(randomtext.PYTHON, 5).split(' ')) addParas([u+w for u in u'E\xc8\xc9\xca\xcb' for w in (u'erily',u'asily')]) addParas([u+w for u in u'A\xc0\xc4\xc1\xc3\xc2' for w in (u'dvance',u'ttend')]) addParas([u+w for u in u'O\xd2\xd6\xd3\xd2' for w in (u'rdinary',u'verflow')]) addParas([u+w for u in u'U\xd9\xdc\xdb' for w in (u'ndertow',u'nbeliever')]) addParas([u+w for u in u'e\xe8\xea\xeb\xe9' for w in (u'ventide',u'lision')]) addParas([u+w for u in u'o\xf2\xf5\xf3\xf4' for w in (u'verture',u'ntology')]) #test ampersand in index term txt = '\nMarks & Spencer - purveyors of fine groceries, underwear and ampersands - should have their initials displayed however they were input.\n<index item="M&S,groceries"/><index item="M&S,underwear"/><index item="M&S,ampersands"/>' para = Paragraph(txt, makeBodyStyle()) story.append(para) story.append(index) doc.build(story, canvasmaker=index.getCanvasMaker())
def scaledRender(self, size, ds=0): ''' >>> print(cbmarks['check'].scaledRender(20)) 12.97075 14.68802 m 15.00139 17.16992 l 15.9039 18.1727 17.93454 18.67409 19.2883 18.67409 c 19.46379 18.27298 l 17.13231 15.51532 l 11.91783 8.62117 l 8.307799 3.030641 l 7.430362 1.526462 l 7.305014 1.275766 7.154596 .97493 6.9039 .824513 c 6.577994 .674095 5.825905 .674095 5.47493 .674095 c 4.672702 .674095 4.497214 .674095 4.321727 .799443 c 4.071031 .97493 3.945682 1.325905 3.770195 1.67688 c 3.218663 2.830084 2.240947 5.337047 2.240947 6.590529 c 2.240947 7.016713 2.491643 7.21727 2.817549 7.442897 c 3.344011 7.818942 4.0961 8.245125 4.747911 8.245125 c 5.249304 8.245125 5.299443 7.818942 5.449861 7.417827 c 5.951253 6.239554 l 6.026462 6.038997 6.252089 5.337047 6.527855 5.337047 c 6.778552 5.337047 7.079387 5.913649 7.179666 6.089136 c 12.97075 14.68802 l h f >>> print(cbmarks['cross'].scaledRender(20)) 19.9104 17.43931 m 12.41908 10 l 19.9104 2.534682 l 18.37572 1 l 10.9104 8.491329 l 3.445087 1 l 1.910405 2.534682 l 9.427746 10 l 1.910405 17.46532 l 3.445087 19 l 10.9104 11.50867 l 18.37572 19 l 19.9104 17.43931 l h f >>> print(cbmarks['circle'].scaledRender(20)) 1.872576 9.663435 m 1.872576 14.64958 5.936288 18.61357 10.89751 18.61357 c 15.8338 18.61357 19.87258 14.59972 19.87258 9.663435 c 19.87258 4.727147 15.8338 .688366 10.89751 .688366 c 5.936288 .688366 1.872576 4.677285 1.872576 9.663435 c h f >>> print(cbmarks['star'].scaledRender(20)) 10.85542 18.3253 m 12.90361 11.84337 l 19.84337 11.84337 l 14.25301 7.650602 l 16.42169 1 l 10.85542 5.096386 l 5.289157 1 l 7.481928 7.650602 l 1.843373 11.84337 l 8.759036 11.84337 l 10.85542 18.3253 l h f >>> print(cbmarks['diamond'].scaledRender(20)) 17.43533 9.662031 m 15.63282 7.484006 l 10.85118 .649513 l 8.422809 4.329624 l 5.919332 7.659249 l 4.267038 9.662031 l 6.16968 12.0153 l 10.85118 18.64951 l 12.75382 15.4701 15.00695 12.49096 17.43533 9.662031 c h f ''' #work out the scale and translation W = H = size - 2 * ds xmin = self.xmin ymin = self.ymin w = self.xmax - xmin h = self.ymax - ymin slack = self.slack * min(W, H) sx = (W - 2 * slack) / float(w) sy = (H - 2 * slack) / float(h) sx = sy = min(sx, sy) w *= sx h *= sy dx = ds + (W - w) * 0.5 dy = ds + (H - h) * 0.5 xsc = lambda v: fp_str((v - xmin) * sx + dx) ysc = lambda v: fp_str((v - ymin) * sy + dy) opNames = self.opNames opCount = self.opCount C = [].append i = 0 points = self.points for op in self.ops: c = opCount[op] for _ in xrange(c): C(xsc(points[i])) C(ysc(points[i + 1])) i += 2 C(opNames[op]) C('f') return ' '.join(C.__self__)
def unpack_cell_range_address_list_update_pos(output_list, data, pos, biff_version, addr_size=6): # output_list is updated in situ assert addr_size in (6, 8) # Used to assert size == 6 if not BIFF8, but pyWLWriter writes # BIFF8-only MERGEDCELLS records in a BIFF5 file! n, = unpack("<H", data[pos:pos + 2]) pos += 2 if n: if addr_size == 6: fmt = "<HHBB" else: fmt = "<HHHH" for _unused in xrange(n): ra, rb, ca, cb = unpack(fmt, data[pos:pos + addr_size]) output_list.append((ra, rb + 1, ca, cb + 1)) pos += addr_size return pos
def testAsciiBase85RoundTrip(self): plain = 'What is the average velocity of a sparrow?' eFuncs = getFuncs('asciiBase85Encode') for i in xrange(256): for j, (dfunc, kind) in enumerate(getFuncs('asciiBase85Decode')): efunc = eFuncs[j][0] encoded = efunc(plain) decoded = dfunc(encoded) assert decoded == asBytes( plain, 'latin1' ), "Round-trip AsciiBase85 failed for %s & %s\nplain=%s\nencoded=%s\ndecoded=%s" % ( ascii(efunc), ascii(dfunc), ascii(plain), ascii(encoded), ascii(decoded)) if not j: enc0 = encoded dec0 = decoded else: assert encoded == enc0, " Python & C encodings differ failed for %s & %s\nplain=%s\nencode0=%s\nencoded=%s\ndecode0=%sdecoded=%s" % ( ascii(efunc), ascii(dfunc), ascii(plain), ascii(enc0), ascii(encoded), ascii(dec0), ascii(decoded)) assert decoded == dec0, " Python & C decodings differ failed for %s & %s\nplain=%s\nencode0=%s\nencoded=%s\ndecode0=%sdecoded=%s" % ( ascii(efunc), ascii(dfunc), ascii(plain), ascii(enc0), ascii(encoded), ascii(dec0), ascii(decoded)) plain += chr(i)
def handle_palette(book, data): if not book.formatting_info: return blah = DEBUG or book.verbosity >= 2 n_colours, = unpack('<H', data[:2]) expected_n_colours = (16, 56)[book.biff_version >= 50] if ((DEBUG or book.verbosity >= 1) and n_colours != expected_n_colours): fprintf(book.logfile, "NOTE *** Expected %d colours in PALETTE record, found %d\n", expected_n_colours, n_colours) elif blah: fprintf(book.logfile, "PALETTE record with %d colours\n", n_colours) fmt = '<xx%di' % n_colours # use i to avoid long integers expected_size = 4 * n_colours + 2 actual_size = len(data) tolerance = 4 if not expected_size <= actual_size <= expected_size + tolerance: raise XLRDError('PALETTE record: expected size %d, actual size %d' % (expected_size, actual_size)) colours = unpack(fmt, data[:expected_size]) assert book.palette_record == [] # There should be only 1 PALETTE record # a colour will be 0xbbggrr # IOW, red is at the little end for i in xrange(n_colours): c = colours[i] red = c & 0xff green = (c >> 8) & 0xff blue = (c >> 16) & 0xff old_rgb = book.colour_map[8 + i] new_rgb = (red, green, blue) book.palette_record.append(new_rgb) book.colour_map[8 + i] = new_rgb if blah: if new_rgb != old_rgb: print("%2d: %r -> %r" % (i, old_rgb, new_rgb), file=book.logfile)
]) print(ET.__file__, ET.__name__, etree_version, ET_has_iterparse, file=logfile) def split_tag(tag): pos = tag.rfind('}') + 1 if pos >= 2: return tag[:pos], tag[pos:] return '', tag def augment_keys(adict, uri): # uri must already be enclosed in {} for x in list(adict.keys()): adict[uri + x] = adict[x] _UPPERCASE_1_REL_INDEX = {} # Used in fast conversion of column names (e.g. "XFD") to indices (16383) for _x in xrange(26): _UPPERCASE_1_REL_INDEX["ABCDEFGHIJKLMNOPQRSTUVWXYZ"[_x]] = _x + 1 for _x in "123456789": _UPPERCASE_1_REL_INDEX[_x] = 0 del _x def cell_name_to_rowx_colx(cell_name, letter_value=_UPPERCASE_1_REL_INDEX): # Extract column index from cell name # A<row number> => 0, Z =>25, AA => 26, XFD => 16383 colx = 0 charx = -1 try: for c in cell_name: charx += 1 lv = letter_value[c] if lv:
def draw(self): colorNamePairs = self.colorNamePairs autoCP = isAuto(colorNamePairs) if autoCP: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) swatchMarker = None autoCP = Auto(obj=chart) n = chart._seriesCount chartTexts = self._getTexts(colorNamePairs) else: swatchMarker = getattr(self,'swatchMarker',None) if isAuto(swatchMarker): chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)) swatchMarker = Auto(obj=chart) n = len(colorNamePairs) dx = self.dx dy = self.dy alignment = self.alignment columnMaximum = self.columnMaximum deltax = self.deltax deltay = self.deltay dxTextSpace = self.dxTextSpace fontName = self.fontName fontSize = self.fontSize fillColor = self.fillColor strokeWidth = self.strokeWidth strokeColor = self.strokeColor subCols = self.subCols leading = fontSize*1.2 yGap = self.yGap if not deltay: deltay = max(dy,leading)+self.autoYPadding ba = self.boxAnchor maxWidth = self._calculateMaxBoundaries(colorNamePairs) nCols = int((n+columnMaximum-1)/(columnMaximum*1.0)) xW = dx+dxTextSpace+self.autoXPadding variColumn = self.variColumn if variColumn: width = sum([m[-1] for m in maxWidth])+xW*nCols else: deltax = max(maxWidth[-1]+xW,deltax) width = nCols*deltax maxWidth = nCols*[maxWidth] thisx = self.x thisy = self.y - self.dy if ba not in ('ne','n','nw','autoy'): height = self._calcHeight() if ba in ('e','c','w'): thisy += height/2. else: thisy += height if ba not in ('nw','w','sw','autox'): if ba in ('n','c','s'): thisx -= width/2 else: thisx -= width upperlefty = thisy g = Group() ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize # normalize lim = columnMaximum - 1 callout = getattr(self,'callout',None) scallout = getattr(self,'swatchCallout',None) dividerLines = self.dividerLines if dividerLines: dividerWidth = self.dividerWidth dividerColor = self.dividerColor dividerDashArray = self.dividerDashArray dividerOffsX = self.dividerOffsX dividerOffsY = self.dividerOffsY for i in xrange(n): if autoCP: col = autoCP col.index = i name = chartTexts[i] else: col, name = colorNamePairs[i] if isAuto(swatchMarker): col = swatchMarker col.index = i if isAuto(name): name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i) T = _getLines(name) S = [] aS = S.append j = int(i/(columnMaximum*1.0)) jOffs = maxWidth[j] # thisy+dy/2 = y+leading/2 y = y0 = thisy+(dy-ascent)*0.5 if callout: callout(self,g,thisx,y,(col,name)) if alignment == "left": x = thisx xn = thisx+jOffs[-1]+dxTextSpace elif alignment == "right": x = thisx+dx+dxTextSpace xn = thisx else: raise ValueError("bad alignment") if not isSeq(name): T = [T] lineCount = _getLineCount(name) yd = y for k,lines in enumerate(T): y = y0 kk = k*2 x1 = x+jOffs[kk] x2 = x+jOffs[kk+1] sc = subCols[k,i] anchor = sc.align scdx = sc.dx scdy = sc.dy fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) fC = getattr(sc,'fillColor',fillColor) fL = sc.leading or 1.2*fontSize if fN==fontName: fA = (ascent*fS)/fontSize else: fA = getFont(fontName).face.ascent/1000. if fA==0: fA=0.718 fA *= fS vA = sc.vAlign if vA=='top': vAdy = 0 else: vAdy = -fL * (lineCount - len(lines)) if vA=='middle': vAdy *= 0.5 if anchor=='left': anchor = 'start' xoffs = x1 elif anchor=='right': anchor = 'end' xoffs = x2 elif anchor=='numeric': xoffs = x2 else: anchor = 'middle' xoffs = 0.5*(x1+x2) for t in lines: aS(String(xoffs+scdx,y+scdy+vAdy,t,fontName=fN,fontSize=fS,fillColor=fC, textAnchor = anchor)) y -= fL yd = min(yd,y) y += fL for iy, a in ((y-max(fL-fA,0),'underlines'),(y+fA,'overlines')): il = getattr(sc,a,None) if il: if not isinstance(il,(tuple,list)): il = (il,) for l in il: l = copy.copy(l) l.y1 += iy l.y2 += iy l.x1 += x1 l.x2 += x2 aS(l) x = xn y = yd leadingMove = 2*y0-y-thisy if dividerLines: xd = thisx+dx+dxTextSpace+jOffs[-1]+dividerOffsX[1] yd = thisy+dy*0.5+dividerOffsY if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum): g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)): yd -= max(deltay,leadingMove)+yGap g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) # Make a 'normal' color swatch... swatchX = x + getattr(self,'swdx',0) swatchY = thisy + getattr(self,'swdy',0) if isAuto(col): chart = getattr(col,'chart',getattr(col,'obj',None)) c = chart.makeSwatchSample(getattr(col,'index',i),swatchX,swatchY,dx,dy) elif isinstance(col, colors.Color): if isSymbol(swatchMarker): c = uSymbol2Symbol(swatchMarker,swatchX+dx/2.,swatchY+dy/2.,col) else: c = self._defaultSwatch(swatchX,swatchY,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor) elif col is not None: try: c = copy.deepcopy(col) c.x = swatchX c.y = swatchY c.width = dx c.height = dy except: c = None else: c = None if c: g.add(c) if scallout: scallout(self,g,thisx,y0,i,(col,name),c) for s in S: g.add(s) if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)): if alignment == "left": xt = thisx else: xt = thisx+dx+dxTextSpace yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap) self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1]+dx+dxTextSpace) if i%columnMaximum==lim: if variColumn: thisx += jOffs[-1]+xW else: thisx = thisx+deltax thisy = upperlefty else: thisy = thisy-max(deltay,leadingMove)-yGap return g
(14, 22, FDT), (27, 36, FDT), # CJK date formats (37, 44, FNU), (45, 47, FDT), (48, 48, FNU), (49, 49, FTX), # Gnumeric assumes (or assumed) that built-in formats finish at 49, not at 163 (50, 58, FDT), # CJK date formats (59, 62, FNU), # Thai number (currency?) formats (67, 70, FNU), # Thai number (currency?) formats (71, 81, FDT), # Thai date formats ] std_format_code_types = {} for lo, hi, ty in fmt_code_ranges: for x in xrange(lo, hi + 1): std_format_code_types[x] = ty del lo, hi, ty, x date_chars = UNICODE_LITERAL('ymdhs') # year, month/minute, day, hour, second date_char_dict = {} for _c in date_chars + date_chars.upper(): date_char_dict[_c] = 5 del _c, date_chars skip_char_dict = {} for _c in UNICODE_LITERAL('$-+/(): '): skip_char_dict[_c] = 1 num_char_dict = { UNICODE_LITERAL('0'): 5,
def testNewAcroform(self): from reportlab.lib.colors import toColor, black, red, green, blue, magenta, yellow, pink canv = canvas.Canvas(outputfile("test_pdfbase_acroform-0.pdf")) doc = canv._doc af = canv.acroForm #these are absolute in unchanged matrix canv.drawString(4 * 72, 800, 'unshifted absolute') af.checkbox(name='cb1A', tooltip='Field cb1A', checked=True, x=72, y=72, buttonStyle='circle', borderWidth=1, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb1B', tooltip='Field cb1B', checked=True, x=72, y=72 + 36, buttonStyle='check', borderWidth=2, borderColor=green, fillColor=blue, textColor=red, forceBorder=True) af.checkbox(name='cb1C', tooltip='Field cb1C', checked=True, x=72, y=72 + 2 * 36, buttonStyle='cross', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb1D', tooltip='Field cb1D', checked=True, x=72, y=72 + 3 * 36, buttonStyle='star', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb1E', tooltip='Field cb1E', checked=True, x=72, y=72 + 4 * 36, buttonStyle='diamond', borderStyle='bevelled', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb1F', tooltip='Field cb1F', checked=True, x=72, y=72 + 5 * 36, buttonStyle='check', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb1H', tooltip='Field cb1H', checked=True, x=72, y=72 + 6 * 36, buttonStyle='check', borderStyle='underlined', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb1G', tooltip='Field cb1G', checked=True, x=72, y=72 + 7 * 36, buttonStyle='check', borderStyle='dashed', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb1I', tooltip='Field cb1I', checked=True, x=72, y=72 + 8 * 36, buttonStyle='check', borderStyle='inset', borderWidth=1, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb1J', tooltip='Field cb1J', checked=True, x=72, y=72 + 9 * 36, buttonStyle='check', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb1K', tooltip='Field cb1K', checked=True, x=72, y=72 + 10 * 36, buttonStyle='check', borderWidth=1, borderColor=None, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb1L', tooltip='Field cb1L', checked=False, x=72, y=800, buttonStyle='check', borderWidth=None, borderColor=None, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb1M', tooltip='Field cb1M', checked=False, x=72, y=600, buttonStyle='check', borderWidth=2, borderColor=blue, fillColor=None, textColor=None, forceBorder=True) af.radio(name='rb1A', tooltip='Field rb1A', value='V1', selected=False, x=144, y=72 + 0 * 36, buttonStyle='circle', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.radio(name='rb1A', tooltip='Field rb1A', value='V2', selected=True, x=144, y=72 + 1 * 36, buttonStyle='circle', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.radio(name='rb1B', tooltip='Field rb1B', value='V1', selected=False, x=144 + 36, y=72 + 0 * 36, buttonStyle='check', borderStyle='solid', shape='square', borderWidth=2, borderColor=green, fillColor=red, textColor=blue, forceBorder=True) af.radio(name='rb1B', tooltip='Field rb1B', value='V2', selected=False, x=144 + 36, y=72 + 1 * 36, buttonStyle='check', borderStyle='solid', shape='square', borderWidth=2, borderColor=green, fillColor=red, textColor=blue, forceBorder=True) af.radio(name='rb1C', tooltip='Field rb1C', value='V1', selected=False, x=144 * 2, y=72 + 0 * 36, buttonStyle='circle', borderStyle='bevelled', shape='circle', borderWidth=2, borderColor=green, fillColor=yellow, textColor=blue, forceBorder=True) af.radio(name='rb1C', tooltip='Field rb1C', value='V2', selected=True, x=144 * 2, y=72 + 1 * 36, buttonStyle='circle', borderStyle='inset', shape='circle', borderWidth=2, borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfield(name='tf1A', tooltip='Field tf1A', value='Hello World', x=144 * 2 + 36, y=72 + 0 * 36, borderStyle='inset', borderWidth=2, borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfield(name='tf1B', tooltip='Field tf1B', value='Hello World', x=144 * 2 + 36, y=72 + 2 * 36, borderStyle='inset', borderWidth=2, fontName='Courier-Bold', borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfield(name='tf1C', tooltip='Field tf1C', value='Hello World', x=144 * 2 + 36, y=72 + 3 * 36, borderStyle='inset', borderWidth=0, fontName='Courier-Bold', borderColor=green, fillColor=red, textColor=black) canv.showPage() canv.translate(72, 0) #shift matrix #these are absolute in changed matrix canv.drawString(4 * 72, 800, 'shifted absolute') af.checkbox(name='cb2A', tooltip='Field cb2A', checked=True, x=72, y=72, buttonStyle='circle', borderWidth=1, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb2B', tooltip='Field cb2B', checked=True, x=72, y=72 + 36, buttonStyle='check', borderWidth=2, borderColor=green, fillColor=blue, textColor=red, forceBorder=True) af.checkbox(name='cb2C', tooltip='Field cb2C', checked=True, x=72, y=72 + 2 * 36, buttonStyle='cross', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb2D', tooltip='Field cb2D', checked=True, x=72, y=72 + 3 * 36, buttonStyle='star', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb2E', tooltip='Field cb2E', checked=True, x=72, y=72 + 4 * 36, buttonStyle='diamond', borderStyle='bevelled', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb2F', tooltip='Field cb2F', checked=True, x=72, y=72 + 5 * 36, buttonStyle='check', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb2H', tooltip='Field cb2H', checked=True, x=72, y=72 + 6 * 36, buttonStyle='check', borderStyle='underlined', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb2G', tooltip='Field cb2G', checked=True, x=72, y=72 + 7 * 36, buttonStyle='check', borderStyle='dashed', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb2I', tooltip='Field cb2I', checked=True, x=72, y=72 + 8 * 36, buttonStyle='check', borderStyle='inset', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb2J', tooltip='Field cb2J', checked=True, x=72, y=72 + 9 * 36, buttonStyle='check', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkbox(name='cb2K', tooltip='Field cb2K', checked=True, x=72, y=72 + 10 * 36, buttonStyle='check', borderWidth=1, borderColor=None, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb2L', tooltip='Field cb2L', checked=False, x=72, y=800, buttonStyle='check', borderWidth=None, borderColor=None, fillColor=None, textColor=None, forceBorder=True) af.checkbox(name='cb2M', tooltip='Field cb2M', checked=False, x=72, y=600, buttonStyle='check', borderWidth=2, borderColor=blue, fillColor=None, textColor=None, forceBorder=True) af.radio(name='rb2A', tooltip='Field rb2A', value='V1', selected=False, x=144, y=72 + 0 * 36, buttonStyle='circle', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.radio(name='rb2A', tooltip='Field rb2A', value='V2', selected=True, x=144, y=72 + 1 * 36, buttonStyle='circle', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.radio(name='rb2B', tooltip='Field rb2B', value='V1', selected=False, x=144 + 36, y=72 + 0 * 36, buttonStyle='check', borderStyle='solid', shape='square', borderWidth=2, borderColor=green, fillColor=red, textColor=blue, forceBorder=True) af.radio(name='rb2B', tooltip='Field rb2B', value='V2', selected=False, x=144 + 36, y=72 + 1 * 36, buttonStyle='check', borderStyle='solid', shape='square', borderWidth=2, borderColor=green, fillColor=red, textColor=blue, forceBorder=True) af.radio(name='rb2C', tooltip='Field rb2C', value='V1', selected=False, x=144 * 2, y=72 + 0 * 36, buttonStyle='circle', borderStyle='bevelled', shape='circle', borderWidth=2, borderColor=green, fillColor=yellow, textColor=blue, forceBorder=True) af.radio(name='rb2C', tooltip='Field rb2C', value='V2', selected=True, x=144 * 2, y=72 + 1 * 36, buttonStyle='circle', borderStyle='inset', shape='circle', borderWidth=2, borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfield(name='tf2A', tooltip='Field tf2A', value='Hello World', x=144 * 2 + 36, y=72 + 0 * 36, borderStyle='inset', borderWidth=2, borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfield(name='tf2B', tooltip='Field tf2B', value='Hello World', x=144 * 2 + 36, y=72 + 2 * 36, borderStyle='inset', borderWidth=2, fontName='Courier-Bold', borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfield(name='tf2C', tooltip='Field tf2C', value='Hello World', x=144 * 2 + 36, y=72 + 3 * 36, borderStyle='inset', borderWidth=0, fontName='Courier-Bold', borderColor=green, fillColor=red, textColor=black) canv.showPage() canv.translate(72, 0) #shift matrix #these are relative in changed matrix canv.drawString(4 * 72, 800, 'shifted relative') af.checkboxRelative(name='cb3A', tooltip='Field cb3A', checked=True, x=72, y=72, buttonStyle='circle', borderWidth=1, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkboxRelative(name='cb3B', tooltip='Field cb3B', checked=True, x=72, y=72 + 36, buttonStyle='check', borderWidth=2, borderColor=green, fillColor=blue, textColor=red, forceBorder=True) af.checkboxRelative(name='cb3C', tooltip='Field cb3C', checked=True, x=72, y=72 + 2 * 36, buttonStyle='cross', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkboxRelative(name='cb3D', tooltip='Field cb3D', checked=True, x=72, y=72 + 3 * 36, buttonStyle='star', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkboxRelative(name='cb3E', tooltip='Field cb3E', checked=True, x=72, y=72 + 4 * 36, buttonStyle='diamond', borderStyle='bevelled', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkboxRelative(name='cb3F', tooltip='Field cb3F', checked=True, x=72, y=72 + 5 * 36, buttonStyle='check', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkboxRelative(name='cb3H', tooltip='Field cb3H', checked=True, x=72, y=72 + 6 * 36, buttonStyle='check', borderStyle='underlined', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkboxRelative(name='cb3G', tooltip='Field cb3G', checked=True, x=72, y=72 + 7 * 36, buttonStyle='check', borderStyle='dashed', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkboxRelative(name='cb3I', tooltip='Field cb3I', checked=True, x=72, y=72 + 8 * 36, buttonStyle='check', borderStyle='inset', borderWidth=2, borderColor=red, fillColor=None, textColor=None, forceBorder=True) af.checkboxRelative(name='cb3J', tooltip='Field cb3J', checked=True, x=72, y=72 + 9 * 36, buttonStyle='check', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.checkboxRelative(name='cb3K', tooltip='Field cb3K', checked=True, x=72, y=72 + 10 * 36, buttonStyle='check', borderWidth=1, borderColor=None, fillColor=None, textColor=None, forceBorder=True) af.checkboxRelative(name='cb3L', tooltip='Field cb3L', checked=False, x=72, y=800, buttonStyle='check', borderWidth=None, borderColor=None, fillColor=None, textColor=None, forceBorder=True) af.checkboxRelative(name='cb3M', tooltip='Field cb3M', checked=False, x=72, y=600, buttonStyle='check', borderWidth=2, borderColor=blue, fillColor=None, textColor=None, forceBorder=True) af.radioRelative(name='rb3A', tooltip='Field rb3A', value='V1', selected=False, x=144, y=72 + 0 * 36, buttonStyle='circle', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.radioRelative(name='rb3A', tooltip='Field rb3A', value='V2', selected=True, x=144, y=72 + 1 * 36, buttonStyle='circle', borderStyle='solid', shape='circle', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) af.radioRelative(name='rb3B', tooltip='Field rb3B', value='V1', selected=False, x=144 + 36, y=72 + 0 * 36, buttonStyle='check', borderStyle='solid', shape='square', borderWidth=2, borderColor=green, fillColor=red, textColor=blue, forceBorder=True) af.radioRelative(name='rb3B', tooltip='Field rb3B', value='V2', selected=False, x=144 + 36, y=72 + 1 * 36, buttonStyle='check', borderStyle='solid', shape='square', borderWidth=2, borderColor=green, fillColor=red, textColor=blue, forceBorder=True) af.radioRelative(name='rb3C', tooltip='Field rb3C', value='V1', selected=False, x=144 * 2, y=72 + 0 * 36, buttonStyle='circle', borderStyle='bevelled', shape='circle', borderWidth=2, borderColor=green, fillColor=yellow, textColor=blue, forceBorder=True) af.radioRelative(name='rb3C', tooltip='Field rb3C', value='V2', selected=True, x=144 * 2, y=72 + 1 * 36, buttonStyle='circle', borderStyle='inset', shape='circle', borderWidth=2, borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfieldRelative(name='tf3A', tooltip='Field tf3A', value='Hello World', x=144 * 2 + 36, y=72 + 0 * 36, borderStyle='inset', borderWidth=2, borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfieldRelative(name='tf3B', tooltip='Field tf3B', value='Hello World', x=144 * 2 + 36, y=72 + 2 * 36, borderStyle='inset', borderWidth=2, fontName='Courier-Bold', borderColor=magenta, fillColor=pink, textColor=blue, forceBorder=True) af.textfieldRelative(name='tf3C', tooltip='Field tf3C', value='Hello World', x=144 * 2 + 36, y=72 + 3 * 36, borderStyle='inset', borderWidth=0, fontName='Courier-Bold', borderColor=green, fillColor=red, textColor=black) canv.showPage() BS = ['solid', 'bevelled', 'inset', 'dashed', 'underlined'] V = ['Av', 'B', 'Cv', 'D', 'Dv', 'E', 'F', 'G', 'Gv'] ff = ['', 'edit'] for i in xrange(500): x = 72 + (i % 3) * 180 y = 800 - int(i / 3) * 36 if y < 100: break value = V[i % len(V)] bW = i % 3 + 1 af.choice(name='CH%d' % i, value=value, x=x, y=y, width=72 + bW, height=20 + bW, borderStyle=BS[i % 5], borderWidth=bW, fieldFlags=ff[i and i % 9 == 0], borderColor=red, fillColor=green, textColor=blue, forceBorder=False, tooltip='CH%d value=%r' % (i, value), options=[('A', 'Av'), 'B', ('C', 'Cv'), ('D', 'Dv'), 'E', ('F', ), ('G', 'Gv')]) canv.showPage() BS = ['solid', 'bevelled', 'inset', 'dashed', 'underlined'] V = ['Av', 'B', 'Cv', 'D', 'Dv', 'E', 'F', 'G', 'Gv', 'H'] ff = ['', 'multiSelect'] for i in xrange(500): x = 72 + (i % 3) * 180 y = 800 - int(i / 3) * 108 - 52 if y < 100: break v = i % len(V) value = [V[v]] if v >= 5: v1 = V[3 + i % 5] if v1 not in value: value.append(v1) bW = i % 3 + 1 fieldFlags = ff[len(value) > 1] af.listbox(name='LB%d' % i, value=value, x=x, y=y, width=72 + bW, height=72 + bW, borderStyle=BS[i % 5], borderWidth=bW, fieldFlags=fieldFlags, borderColor=red, fillColor=green, textColor=blue, forceBorder=False, tooltip='LB%d value=%r' % (i, value), options=[('A', 'Av'), 'B', ('C', 'Cv'), ('D', 'Dv'), 'E', ('F', ), ('G', 'Gv'), 'H']) canv.showPage() canv.save()
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/renderPS.py __version__ = '3.3.0' __doc__ = """Render drawing objects in Postscript""" from reportlab.pdfbase.pdfmetrics import getFont, stringWidth, unicode2T1 # for font info from reportlab.lib.utils import getBytesIO, getStringIO, asBytes, char2int, rawBytes, asNative, isUnicode from reportlab.lib.rl_accel import fp_str from reportlab.lib.colors import black from reportlab.graphics.renderbase import Renderer, StateTracker, getStateDelta, renderScaledDrawing from reportlab.graphics.shapes import STATE_DEFAULTS import math from operator import getitem from reportlab import rl_config, xrange, ascii from reportlab.pdfgen.canvas import FILL_EVEN_ODD, FILL_NON_ZERO _ESCAPEDICT = {} for c in xrange(256): if c < 32 or c >= 127: _ESCAPEDICT[c] = '\\%03o' % c elif c in (ord('\\'), ord('('), ord(')')): _ESCAPEDICT[c] = '\\' + chr(c) else: _ESCAPEDICT[c] = chr(c) del c def _escape_and_limit(s): s = asBytes(s) R = [] aR = R.append n = 0 for c in s:
def test0(self): "IndentTestCase test0" # Build story. story = [] doc = MyDocTemplate(outputfile('test_platypus_indents.pdf')) storyAdd = story.append styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.spaceBefore = 18 bt = styleSheet['BodyText'] bt.spaceBefore = 6 storyAdd(Paragraph('Test of context-relative indentation', h1)) storyAdd(Spacer(18, 18)) storyAdd(Indenter(0, 0)) storyAdd( Paragraph( "This should be indented 0 points at each edge. " + ("spam " * 25), bt)) storyAdd(Indenter(0, 0)) storyAdd(Indenter(36, 0)) storyAdd( Paragraph( "This should be indented 36 points at the left. " + ("spam " * 25), bt)) storyAdd(Indenter(-36, 0)) storyAdd(Indenter(0, 36)) storyAdd( Paragraph( "This should be indented 36 points at the right. " + ("spam " * 25), bt)) storyAdd(Indenter(0, -36)) storyAdd(Indenter(36, 36)) storyAdd( Paragraph( "This should be indented 36 points at each edge. " + ("spam " * 25), bt)) storyAdd(Indenter(36, 36)) storyAdd( Paragraph( "This should be indented a FURTHER 36 points at each edge. " + ("spam " * 25), bt)) storyAdd(Indenter(-72, -72)) storyAdd( Paragraph( "This should be back to normal at each edge. " + ("spam " * 25), bt)) storyAdd(Indenter(36, 36)) storyAdd( Paragraph(("""This should be indented 36 points at the left and right. It should run over more than one page and the indent should continue on the next page. """ + (random.randint(0, 10) * 'x') + ' ') * 20, bt)) storyAdd(Indenter(-36, -36)) storyAdd(NextPageTemplate('updown')) storyAdd(FrameBreak()) storyAdd(Paragraph('Another test of context-relative indentation', h1)) storyAdd(NextPageTemplate( 'normal')) # so NEXT page is different template... storyAdd( Paragraph( """This time we see if the indent level is continued across frames...this page has 2 frames, let's see if it carries top to bottom. Then onto a totally different template.""", bt)) storyAdd(Indenter(0, 0)) storyAdd( Paragraph( "This should be indented 0 points at each edge. " + ("spam " * 25), bt)) storyAdd(Indenter(0, 0)) storyAdd(Indenter(36, 72)) storyAdd( Paragraph(("""This should be indented 36 points at the left and 72 at the right. It should run over more than one frame and one page, and the indent should continue on the next page. """ + (random.randint(0, 10) * 'x') + ' ') * 35, bt)) storyAdd(Indenter(-36, -72)) storyAdd( Paragraph( "This should be back to normal at each edge. " + ("spam " * 25), bt)) storyAdd(PageBreak()) storyAdd(PageBreak()) storyAdd( Paragraph( "Below we should colour the background lightgreen and have a red border", bt)) storyAdd( FrameBG(start=True, color=lightgreen, strokeColor=toColor('red'), strokeWidth=1)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(Spacer(6, 6)) storyAdd(FrameBG(start=False)) storyAdd( Paragraph("Below we should colour the background lightgreen", bt)) storyAdd( FrameBG(start=True, color=lightgreen, strokeColor=toColor('red'), strokeWidth=None)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(Spacer(6, 6)) storyAdd(FrameBG(start=False)) storyAdd( Paragraph( "Below we split to two new frames with dark green borders", bt)) storyAdd(FrameSplitter('templateX', ['XF4', 'XF5'], adjustHeight=False)) storyAdd( FrameBG(start=True, color=lightgreen, strokeColor=toColor('red'), strokeWidth=1)) for i in xrange(15): storyAdd( Paragraph( "We should have a light green background here %d" % i, bt)) storyAdd(Spacer(6, 6)) storyAdd(FrameBG(start=False)) storyAdd(NextPageTemplate('normal')) storyAdd(PageBreak()) storyAdd( Paragraph("Below we should colour the background lightgreen", bt)) storyAdd(FrameBG(start="frame", color=lightgreen)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(PageBreak()) storyAdd(Paragraph("Here we should have no background.", bt)) storyAdd(PageBreak()) storyAdd(FrameBG(start="frame", color=lightblue)) storyAdd( Paragraph( "We should have a light blue background here and the whole frame should be filled in.", bt)) storyAdd(PageBreak()) storyAdd(Paragraph("Here we should have no background again.", bt)) storyAdd( Paragraph("Below we should colour the background lightgreen", bt)) storyAdd(FrameBG(start="frame-permanent", color=lightgreen)) storyAdd(Paragraph("We should have a light green background here", bt)) storyAdd(PageBreak()) storyAdd( Paragraph("Here we should still have a lightgreen background.", bt)) storyAdd(PageBreak()) storyAdd(FrameBG(start="frame", color=lightblue, left=36, right=36)) storyAdd( Paragraph("We should have a lighgreen/lightblue background.", bt)) storyAdd(PageBreak()) storyAdd( Paragraph("Here we should have only light green background.", bt)) doc.multiBuild(story)
def makeSectors(self): # normalize slice data data = self.data multi = isListOfListOfNoneOrNumber(data) if multi: #it's a nested list, more than one sequence normData = [] n = [] for l in data: t = self.normalizeData(l) normData.append(t) n.append(len(t)) self._seriesCount = max(n) else: normData = self.normalizeData(data) n = len(normData) self._seriesCount = n #labels checkLabelOverlap = self.checkLabelOverlap L = [] L_add = L.append labels = self.labels if labels is None: labels = [] if not multi: labels = [''] * n else: for m in n: labels = list(labels) + [''] * m else: #there's no point in raising errors for less than enough labels if #we silently create all for the extreme case of no labels. if not multi: i = n-len(labels) if i>0: labels = list(labels) + [''] * i else: tlab = 0 for m in n: tlab += m i = tlab-len(labels) if i>0: labels = list(labels) + [''] * i self.labels = labels xradius = self.width/2.0 yradius = self.height/2.0 centerx = self.x + xradius centery = self.y + yradius if self.direction == "anticlockwise": whichWay = 1 else: whichWay = -1 g = Group() startAngle = self.startAngle #% 360 styleCount = len(self.slices) irf = self.innerRadiusFraction if multi: #multi-series doughnut ndata = len(data) if irf is None: yir = (yradius/2.5)/ndata xir = (xradius/2.5)/ndata else: yir = yradius*irf xir = xradius*irf ydr = (yradius-yir)/ndata xdr = (xradius-xir)/ndata for sn,series in enumerate(normData): for i,angle in enumerate(series): endAngle = (startAngle + (angle * whichWay)) #% 360 aa = abs(startAngle-endAngle) if aa<1e-5: startAngle = endAngle continue if startAngle < endAngle: a1 = startAngle a2 = endAngle else: a1 = endAngle a2 = startAngle startAngle = endAngle #if we didn't use %stylecount here we'd end up with the later sectors #all having the default style sectorStyle = self.slices[sn,i%styleCount] # is it a popout? cx, cy = centerx, centery if sectorStyle.popout != 0: # pop out the sector averageAngle = (a1+a2)/2.0 aveAngleRadians = averageAngle * pi/180.0 popdistance = sectorStyle.popout cx = centerx + popdistance * cos(aveAngleRadians) cy = centery + popdistance * sin(aveAngleRadians) yr1 = yir+sn*ydr yr = yr1 + ydr xr1 = xir+sn*xdr xr = xr1 + xdr if len(series) > 1: theSector = Wedge(cx, cy, xr, a1, a2, yradius=yr, radius1=xr1, yradius1=yr1) else: theSector = Wedge(cx, cy, xr, a1, a2, yradius=yr, radius1=xr1, yradius1=yr1, annular=True) theSector.fillColor = sectorStyle.fillColor theSector.strokeColor = sectorStyle.strokeColor theSector.strokeWidth = sectorStyle.strokeWidth theSector.strokeDashArray = sectorStyle.strokeDashArray shader = sectorStyle.shadingKind if shader: nshades = aa / float(sectorStyle.shadingAngle) if nshades > 1: shader = colors.Whiter if shader=='lighten' else colors.Blacker nshades = 1+int(nshades) shadingAmount = 1-sectorStyle.shadingAmount if sectorStyle.shadingDirection=='normal': dsh = (1-shadingAmount)/float(nshades-1) shf1 = shadingAmount else: dsh = (shadingAmount-1)/float(nshades-1) shf1 = 1 shda = (a2-a1)/float(nshades) shsc = sectorStyle.fillColor theSector.fillColor = None for ish in xrange(nshades): sha1 = a1 + ish*shda sha2 = a1 + (ish+1)*shda shc = shader(shsc,shf1 + dsh*ish) if len(series)>1: shSector = Wedge(cx, cy, xr, sha1, sha2, yradius=yr, radius1=xr1, yradius1=yr1) else: shSector = Wedge(cx, cy, xr, sha1, sha2, yradius=yr, radius1=xr1, yradius1=yr1, annular=True) shSector.fillColor = shc shSector.strokeColor = None shSector.strokeWidth = 0 g.add(shSector) g.add(theSector) if sn == 0 and sectorStyle.visible and sectorStyle.label_visible: text = self.getSeriesName(i,'') if text: averageAngle = (a1+a2)/2.0 aveAngleRadians = averageAngle*pi/180.0 labelRadius = sectorStyle.labelRadius rx = xradius*labelRadius ry = yradius*labelRadius labelX = centerx + (0.5 * self.width * cos(aveAngleRadians) * labelRadius) labelY = centery + (0.5 * self.height * sin(aveAngleRadians) * labelRadius) l = _addWedgeLabel(self,text,averageAngle,labelX,labelY,sectorStyle) if checkLabelOverlap: l._origdata = { 'x': labelX, 'y':labelY, 'angle': averageAngle, 'rx': rx, 'ry':ry, 'cx':cx, 'cy':cy, 'bounds': l.getBounds(), } L_add(l) else: #single series doughnut if irf is None: yir = yradius/2.5 xir = xradius/2.5 else: yir = yradius*irf xir = xradius*irf for i,angle in enumerate(normData): endAngle = (startAngle + (angle * whichWay)) #% 360 aa = abs(startAngle-endAngle) if aa<1e-5: startAngle = endAngle continue if startAngle < endAngle: a1 = startAngle a2 = endAngle else: a1 = endAngle a2 = startAngle startAngle = endAngle #if we didn't use %stylecount here we'd end up with the later sectors #all having the default style sectorStyle = self.slices[i%styleCount] # is it a popout? cx, cy = centerx, centery if sectorStyle.popout != 0: # pop out the sector averageAngle = (a1+a2)/2.0 aveAngleRadians = averageAngle * pi/180.0 popdistance = sectorStyle.popout cx = centerx + popdistance * cos(aveAngleRadians) cy = centery + popdistance * sin(aveAngleRadians) if n > 1: theSector = Wedge(cx, cy, xradius, a1, a2, yradius=yradius, radius1=xir, yradius1=yir) elif n==1: theSector = Wedge(cx, cy, xradius, a1, a2, yradius=yradius, radius1=xir, yradius1=yir, annular=True) theSector.fillColor = sectorStyle.fillColor theSector.strokeColor = sectorStyle.strokeColor theSector.strokeWidth = sectorStyle.strokeWidth theSector.strokeDashArray = sectorStyle.strokeDashArray shader = sectorStyle.shadingKind if shader: nshades = aa / float(sectorStyle.shadingAngle) if nshades > 1: shader = colors.Whiter if shader=='lighten' else colors.Blacker nshades = 1+int(nshades) shadingAmount = 1-sectorStyle.shadingAmount if sectorStyle.shadingDirection=='normal': dsh = (1-shadingAmount)/float(nshades-1) shf1 = shadingAmount else: dsh = (shadingAmount-1)/float(nshades-1) shf1 = 1 shda = (a2-a1)/float(nshades) shsc = sectorStyle.fillColor theSector.fillColor = None for ish in xrange(nshades): sha1 = a1 + ish*shda sha2 = a1 + (ish+1)*shda shc = shader(shsc,shf1 + dsh*ish) if n > 1: shSector = Wedge(cx, cy, xradius, sha1, sha2, yradius=yradius, radius1=xir, yradius1=yir) elif n==1: shSector = Wedge(cx, cy, xradius, sha1, sha2, yradius=yradius, radius1=xir, yradius1=yir, annular=True) shSector.fillColor = shc shSector.strokeColor = None shSector.strokeWidth = 0 g.add(shSector) g.add(theSector) # now draw a label if labels[i] and sectorStyle.visible and sectorStyle.label_visible: averageAngle = (a1+a2)/2.0 aveAngleRadians = averageAngle*pi/180.0 labelRadius = sectorStyle.labelRadius labelX = centerx + (0.5 * self.width * cos(aveAngleRadians) * labelRadius) labelY = centery + (0.5 * self.height * sin(aveAngleRadians) * labelRadius) rx = xradius*labelRadius ry = yradius*labelRadius l = _addWedgeLabel(self,labels[i],averageAngle,labelX,labelY,sectorStyle) if checkLabelOverlap: l._origdata = { 'x': labelX, 'y':labelY, 'angle': averageAngle, 'rx': rx, 'ry':ry, 'cx':cx, 'cy':cy, 'bounds': l.getBounds(), } L_add(l) if checkLabelOverlap and L: fixLabelOverlaps(L) for l in L: g.add(l) return g
def title(n): for _ in xrange(n): print(generator.generate_sent())
def xf_epilogue(self): # self is a Book instance. self._xf_epilogue_done = 1 num_xfs = len(self.xf_list) blah = DEBUG or self.verbosity >= 3 blah1 = DEBUG or self.verbosity >= 1 if blah: fprintf(self.logfile, "xf_epilogue called ...\n") def check_same(book_arg, xf_arg, parent_arg, attr): # the _arg caper is to avoid a Warning msg from Python 2.1 :-( if getattr(xf_arg, attr) != getattr(parent_arg, attr): fprintf(book_arg.logfile, "NOTE !!! XF[%d] parent[%d] %s different\n", xf_arg.xf_index, parent_arg.xf_index, attr) for xfx in xrange(num_xfs): xf = self.xf_list[xfx] if xf.format_key not in self.format_map: msg = "ERROR *** XF[%d] unknown format key (%d, 0x%04x)\n" fprintf(self.logfile, msg, xf.xf_index, xf.format_key, xf.format_key) xf.format_key = 0 fmt = self.format_map[xf.format_key] cellty = _cellty_from_fmtty[fmt.type] self._xf_index_to_xl_type_map[xf.xf_index] = cellty # Now for some assertions etc if not self.formatting_info: continue if xf.is_style: continue if not (0 <= xf.parent_style_index < num_xfs): if blah1: fprintf( self.logfile, "WARNING *** XF[%d]: is_style=%d but parent_style_index=%d\n", xf.xf_index, xf.is_style, xf.parent_style_index) # make it conform xf.parent_style_index = 0 if self.biff_version >= 30: if blah1: if xf.parent_style_index == xf.xf_index: fprintf( self.logfile, "NOTE !!! XF[%d]: parent_style_index is also %d\n", xf.xf_index, xf.parent_style_index) elif not self.xf_list[xf.parent_style_index].is_style: fprintf( self.logfile, "NOTE !!! XF[%d]: parent_style_index is %d; style flag not set\n", xf.xf_index, xf.parent_style_index) if blah1 and xf.parent_style_index > xf.xf_index: fprintf( self.logfile, "NOTE !!! XF[%d]: parent_style_index is %d; out of order?\n", xf.xf_index, xf.parent_style_index) parent = self.xf_list[xf.parent_style_index] if not xf._alignment_flag and not parent._alignment_flag: if blah1: check_same(self, xf, parent, 'alignment') if not xf._background_flag and not parent._background_flag: if blah1: check_same(self, xf, parent, 'background') if not xf._border_flag and not parent._border_flag: if blah1: check_same(self, xf, parent, 'border') if not xf._protection_flag and not parent._protection_flag: if blah1: check_same(self, xf, parent, 'protection') if not xf._format_flag and not parent._format_flag: if blah1 and xf.format_key != parent.format_key: fprintf( self.logfile, "NOTE !!! XF[%d] fmtk=%d, parent[%d] fmtk=%r\n%r / %r\n", xf.xf_index, xf.format_key, parent.xf_index, parent.format_key, self.format_map[xf.format_key].format_str, self.format_map[parent.format_key].format_str) if not xf._font_flag and not parent._font_flag: if blah1 and xf.font_index != parent.font_index: fprintf(self.logfile, "NOTE !!! XF[%d] fontx=%d, parent[%d] fontx=%r\n", xf.xf_index, xf.font_index, parent.xf_index, parent.font_index)
def test1(self): if rl_invariant: random.seed(888147853) styleSheet = getSampleStyleSheet() doc = SimpleDocTemplate(outputfile('test_platypus_lists1.pdf'), showBoundary=True) story = [] sty = [ ('GRID', (0, 0), (-1, -1), 1, colors.green), ('BOX', (0, 0), (-1, -1), 2, colors.red), ] normal = styleSheet['BodyText'] bold = normal.clone('bold', fontName='Helvetica-Bold') lpSty = normal.clone('lpSty', spaceAfter=18) data = [[ str(i + 1), Paragraph("xx " * (i % 10), styleSheet["BodyText"]), Paragraph(("blah " * (i % 40)), normal) ] for i in xrange(5)] data1 = [[ str(i + 1), Paragraph(["zz ", "yy "][i] * (i + 3), styleSheet["BodyText"]), Paragraph(("duh " * (i + 3)), normal) ] for i in xrange(2)] OL = ListFlowable([ Paragraph("A table with 5 rows", lpSty), Table(data, style=sty, colWidths=[50, 100, 200]), ListItem( Paragraph("A sublist", normal), value=7, ), ListFlowable( [ Paragraph("Another table with 3 rows", normal), Table(data[:3], style=sty, colWidths=[60, 90, 180]), Paragraph(TEXTS[0], normal), ], bulletType='i', ), Paragraph("An unordered sublist", normal), ListFlowable( [ Paragraph("A table with 2 rows", normal), ListItem(Table(data1, style=sty, colWidths=[60, 90, 180]), bulletColor='green'), ListItem(Paragraph(TEXTS[2], normal), bulletColor='red', value='square') ], bulletType='bullet', start='circle', ), Paragraph(TEXTS[1], normal), ]) story.append(OL) story.append(PageBreak()) story.append( Paragraph( "Now try a list with a very long URL in it. Without splitting the long word it used to be that this can push out the right page margin", normal)) OL = ListFlowable([ Paragraph(TEXTS[1], normal), Paragraph( '''For details about pairing the smart card reader with the Android device, refer to the baiMobile specification: <a href="http://www.biometricassociates.com/downloads/user-guides/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf" color="blue">http://www.biometricassociates.com/downloads/user-guides/make-the-url-even-longer/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf</a>.''', normal), Paragraph(TEXTS[1], normal), ]) story.append(OL) story.append( Paragraph( "Same as above with a simple paragraph for the long word", normal)) OL = ListFlowable([ Paragraph(TEXTS[1], normal), Paragraph( '''For details about pairing the smart card reader with the Android device, refer to the baiMobile specification: http://www.biometricassociates.com/downloads/user-guides/make-the-url-even-longer/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf.''', normal), Paragraph(TEXTS[1], normal), ]) story.append(OL) story.append( Paragraph( "Same as above with a simple unicode paragraph for the long word", normal)) OL = ListFlowable([ Paragraph(TEXTS[1], normal), Paragraph( u'''For details about pairing the smart card reader with the Android device, refer to the baiMobile specification: http://www.biometricassociates.com/downloads/user-guides/make-the-url-even-longer/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf.''', normal), Paragraph(TEXTS[1], normal), ]) story.append(OL) story.append( ListFlowable( [ Paragraph("Level 0.1", normal), Paragraph("Level 0.2", normal), ListFlowable([ Paragraph("Level 1.1", normal), Paragraph("Level 1.1", normal), ListFlowable([ Paragraph("Level 2.1", normal), Paragraph("Level 2.1", normal), Paragraph("Level 2.3", normal), ], ), Paragraph("Level 1.4", normal), ], ), Paragraph("Level 0.4", normal), ], bulletType='1', start='10', ), ) story.append(PageBreak()) story.append(Paragraph("DDIndenter", style=normal)) story.append(Paragraph("Coffee", style=bold)) story.append( DDIndenter(Paragraph("Black hot drink", style=normal), leftIndent=36)) story.append(Paragraph("Milk", style=bold)) story.append( DDIndenter(Paragraph("White cold drink", style=normal), leftIndent=36)) story.append(Paragraph("Whiskey", style=bold)) story.append( DDIndenter(Paragraph("A nice alcoholic drink", style=normal), leftIndent=36)) story.append(PageBreak()) story.append(Paragraph("MultiCol", style=normal)) RT = 'STARTUP COMPUTERS BLAH BUZZWORD STARTREK PRINTING PYTHON CHOMSKY CHOMSKY'.split( ) for i in xrange(5): topic = RT[randint(0, len(RT) - 1)] np = randint(2, 6) story.append( MultiCol( [[Paragraph('Column %d' % (i + 1, ), style=bold)], [], [ Paragraph(xmlEscape( randomtext.randomText(topic, randint(1, 7))), style=normal) for j in xrange(np) ]], widths=['20%', 3, '80%'], )) story.append(PageBreak()) story.append(Paragraph("MultiCol 2", style=normal)) for i in xrange(5): topic = RT[randint(0, len(RT) - 1)] np = randint(2, 6) story.append( MultiCol( [([Paragraph('Column %d' % (i + 1, ), style=bold)] + [ Paragraph(xmlEscape( randomtext.randomText(topic, randint(1, 7))), style=normal) for j in xrange(np) ]), [], [ Paragraph(xmlEscape( randomtext.randomText(topic, randint(1, 7))), style=normal) for j in xrange(np) ]], widths=['50%', 5, '50%'], )) doc.build(story)
def draw(self): colorNamePairs = self.colorNamePairs autoCP = isAuto(colorNamePairs) if autoCP: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) swatchMarker = None autoCP = Auto(obj=chart) n = chart._seriesCount chartTexts = self._getTexts(colorNamePairs) else: swatchMarker = getattr(self,'swatchMarker',None) if isAuto(swatchMarker): chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)) swatchMarker = Auto(obj=chart) n = len(colorNamePairs) dx = self.dx dy = self.dy alignment = self.alignment columnMaximum = self.columnMaximum deltax = self.deltax deltay = self.deltay dxTextSpace = self.dxTextSpace fontName = self.fontName fontSize = self.fontSize fillColor = self.fillColor strokeWidth = self.strokeWidth strokeColor = self.strokeColor subCols = self.subCols leading = fontSize*1.2 yGap = self.yGap if not deltay: deltay = max(dy,leading)+self.autoYPadding ba = self.boxAnchor maxWidth = self._calculateMaxBoundaries(colorNamePairs) nCols = int((n+columnMaximum-1)/(columnMaximum*1.0)) xW = dx+dxTextSpace+self.autoXPadding variColumn = self.variColumn if variColumn: width = sum([m[-1] for m in maxWidth])+xW*nCols else: deltax = max(maxWidth[-1]+xW,deltax) width = nCols*deltax maxWidth = nCols*[maxWidth] thisx = self.x thisy = self.y - self.dy if ba not in ('ne','n','nw','autoy'): height = self._calcHeight() if ba in ('e','c','w'): thisy += height/2. else: thisy += height if ba not in ('nw','w','sw','autox'): if ba in ('n','c','s'): thisx -= width/2 else: thisx -= width upperlefty = thisy g = Group() ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize # normalize lim = columnMaximum - 1 callout = getattr(self,'callout',None) scallout = getattr(self,'swatchCallout',None) dividerLines = self.dividerLines if dividerLines: dividerWidth = self.dividerWidth dividerColor = self.dividerColor dividerDashArray = self.dividerDashArray dividerOffsX = self.dividerOffsX dividerOffsY = self.dividerOffsY for i in xrange(n): if autoCP: col = autoCP col.index = i name = chartTexts[i] else: col, name = colorNamePairs[i] if isAuto(swatchMarker): col = swatchMarker col.index = i if isAuto(name): name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i) T = _getLines(name) S = [] aS = S.append j = int(i/(columnMaximum*1.0)) jOffs = maxWidth[j] # thisy+dy/2 = y+leading/2 y = y0 = thisy+(dy-ascent)*0.5 if callout: callout(self,g,thisx,y,(col,name)) if alignment == "left": x = thisx xn = thisx+jOffs[-1]+dxTextSpace elif alignment == "right": x = thisx+dx+dxTextSpace xn = thisx else: raise ValueError("bad alignment") if not isSeq(name): T = [T] yd = y for k,lines in enumerate(T): y = y0 kk = k*2 x1 = x+jOffs[kk] x2 = x+jOffs[kk+1] sc = subCols[k,i] anchor = sc.align scdx = sc.dx scdy = sc.dy fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) fC = getattr(sc,'fillColor',fillColor) fL = getattr(sc,'leading',1.2*fontSize) if fN==fontName: fA = (ascent*fS)/fontSize else: fA = getFont(fontName).face.ascent/1000. if fA==0: fA=0.718 fA *= fS if anchor=='left': anchor = 'start' xoffs = x1 elif anchor=='right': anchor = 'end' xoffs = x2 elif anchor=='numeric': xoffs = x2 else: anchor = 'middle' xoffs = 0.5*(x1+x2) for t in lines: aS(String(xoffs+scdx,y+scdy,t,fontName=fN,fontSize=fS,fillColor=fC, textAnchor = anchor)) y -= fL yd = min(yd,y) y += fL for iy, a in ((y-max(fL-fA,0),'underlines'),(y+fA,'overlines')): il = getattr(sc,a,None) if il: if not isinstance(il,(tuple,list)): il = (il,) for l in il: l = copy.copy(l) l.y1 += iy l.y2 += iy l.x1 += x1 l.x2 += x2 aS(l) x = xn y = yd leadingMove = 2*y0-y-thisy if dividerLines: xd = thisx+dx+dxTextSpace+jOffs[-1]+dividerOffsX[1] yd = thisy+dy*0.5+dividerOffsY if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum): g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)): yd -= max(deltay,leadingMove)+yGap g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) # Make a 'normal' color swatch... swatchX = x + getattr(self,'swdx',0) swatchY = thisy + getattr(self,'swdy',0) if isAuto(col): chart = getattr(col,'chart',getattr(col,'obj',None)) c = chart.makeSwatchSample(getattr(col,'index',i),swatchX,swatchY,dx,dy) elif isinstance(col, colors.Color): if isSymbol(swatchMarker): c = uSymbol2Symbol(swatchMarker,swatchX+dx/2.,swatchY+dy/2.,col) else: c = self._defaultSwatch(swatchX,swatchY,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor) elif col is not None: try: c = copy.deepcopy(col) c.x = swatchX c.y = swatchY c.width = dx c.height = dy except: c = None else: c = None if c: g.add(c) if scallout: scallout(self,g,thisx,y0,i,(col,name),c) for s in S: g.add(s) if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)): if alignment == "left": xt = thisx else: xt = thisx+dx+dxTextSpace yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap) self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1]+dx+dxTextSpace) if i%columnMaximum==lim: if variColumn: thisx += jOffs[-1]+xW else: thisx = thisx+deltax thisy = upperlefty else: thisy = thisy-max(deltay,leadingMove)-yGap return g
def testBidi(self): fontName = getAFont() # create styles based on the registered font stySTD = ParagraphStyle('STD', fontName = fontName) styRJ = ParagraphStyle('RJ', parent=stySTD, alignment=TA_RIGHT) styLTR = ParagraphStyle('LTR', parent=stySTD, wordWrap='LTR') styRTL = ParagraphStyle('RTL', parent = stySTD, alignment = TA_RIGHT, wordWrap = 'RTL', spaceAfter = 12) # strings for testing Normal & LTR styles ltrStrings = [# English followed by Arabic. b'English followed by \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a.', # English with Arabic in the middle b'English with \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a in the middle.', # English symbols (!@#$%^&*) Arabic b'English symbols (!@#$%^&*) \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a.', # ((testing integers in LTR)) b'123 LTR 123 Integers 123.', # ((testing decimals in LTR)) b'456.78 LTR 456.78 Decimals 456.78.', # Long English text with RTL script in the middle, splitting over multiple lines b'Long \xd8\xb7\xd9\x88\xd9\x8a\xd9\x84 English text' b' \xd9\x86\xd8\xb5 \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a with RTL script' b' \xd9\x83\xd8\xaa\xd8\xa7\xd8\xa8\xd8\xa9 \xd9\x85\xd9\x86' b' \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86 \xd8\xa5\xd9\x84\xd9\x89' b' \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1 in the middle,' b' \xd9\x81\xd9\x8a \xd8\xa7\xd9\x84\xd9\x88\xd8\xb3\xd8\xb7\xd8\x8c' b' splitting \xd9\x85\xd9\x82\xd8\xb3\xd9\x85 over \xd8\xb9\xd9\x84\xd9\x89' b' multiple lines \xd8\xb9\xd8\xaf\xd8\xa9 \xd8\xb3\xd8\xb7\xd9\x88\xd8\xb1.', ] # strings for testing RTL rtlStrings = [# Arabic followed by English b'\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a \xd9\x85\xd8\xaa\xd8\xa8\xd9\x88\xd8\xb9' b' \xd8\xa8\xd9\x80 English.', # Arabic with English in the middle b'\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a \xd9\x85\xd8\xb9 English \xd9\x81\xd9\x8a' b' \xd8\xa7\xd9\x84\xd9\x85\xd9\x86\xd8\xaa\xd8\xb5\xd9\x81.', # Arabic symbols (!@##$%^&*) English b'\xd8\xb1\xd9\x85\xd9\x88\xd8\xb2 \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9' b' (!@#$%^&*) English.', # 123 from right to left 123 integer numbers 123. ((testing integers in RTL)) b'123 \xd9\x85\xd9\x86 \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86' b' \xd8\xa5\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1' b' 123 \xd8\xa3\xd8\xb1\xd9\x82\xd8\xa7\xd9\x85' b' \xd8\xb5\xd8\xad\xd9\x8a\xd8\xad\xd8\xa9 123.', # 456.78 from right to left 456.78 decimal numbers 456.78. ((testing decimals in RTL)) b'456.78 \xd9\x85\xd9\x86 \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86' b' \xd8\xa5\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1' b' 456.78 \xd8\xa3\xd8\xb1\xd9\x82\xd8\xa7\xd9\x85' b' \xd8\xb9\xd8\xb4\xd8\xb1\xd9\x8a\xd8\xa9 456.78.', # Long Arabic text with LTR text in the middle, splitting over multiple lines b'\xd9\x86\xd8\xb5 \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a \xd8\xb7\xd9\x88\xd9\x8a\xd9\x84' b' Long Arabic text \xd9\x85\xd8\xb9 with \xd9\x83\xd8\xaa\xd8\xa7\xd8\xa8\xd8\xa9' b' \xd9\x85\xd9\x86 \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1' b' \xd8\xa5\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86' b' LTR script \xd9\x81\xd9\x8a \xd8\xa7\xd9\x84\xd9\x88\xd8\xb3\xd8\xb7\xd8\x8c' b' in the middle, \xd9\x85\xd9\x82\xd8\xb3\xd9\x85 splitted' b' \xd8\xb9\xd9\x84\xd9\x89 over \xd8\xb9\xd8\xaf\xd8\xa9' b' \xd8\xb3\xd8\xb7\xd9\x88\xd8\xb1 multiple lines.' ] assert len(ltrStrings) == len(rtlStrings) n = len(ltrStrings) # create a store to be printed story = [] story.append(Paragraph("<b><i>Following pairs of left justified texts have style.wordWrap=None & 'LTR'.</i></b><br/>",stySTD)) # write every LTR string and its corresponding RTL string to be matched. for i in xrange(n): story.append(Paragraph(ltrStrings[i], stySTD)) story.append(Paragraph(ltrStrings[i], styLTR)) story.append(Paragraph("<br/><b><i>Following pairs of right justfied texts have style.wordWrap=None & 'RTL'.</i></b><br/>",stySTD)) for i in xrange(n): story.append(Paragraph(rtlStrings[i], styRJ)) story.append(Paragraph(rtlStrings[i], styRTL)) story.append(Paragraph("<b><i><br/>Following texts have style.wordWrap='RTL'</i></b>",stySTD)) # a few additional scripts for testing. story.append( Paragraph(b'\xd9\x87\xd8\xb0\xd9\x87 \xd9\x81\xd9\x82\xd8\xb1\xd8\xa9' b' \xd8\xb9\xd8\xa7\xd8\xaf\xd9\x8a\xd8\xa9. ', styRTL)) story.append( Paragraph(b'\xd9\x87\xd8\xb0\xd9\x87 \xd8\xa7\xd9\x84\xd9\x81\xd9\x82\xd8\xb1\xd8\xa9' b' \xd9\x84\xd8\xaf\xd9\x8a\xd9\x87\xd8\xa7 12' b' \xd9\x86\xd9\x82\xd8\xb7\xd8\xa9 \xd9\x82\xd8\xa8\xd9\x84\xd9\x87\xd8\xa7' b' \xd9\x88\xd8\xa8\xd8\xb9\xd8\xaf\xd9\x87\xd8\xa7. ', styRTL)) story.append( Paragraph(b'<para spacebefore="12" spaceafter="12">' b'\xd9\x87\xd8\xb0\xd9\x87 \xd8\xa7\xd9\x84\xd9\x81\xd9\x82\xd8\xb1\xd8\xa9' b' \xd9\x84\xd8\xaf\xd9\x8a\xd9\x87\xd8\xa7 12 \xd9\x86\xd9\x82\xd8\xb7\xd8\xa9' b' \xd9\x82\xd8\xa8\xd9\x84\xd9\x87\xd8\xa7' b' \xd9\x88\xd8\xa8\xd8\xb9\xd8\xaf\xd9\x87\xd8\xa7\xd8\x8c' b' \xd9\x85\xd8\xad\xd8\xaf\xd8\xaf\xd8\xa9 \xd8\xa8\xd9\x80 XML.' b' \xd8\xa5\xd9\x86\xd9\x87\xd8\xa7 \xd8\xaa\xd8\xb9\xd9\x85\xd9\x84' b' \xd8\xa3\xd9\x8a\xd8\xb6\xd8\xa7! \xd9\x80.' b'</para>', styRTL)) # TODO: add more RTL scripts to the test (Farsi, Hebrew, etc.) template = SimpleDocTemplate(outputfile('test_paragraphs_bidi.pdf')) template.build(story)