class TestResult(object): def __init__(self, name, url, group, deprecates, text, check_type, result, output_extra, attachments=[]): self.name = name self.url = url self.group = group self.deprecates = deprecates self.text = re.sub("\s+", " ", text) if text else '' self.type = check_type self.result = result self.output_extra = output_extra self.attachments = attachments if self.output_extra: self.output_extra = re.sub("\s+", " ", self.output_extra) self.wrapper = TextWrapper(width=78, subsequent_indent=" " * 5, break_long_words=False, ) def get_text(self): strbuf = StringIO.StringIO() main_lines = self.wrapper.wrap("%s: %s %s" % (TEST_STATES[self.result], self.type, self.text)) strbuf.write("%s" % '\n'.join(main_lines)) if self.output_extra and self.output_extra != "": strbuf.write("\n") extra_lines = self.wrapper.wrap(" Note: %s" % self.output_extra) strbuf.write('\n'.join(extra_lines)) return strbuf.getvalue()
def dict_str(self): """Build a human-readable definition for this word, including data for each synset""" tw = TextWrapper(width=self.LINE_WIDTH_MAX, initial_indent=(self.prefix_fmtf_line_first % self.category_map_rev[self.category]), subsequent_indent=(self.prefix_fmtn_line_first % (len(self.category_map_rev[self.category]), ''))) lines = (tw.wrap(self.synsets[0].synset_get().dict_str())) i = 2 prefix_fmtn_line_nonfirst = self.prefix_fmtn_line_nonfirst pfln_len = 0 for ss_wrap in self.synsets[1:]: # adjust indenting based on index-number with pfln_len_new = len('%d' % (i,)) if (pfln_len_new > pfln_len): pfln_len = pfln_len_new pfln_str = (self.prefix_fmtn_line_nonfirst % (pfln_len, '')) # format data for this synset synset = ss_wrap.synset_get() tw = TextWrapper(width=self.LINE_WIDTH_MAX, initial_indent=(self.prefix_fmtf_line_nonfirst % i), subsequent_indent=pfln_str) lines.extend(tw.wrap(synset.dict_str())) i += 1 return self.linesep.join(lines)
class TestResult(object): nowrap = ["CheckRpmLint", "CheckSourceMD5"] def __init__(self, name, url, group, deprecates, text, check_type, result, output_extra): self.name = name self.url = url self.group = group self.deprecates = deprecates self.text = re.sub("\s+", " ", text) self.type = check_type self.result = result self.output_extra = output_extra if self.output_extra and self.name not in TestResult.nowrap: self.output_extra = re.sub("\s+", " ", self.output_extra) self.wrapper = TextWrapper(width=78, subsequent_indent=" " * 5, break_long_words=False, ) def get_text(self): strbuf = StringIO.StringIO() main_lines = self.wrapper.wrap("%s: %s %s" % (TEST_STATES[self.result], self.type, self.text)) strbuf.write("%s" % '\n'.join(main_lines)) if self.output_extra and self.output_extra != "": strbuf.write("\n") if self.name in TestResult.nowrap: strbuf.write(self.output_extra) else: extra_lines = self.wrapper.wrap(" Note: %s" % self.output_extra) strbuf.write('\n'.join(extra_lines)) return strbuf.getvalue()
def create_verification_message(userInfo, siteInfo, toAddr, fromAddr, verificationId): container = MIMEMultipart('alternative') subject = u'Verify your email address on %s' % siteInfo.name container['Subject'] = str(Header(subject.encode(utf8), utf8)) container['From'] = str(fromAddr) container['To'] = str(toAddr) wrapper = TextWrapper(width=72) b = 'We received a request to add the email address <%s> '\ 'to your profile on %s. To verify that you control this '\ 'email address, please click the following link.' % \ (toAddr, siteInfo.name) body = '\n'.join(wrapper.wrap(b)) u = '%s/r/verify/%s' % (siteInfo.url, verificationId) d = { 'siteName': siteInfo.name, 'siteUrl': siteInfo.url, 'body': body, 'verificationUrl': u } t = u'''Hi there! %(body)s %(verificationUrl)s -- %(siteName)s %(siteUrl)s ''' % d text = MIMEText(t.strip().encode(utf8), 'plain', utf8) container.attach(text) hb = 'We received a request to add the email address '\ '<a href="mailto:%s">%s</a> '\ 'to your profile on %s. To verify that you control this '\ 'email address, please click the following link.' % \ (toAddr, toAddr, siteInfo.name) hbody = '\n'.join(wrapper.wrap(hb)) d['hbody'] = hbody h = u'''<p><strong>Hi there!</strong></p> <p>%(hbody)s</p> <pre> <a href="%(verificationUrl)s">%(verificationUrl)s</a> </pre> <hr/> <p><a href="%(siteUrl)s">%(siteName)s</a></p> ''' % d html = MIMEText(h.encode(utf8), 'html', utf8) container.attach(html) retval = container.as_string() assert retval assert type(retval) == str return retval
class TestResult(object): ''' The printable outcome of a test, stored in check.result. ''' TEST_STATES = { 'pending': '[ ]', 'pass': '******', 'fail': '[!]', 'na': '[-]'} def __init__(self, check, result, output_extra, attachments=None): self.check = check self.text = re.sub(r"\s+", " ", check.text) if check.text else '' self.result = result self._leader = self.TEST_STATES[result] + ': ' self.output_extra = output_extra self.attachments = attachments if attachments else [] if self.output_extra: self.output_extra = re.sub(r"\s+", " ", self.output_extra) self.set_indent(5) url = property(lambda self: self.check.url) name = property(lambda self: self.check.name) type = property(lambda self: self.check.type) group = property(lambda self: self.check.group) deprecates = property(lambda self: self.check.deprecates) is_failed = property(lambda self: self.check.is_failed) state = property(lambda self: self.result) def set_indent(self, indent): ''' Set indentation level for get_text (int, defaults to 5). ''' # pylint: disable=W0201 self.wrapper = TextWrapper(width = 78, subsequent_indent = " " * indent, break_long_words = False, ) def set_leader(self, leader): ''' Set the leading string, defaults to [!], [ ], [-], etc. ''' self._leader = leader def get_text(self): ''' Return printable representation of test. ''' strbuf = StringIO.StringIO() main_lines = self.wrapper.wrap(self._leader + self.text) strbuf.write('\n'.join(main_lines)) if self.output_extra and self.output_extra != "": strbuf.write("\n") extra_lines = self.wrapper.wrap( self.wrapper.subsequent_indent + "Note: " + self.output_extra) strbuf.write('\n'.join(extra_lines)) if self.is_failed: see = self.wrapper.wrap( self.wrapper.subsequent_indent + "See: " + self.url) strbuf.write("\n" + "\n".join(see)) return strbuf.getvalue() def __str__(self): self.get_text()
def dict_str(self): tw = TextWrapper(width=self.LINE_WIDTH_MAX, initial_indent=(self.prefix_fmtf_line_first % self.category_map_rev[self.category]), subsequent_indent=self.prefix_fmtn_line_first) lines = (tw.wrap(self.synsets[0].dict_str())) i = 2 for synset in self.synsets[1:]: tw = TextWrapper(width=self.LINE_WIDTH_MAX, initial_indent=(self.prefix_fmtf_line_nonfirst % i), subsequent_indent=self.prefix_fmtn_line_nonfirst) lines.extend(tw.wrap(synset.dict_str())) i += 1 return self.linesep.join(lines)
def text(self, text, offset=None, horiz=None, vert=None, *, angle=None, font=None, colour=None, width=None): attrs = dict() style = list() transform = list() if vert is not None: baselines = { self.CENTRE: "central", self.TOP: "text-before-edge", self.BOTTOM: "text-after-edge", } style.append(("dominant-baseline", baselines[vert])) if horiz is not None: anchors = { self.CENTRE: "middle", self.LEFT: "start", self.RIGHT: "end", } style.append(("text-anchor", anchors[horiz])) transform.extend(self._offset(offset)) if angle is not None: transform.append("rotate({})".format(angle * self.flip[1])) if font is not None: attrs["class"] = font attrs.update(self._colour(colour)) with self.element("text", attrs, style=style, transform=transform): if width is None: if isinstance(text, str): self.xml.characters(text) else: for seg in text: attrs = dict() if seg.get("overline"): attrs["text-decoration"] = "overline" self.tree(("tspan", attrs, (seg["text"],))) return # Very hacky approximation of the size of each character # as one en wide width /= self.textsize / 2 wrapper = TextWrapper(width=width, replace_whitespace=False) hardlines = text.splitlines(keepends=True) if not hardlines: hardlines.append("") line = 0 for hardline in hardlines: wrapped = wrapper.wrap(hardline) if not wrapped: # Caused by empty string wrapped.append("") for softline in wrapped: lineattrs = { "x": "0", "y": "{}em".format(line / 0.875), "xml:space": "preserve", } self.tree(("tspan", lineattrs, (softline,))) line += 1
def format_search_result(number, result): term_width = terminal_size()[0] if term_width > 8: term_width = term_width - 8 wrapper = TextWrapper(initial_indent=" ", subsequent_indent=" ", width=term_width) heading = "%s) %s " % (number, result['name']) if 'categories' in result and result['categories']: heading += "[%s] " % (", ".join(result['categories']),) if 'authors' in result and result['authors']: heading += "(author: %s) " % (", ".join(result['authors']),) right = "" if 'last_updated' in result: right += " Updated %s" % (result['last_updated']) if 'stage' in result: right += " [%s]" % (result['stage'],) heading += right.rjust(term_width - len(heading)) lines = [heading, ''] if 'summary' in result and result['summary']: lines += wrapper.wrap(result['summary']) lines.append('') return lines
def info(cls, _str=True): if not _str: return PCFGConfig.argNames # Auto text wrapper to output the doc. tw = TextWrapper() tw.initial_indent = " " tw.subsequent_indent = " " retVal = "General Configuration: \n" for argName in PCFGConfig.argNames: arg = str(argName["arg"]) argreq = str(argName["req"]) argtype = str(argName["type"].__name__) argdef = str(argName["def"]) argdoc = str(argName["doc"]) argex = str(argName["ex"]) doclines = tw.wrap(argdoc) aType = "optional" if argreq: aType = "required" retVal += " %s (%s, %s):\n" % (arg, argtype, aType) retVal += " Defaults to %s\n" % (argdef) for docline in doclines: retVal += "%s\n" % docline retVal += " Example: %s\n" % argex retVal += "\n" return retVal
def printHeader(s, level=1, length=70, prefix='# <Menotexport>:'): from textwrap import TextWrapper decs={1: '=', 2: '-', 3: '.'} indents={1: 0, 2: 4, 3: 8} dec=decs[level] ind=indents[level] indstr=' '*int(ind) wrapper=TextWrapper() wrapper.width=length-ind wrapper.initial_indent=indstr wrapper.subsequent_indent=indstr #-------------Get delimiter line------------- hline='%s%s' %(' '*int(ind),dec*int(length-ind)) #--------------------Wrap texts-------------------- strings=wrapper.wrap('%s %s' %(prefix,s)) #----------------------Print---------------------- try: print('\n'+hline) except: print('\n'+hline.encode('ascii','replace')) for ss in strings: try: print(ss) except: print(ss.encode('ascii','replace')) #print(hline) return
def wrap(payload): indent = ' ' tw = TextWrapper( width=70, initial_indent=indent, subsequent_indent=indent) return u'\n'.join(tw.wrap(payload))
def courses(args, store): if args.subject is None: err('--subject is required') else: if args.chatty: print('Subject: %s\n' % unicode(args.subject)) courses = store.get_courses( term=args.term, subject=args.subject, ) if courses is None: not_available() else: pad = 2 wrapper = TextWrapper( initial_indent=' ' * (4 + pad), subsequent_indent=' ' * (4 + pad), ) for course in courses: print((' ' * pad).join(( course['number'], course['name'], ))) print('') d = course['description'] if d is not None: for line in wrapper.wrap(d): print(line) print('')
def sections_by_subject(args, store): courses = store.get_courses( term=args.term, subject=args.subject, ) pad = 2 wrapper = TextWrapper( initial_indent=' ' * pad, subsequent_indent=' ' * (4 + pad), ) for course in courses: course = Course(args.subject, course['number']) sections = store.get_sections( course=course, term=args.term, ) if len(sections) != 0: print(course.get_number() + '\n'.join( wrapper.wrap(' '.join([ section['name'] for section in sections ])) )) print('')
def wrap_for_make(items): line = join(sorted(items)) wrapper = TextWrapper() wrapper.width = 60 wrapper.break_on_hyphens = False wrapper.subsequent_indent = '\t' * 2 return ' \\\n'.join(wrapper.wrap(line))
def _serialize_string(cls, value, level): length = len(value) if length == 0: return "''" elif length <= 5 and value.lower() in cls.requires_quotes: return "'%s'" % value indent = cls.indent * level if '\n' in value: lines = ['|'] for line in value.split('\n'): if line: lines.append(indent + line) else: lines.append('') return lines elif length + len(indent) <= cls.line_width: if cls._requires_escaping(value): return "'%s'" % value.replace("'", "''") else: return value else: if cls._requires_escaping(value): value = "'%s'" % value.replace("'", "''") wrapper = TextWrapper(width=cls.line_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, replace_whitespace=False, drop_whitespace=False) lines = [] for line in value.splitlines(): lines.extend(wrapper.wrap(line)) return lines
def report(trans, html=False): """Returns a summary report of all of the transactions.""" invs = inventories(trans) rankings = [] for player, inv in invs.items(): rankings.append((player, inv['cones'], inv['magic'])) rankings.sort(key=lambda x: x[1], reverse=True) listings = [] tw = TextWrapper(width=30) mctemp = '{1}x {0} cone{2}' for player, cones, magic in rankings: s = ', '.join([mctemp.format(key, value, '' if value == 1 else 's') \ for key, value in sorted(magic.items()) if value > 0]) s = '\n'.join(tw.wrap(s)) listings.append((player, cones // CONES_PER_TREE or '', (cones // CONES_PER_SAPLING) % (CONES_PER_TREE // CONES_PER_SAPLING) or \ ('' if cones // CONES_PER_TREE == 0 else 0), cones % CONES_PER_SAPLING, s, )) tab = PrettyTable(['Player', 'Trees', 'Saplings', 'Cones', 'Magic Cones']) for listing in listings: tab.add_row(listing) rep = tab.get_html_string(format=True) if html else tab.get_string() return rep
def print_error(fname, line_number, err_msg): header = "Error in file {0}, line {1}:".format(fname, line_number + 1) tw = TextWrapper(width=80, initial_indent=' '*4, subsequent_indent=' '*4) body = '\n'.join(tw.wrap(err_msg)) print(header + '\n' + body + '\n')
def test_whitespace(self): # Whitespace munging and end-of-sentence detection text = """\ This is a paragraph that already has line breaks. But some of its lines are much longer than the others, so it needs to be wrapped. Some lines are \ttabbed too. What a mess! """ expect = [ "This is a paragraph that already has line", "breaks. But some of its lines are much", "longer than the others, so it needs to be", "wrapped. Some lines are tabbed too. What a", "mess!", ] wrapper = TextWrapper(45, fix_sentence_endings=True) result = wrapper.wrap(text) self.check(result, expect) result = wrapper.fill(text) self.check(result, "\n".join(expect))
def quote_text_as_email(text, width=80): """Quote the text as if it is an email response. Uses '> ' as a line prefix, and breaks long lines. Trailing whitespace is stripped. """ # Empty text begets empty text. if text is None: return '' text = text.rstrip() if not text: return '' prefix = '> ' # The TextWrapper's handling of code is somewhat suspect. wrapper = TextWrapper( initial_indent=prefix, subsequent_indent=prefix, width=width, replace_whitespace=False) result = [] # Break the string into lines, and use the TextWrapper to wrap the # individual lines. for line in text.rstrip().split('\n'): # TextWrapper won't do an indent of an empty string. if line.strip() == '': result.append(prefix) else: result.extend(wrapper.wrap(line)) return '\n'.join(result)
def _stream_formatter(self, record): """The formatter for standard output.""" if record.levelno < logging.DEBUG: print(record.levelname, end='') elif(record.levelno < logging.INFO): colourPrint(record.levelname, 'green', end='') elif(record.levelno < IMPORTANT): colourPrint(record.levelname, 'magenta', end='') elif(record.levelno < logging.WARNING): colourPrint(record.levelname, 'lightblue', end='') elif(record.levelno < logging.ERROR): colourPrint(record.levelname, 'brown', end='') else: colourPrint(record.levelname, 'red', end='') if record.levelno == logging.WARN: message = '{0}'.format(record.msg[record.msg.find(':')+2:]) else: message = '{0}'.format(record.msg) if len(message) > self.wrapperLength: tw = TextWrapper() tw.width = self.wrapperLength tw.subsequent_indent = ' ' * (len(record.levelname)+2) tw.break_on_hyphens = False message = '\n'.join(tw.wrap(message)) print(': ' + message)
def msg(text, sep=' ', *args, **kwargs): ''' A convenience to neatly format message strings, such as error messages. ''' text_wrapper = TextWrapper(*args, **kwargs) return sep.join(text_wrapper.wrap(text.strip()))
class LongWordTestCase (BaseTestCase): def setUp(self): self.wrapper = TextWrapper() self.text = '''\ Did you say "supercalifragilisticexpialidocious?" How *do* you spell that odd word, anyways? ''' def test_break_long(self): # Wrap text with long words and lots of punctuation self.check_wrap(self.text, 30, ['Did you say "supercalifragilis', 'ticexpialidocious?" How *do*', 'you spell that odd word,', 'anyways?']) self.check_wrap(self.text, 50, ['Did you say "supercalifragilisticexpialidocious?"', 'How *do* you spell that odd word, anyways?']) # SF bug 797650. Prevent an infinite loop by making sure that at # least one character gets split off on every pass. self.check_wrap('-'*10+'hello', 10, ['----------', ' h', ' e', ' l', ' l', ' o'], subsequent_indent = ' '*15) # bug 1146. Prevent a long word to be wrongly wrapped when the # preceding word is exactly one character shorter than the width self.check_wrap(self.text, 12, ['Did you say ', '"supercalifr', 'agilisticexp', 'ialidocious?', '" How *do*', 'you spell', 'that odd', 'word,', 'anyways?']) def test_nobreak_long(self): # Test with break_long_words disabled self.wrapper.break_long_words = 0 self.wrapper.width = 30 expect = ['Did you say', '"supercalifragilisticexpialidocious?"', 'How *do* you spell that odd', 'word, anyways?' ] result = self.wrapper.wrap(self.text) self.check(result, expect) # Same thing with kwargs passed to standalone wrap() function. result = wrap(self.text, width=30, break_long_words=0) self.check(result, expect)
class MyTextWrapper: """My wrapper for the textwrap.TextWrapper class.""" def __init__(self, text, width=GLOBAL_LEN): self.text = text self.width = width self.tw = TextWrapper(width=width) def _renew(self, **kwargs): self.tw = TextWrapper(**kwargs) def _fill(self, word_list): return "\n".join(word_list) def wrap(self, width=GLOBAL_LEN, as_string=True, shorten=False): """Return a string/list of wrapped text.""" if shorten: self.max_lines = 1 shorten_text = ' '.join(self.text.strip().split()) else: self.max_lines = None shorten_text = None if width != self.width or bool(self.max_lines) is shorten: self.width = width self._renew(**{'width': self.width, 'max_lines': self.max_lines}) text = shorten_text if shorten_text else self.text word_list = self.tw.wrap(text=text) if as_string is True: return self._fill(word_list) else: return word_list raise ValueError("as_string value error!") def shorten(self, width=GLOBAL_LEN): """Shorten the original text.""" return self.wrap(width=width, as_string=True, shorten=True) def dedent(self): """Remove leading whitespace from every line.""" return dedent(self.text) def indent(self, prefix, predicate=None, dedent=False): """Add a prefix to each line of text.""" if dedent: return indent(self.dedent(), prefix=prefix, predicate=predicate) return indent(self.text, prefix=prefix, predicate=predicate) def __repr__(self): """__repr__ of MyTextWrapper.""" self.__class__.__name__ return f"{self.__class__.__name__}('''{self.text}''')" def __str__(self): """__str__ of MyTextWrapper.""" return self.wrap()
def DisassemblyPrinter( instructions, fifoname='', width=int(ExtensionSettings.getValue('main_termal_width')), wrap=False): if (fifoname): output=fifoname else: output=sys.stdout print >>output, "=" * 16 data = gdb.execute("x/" + str(instructions) + "i $pc", False, True) if wrap: print >>output, data else: wrapper = TextWrapper() # use TextWrapper to properly deal with tab lengths in output wrapper.width = width wrapper.drop_whitespace = False for line in data.split('\n'): out = wrapper.wrap(line) if len(out) > 0: print >>output, wrapper.wrap(line)[0]
def test_fix_sentence_endings(self): wrapper = TextWrapper(60, fix_sentence_endings=True) # SF #847346: ensure that fix_sentence_endings=True does the # right thing even on input short enough that it doesn't need to # be wrapped. text = "A short line. Note the single space." expect = ["A short line. Note the single space."] self.check(wrapper.wrap(text), expect) # Test some of the hairy end cases that _fix_sentence_endings() # is supposed to handle (the easy stuff is tested in # test_whitespace() above). text = "Well, Doctor? What do you think?" expect = ["Well, Doctor? What do you think?"] self.check(wrapper.wrap(text), expect) text = "Well, Doctor?\nWhat do you think?" self.check(wrapper.wrap(text), expect) text = 'I say, chaps! Anyone for "tennis?"\nHmmph!' expect = ['I say, chaps! Anyone for "tennis?" Hmmph!'] self.check(wrapper.wrap(text), expect) wrapper.width = 20 expect = ["I say, chaps!", 'Anyone for "tennis?"', "Hmmph!"] self.check(wrapper.wrap(text), expect) text = 'And she said, "Go to hell!"\nCan you believe that?' expect = ['And she said, "Go to', 'hell!" Can you', "believe that?"] self.check(wrapper.wrap(text), expect) wrapper.width = 60 expect = ['And she said, "Go to hell!" Can you believe that?'] self.check(wrapper.wrap(text), expect)
def line_iterator (text, max_width=80): # _line_iterator """Split text in lines of max_width length and iterate over them""" wrapper = TextWrapper (width=max_width) for line in text.splitlines(): if len(line) <= max_width: yield line else: for l in wrapper.wrap (line): yield l
def wrap(text): if hasattr(wrap, 'tw'): tw = wrap.tw else: tw = TextWrapper(width=72, replace_whitespace=False) paragraphs = [p.replace('\n', ' ') for p in text.split('\n\n')] paragraphs = ['\n'.join(tw.wrap(p)) for p in paragraphs] return '\n\n'.join(paragraphs)
def load_all_configs(): """Load all GunGame configs.""" for file in Path(__file__).parent.files('*.py'): if file.namebase in ('__init__', Path(__file__).namebase): continue import_module( 'gungame.core.config.{file_name}'.format( file_name=file.namebase, ) ) for plugin_name in valid_plugins.all: plugin_type = valid_plugins.get_plugin_type(plugin_name) if not GUNGAME_PLUGINS_PATH.joinpath( plugin_type, plugin_name, 'configuration.py', ).isfile(): continue try: import_module( 'gungame.plugins.{plugin_type}.{plugin_name}.' 'configuration'.format( plugin_type=plugin_type, plugin_name=plugin_name, ) ) except Exception: warn( 'Unable to import configuration for {plugin} due to error:' '\n\n\t{error}'.format( plugin=plugin_name, error=sys.exc_info()[1] ) ) always_loaded = GUNGAME_CFG_PATH / 'gg_plugins.cfg' if not always_loaded.isfile(): strings = LangStrings('gungame/plugins') with always_loaded.open('w') as open_file: wrapper = TextWrapper( width=79, initial_indent='// ', subsequent_indent='// ', ) text = strings['Plugins:Loaded:Always'].get_string( plugins=', '.join(sorted(valid_plugins.all)) ) for line in text.splitlines(keepends=True): if line == '\n': open_file.write(line) continue for output in wrapper.wrap(line): open_file.write(output + '\n') exec_path = always_loaded.replace( always_loaded.parent.parent.parent, '', )[1:~3].replace('\\', '/') queue_command_string('exec {config}'.format(config=exec_path))
def wrapped_message(self): from textwrap import TextWrapper lines = self.record.getMessage().splitlines() new_lines = [] w = TextWrapper(width=66) # 70 - 4 for line in lines: for _line in w.wrap(line): new_lines.append(_line) return u"\n".join([u" %s" % l for l in new_lines])
def test_fix_sentence_endings(self): wrapper = TextWrapper(60, fix_sentence_endings=True) # SF #847346: ensure that fix_sentence_endings=True does the # right thing even on input short enough that it doesn't need to # be wrapped. text = "A short line. Note the single space." expect = ["A short line. Note the single space."] self.check(wrapper.wrap(text), expect) # Test some of the hairy end cases that _fix_sentence_endings() # is supposed to handle (the easy stuff is tested in # test_whitespace() above). text = "Well, Doctor? What do you think?" expect = ["Well, Doctor? What do you think?"] self.check(wrapper.wrap(text), expect) text = "Well, Doctor?\nWhat do you think?" self.check(wrapper.wrap(text), expect) text = 'I say, chaps! Anyone for "tennis?"\nHmmph!' expect = ['I say, chaps! Anyone for "tennis?" Hmmph!'] self.check(wrapper.wrap(text), expect) wrapper.width = 20 expect = ['I say, chaps!', 'Anyone for "tennis?"', 'Hmmph!'] self.check(wrapper.wrap(text), expect) text = 'And she said, "Go to hell!"\nCan you believe that?' expect = ['And she said, "Go to', 'hell!" Can you', 'believe that?'] self.check(wrapper.wrap(text), expect) wrapper.width = 60 expect = ['And she said, "Go to hell!" Can you believe that?'] self.check(wrapper.wrap(text), expect)
paragraphs = getdocumenttext(infil) pw = PDFWriter(outfilename) pw.setFont("Courier", 12) pw.setHeader("DOCXtoPDF - convert text in DOCX file to PDF") pw.setFooter("Generated by xtopdf and python-docx") wrapper = TextWrapper(width=70, drop_whitespace=False) # For Unicode handling. new_paragraphs = [] for paragraph in paragraphs: new_paragraphs.append(paragraph.encode("utf-8")) for paragraph in new_paragraphs: lines = wrapper.wrap(paragraph) for line in lines: pw.writeLine(line) pw.writeLine("") pw.savePage() pw.close() def usage(): return "Usage: python DOCXtoPDF.py infile.docx outfile.txt\n" def main(): try: # Check for correct number of command-line arguments.
def __str__(self): """ Display VM information as below: VM information: +---------------------------------------------------------------+ | Name | test_vm | +---------------------------------------------------------------+ | IP | 192.168.10.125 | +---------------------------------------------------------------+ | Guest OS Distribution | VMware Photon OS 4.0 x86_64 | +---------------------------------------------------------------+ | Hardware Version | vmx-19 | +---------------------------------------------------------------+ | VMTools Version | 11.2.5.26209 (build-17337674) | +---------------------------------------------------------------+ | CloudInit Version | 20.4.1 | +---------------------------------------------------------------+ | GUI Installed | False | +---------------------------------------------------------------+ | Config Guest Id | vmwarePhoton64Guest | +---------------------------------------------------------------+ | GuestInfo Guest Id | vmwarePhoton64Guest | +---------------------------------------------------------------+ | GuestInfo Guest Full Name | VMware Photon OS (64-bit) | +---------------------------------------------------------------+ | GuestInfo Guest Family | linuxGuest | +---------------------------------------------------------------+ | GuestInfo Detailed Data | architecture='X86' | | | bitness='64' | | | distroName='VMware Photon OS' | | | distroVersion='4.0' | | | familyName='Linux' | | | kernelVersion='5.10.61-1.ph4-esx' | | | prettyName='VMware Photon OS 4.0' | +---------------------------------------------------------------+ """ # Get VM name from testing vars file and set log dir msg = 'VM information:\n' wrap_width = 50 wrapped_vm_info = {} # Get column width head_col_width = 0 info_col_width = 0 for attr_name, attr_value in vars(self).items(): if not attr_name.startswith('__') and attr_value is not None: head_col_width = max([head_col_width, len(attr_name)]) if len(attr_value) > wrap_width: if attr_name == 'GuestInfo_Detailed_Data': wrapped_vm_info[ attr_name] = self.GuestInfo_Detailed_Data.replace( "' ", "'\n").split('\n') else: textwrap = TextWrapper(width=wrap_width) wrapped_vm_info[attr_name] = textwrap.wrap(attr_value) elif (attr_name == 'CloudInit_Version' and ('windows' in self.Config_Guest_Id.lower() or 'windows' in self.Guest_OS_Distribution.lower() or 'windows' in self.GuestInfo_Guest_Id.lower())): continue else: wrapped_vm_info[attr_name] = [attr_value] max_text_line = max( [len(line) for line in wrapped_vm_info[attr_name]]) info_col_width = max([info_col_width, max_text_line]) # Table width table_width = head_col_width + info_col_width + 5 row_border = '+{}+\n'.format(''.ljust(table_width, '-')) row_format = '| {:<} | {:<} |\n' # Table content msg += row_border for attr_name in wrapped_vm_info: head_name = attr_name.replace('_', ' ') if (len(wrapped_vm_info[attr_name]) == 1 and ('GuestInfo' in attr_name or len(wrapped_vm_info[attr_name][0]) > 0)): msg += row_format.format( head_name.ljust(head_col_width), wrapped_vm_info[attr_name][0].ljust(info_col_width)) else: msg += row_format.format( head_name.ljust(head_col_width), wrapped_vm_info[attr_name][0].ljust(info_col_width)) index = 1 while index < len(wrapped_vm_info[attr_name]): msg += row_format.format( ''.ljust(head_col_width, ' '), wrapped_vm_info[attr_name][index].ljust( info_col_width)) index += 1 msg += row_border msg += "\n" return msg
def text(self, text, offset=None, horiz=None, vert=None, *, angle=None, font=None, colour=None, width=None): attrs = dict() style = list() transform = list() if vert is not None: baselines = { self.CENTRE: "central", self.TOP: "text-before-edge", self.BOTTOM: "text-after-edge", } style.append(("dominant-baseline", baselines[vert])) if horiz is not None: anchors = { self.CENTRE: "middle", self.LEFT: "start", self.RIGHT: "end", } style.append(("text-anchor", anchors[horiz])) transform.extend(self._offset(offset)) if angle is not None: transform.append("rotate({})".format(angle * self.flip[1])) if font is not None: attrs["class"] = font attrs.update(self._colour(colour)) with self.element("text", attrs, style=style, transform=transform): if width is None: if isinstance(text, str): self.xml.characters(text) else: for seg in text: attrs = dict() if seg.get("overline"): attrs["text-decoration"] = "overline" self.tree(("tspan", attrs, (seg["text"], ))) return # Very hacky approximation of the size of each character # as one en wide width /= self.textsize / 2 wrapper = TextWrapper(width=width, replace_whitespace=False) hardlines = text.splitlines(keepends=True) if not hardlines: hardlines.append("") line = 0 for hardline in hardlines: wrapped = wrapper.wrap(hardline) if not wrapped: # Caused by empty string wrapped.append("") for softline in wrapped: lineattrs = { "x": "0", "y": "{}em".format(line / 0.875), "xml:space": "preserve", } self.tree(("tspan", lineattrs, (softline, ))) line += 1
print('\tInput ' + str(i+1) + ':') print('\t\tTransaction ID: ', fh.read(32).hex()) print('\t\tIndex: ', int.from_bytes(fh.read(4), byteorder = 'big')) len_sig = int.from_bytes(fh.read(4), byteorder = 'big') print('\t\tLength of the signature: ', len_sig) print('\t\tSignature: ', fh.read(len_sig).hex(), '\n') num_outputs = int.from_bytes(fh.read(4), byteorder = 'big') print('Number of outputs: {}\n'.format(num_outputs)) for i in range(num_outputs): print('\tOutput ' + str(i+1) + ':') print('\t\tNumber of coins: ', int.from_bytes(fh.read(8), 'big')) len_pubkey = int.from_bytes(fh.read(4), 'big') print('\t\tLength of public key: ', len_pubkey) wrapper = TextWrapper(subsequent_indent = '\t\t ') pubkey = wrapper.wrap(text = fh.read(len_pubkey).decode('utf-8')) print('\t\tPublic key: ', end = '') for line in pubkey: print(line) print('\n') fh.close()
def _jclassDoc(cls): """Generator for JClass.__doc__ property Parameters: cls (JClass): class to document. Returns: The doc string for the class. """ from textwrap import TextWrapper jclass = cls.class_ out = [] out.append("Java class '%s'" % (jclass.getName())) out.append("") sup = jclass.getSuperclass() if sup: out.append(" Extends:") out.append(" %s" % sup.getName()) out.append("") intfs = jclass.getInterfaces() if intfs: out.append(" Interfaces:") words = ", ".join([str(i.getCanonicalName()) for i in intfs]) wrapper = TextWrapper(initial_indent=' ', subsequent_indent=' ') out.extend(wrapper.wrap(words)) out.append("") ctors = jclass.getDeclaredConstructors() if ctors: exceptions = [] name = jclass.getSimpleName() ctordecl = [] for ctor in ctors: modifiers = ctor.getModifiers() if not modifiers & 1: continue params = ", ".join( [str(i.getCanonicalName()) for i in ctor.getParameterTypes()]) ctordecl.append(" * %s(%s)" % (name, params)) exceptions.extend(ctor.getExceptionTypes()) if ctordecl: out.append(" Constructors:") out.extend(ctordecl) out.append("") if exceptions: out.append(" Raises:") for exc in set(exceptions): out.append(" %s: from java" % exc.getCanonicalName()) out.append("") fields = jclass.getDeclaredFields() if fields: fielddesc = [] for field in fields: modifiers = field.getModifiers() if not modifiers & 1: continue fieldInfo = [] if modifiers & 16: fieldInfo.append("final") if modifiers & 8: fieldInfo.append("static") if field.isEnumConstant(): fieldInfo.append("enum constant") else: fieldInfo.append("field") fielddesc.append(" %s (%s): %s" % (field.getName(), field.getType().getName(), " ".join(fieldInfo))) if fielddesc: out.append(" Attributes:") out.extend(fielddesc) out.append("") return "\n".join(out)
import sys from textwrap import TextWrapper WRAPCHARS = 28 BANKSIZE = (16 << 10) - 1 print('; Autogenerated by maketable.py\n') # Breaking on hyphens makes several NKIs less funny. wrapper = TextWrapper(width=WRAPCHARS, break_on_hyphens=False) bank = 0 bank_size = 0 nki_num = 0 for nki in sys.stdin: nki = nki.replace('--', '-') lines = wrapper.wrap(nki) assert len(lines) <= 5 nki_size = sum(len(line) + 1 for line in lines) + 1 if bank_size + nki_size > BANKSIZE: bank += 1 bank_size = 0 lines = [line.replace('"', '""') for line in lines] print('.strings nki_{}, {}, ["{}"]'.format(nki_num, bank, '", "'.join(lines))) nki_num += 1 bank_size += nki_size print('\nnki_count = {}'.format(nki_num))
def main(): """Parse command line options """ usage = "usage: %(prog)s [raw-input-file [options] ]\n" \ "Program will filter and/or translate supplied raw packets.\n" parser = ArgumentParser(prog='pydyparser', usage=usage, formatter_class=RawTextHelpFormatter) tw = TextWrapper() mywrap = lambda x: "\n".join(tw.wrap(x)) tw.width = 80 - 25 quicktext = "\n".join(["\n".join(tw.wrap(_)) for _ in ( "Arg(s) will be concatenated and treated as " "a single packet and then parsed. Input should be space-delimited " "bytes. 0xff, 255, and \\xff styles are all supported. " "If using the latter, space delimiting is optional, but you must " "wrap the sequence of bytes in quotes " "(or escape the backslashes).\n\n" "Example usage:" "\n$ pydyparser -q 255 255 12 7 3 30 0 2 0 2 195" "\n$ pydyparser -q 0xFF 0xFF 0x0C 0x07 0x03 0x1E 0x00 0x02 0x00 0x02 0xC3" "\n$ pydyparser -q \"\\xFF\\xFF\\x0C\\x07\\x03\\x1E\\x00\\x02\\x00\\x02\\xC3\"" "\n$ pydyparser -q \"\\xFF \\xFF \\x0C \\x07 \\x03 \\x1E \\x00 \\x02 \\x00 \\x02 \\xC3\"" "\n\nThese all produce output:\n" " ['ID: 12', 'write data', 'GOAL_POSITION_L ', 'Val: 512', " "'GOAL_SPEED_L', 'Val: 512', 'invalid checksum c3 (actual c9)']").splitlines()]) # parser.add_argument('arglist', nargs='*', default=list(), help=mywrap("Path to a file to parse/translate, or list of bytes " "to parse/translate if using -q flag.")) parser.add_argument('-q', '--quick', action="store_true", dest="quick", default=False, help=quicktext) parser.add_argument('-s', '--servos', action="store", dest="my_f_id", default=None, help=mywrap("A single integer " "or set of comma separated integers for servo IDs to keep " "when filtering; e.g. '-s 1,2,3'.\nDefault: %(default)s")) parser.add_argument('-i', '--instructions', action="store", dest="my_f_instr", default=None, help=mywrap("A single integer " "or set of comma separated integers for instructions to keep " "when filtering; e.g. '-i 1,2,3'.\nDefault: %(default)s")) parser.add_argument('-c', '--commands', action="store", dest="my_f_cmd", default=None, help=mywrap("A single integer " "or set of comma separated integers for commands to keep " "when filtering; e.g. '-c 1,2,3'.\nDefault: %(default)s")) parser.add_argument('-o', '--output', action="store", dest="output", default="filtered_out.txt", help=mywrap("Specify " "output file for filtered list of packets. (do `-o ''` to prevent " "output creation.) Default: %(default)s")) parser.add_argument('-t', '--translate', action="store_true", dest="translate", default=False, help=mywrap("Write filtered " "packets in human-readable form.\nDefault: %(default)s")) parser.add_argument('--time', action="store_true", dest="timestamp", default=None, help=mywrap("Appends timestamps " "to end of each translated packet (if timestamps exist). " "Default: %(default)s")) parser.add_argument('-T', '--Tally', action="store", dest="my_tally_by", default=None, help=mywrap("Tally filtered " "packets by command (cmd), instruction (instr) or servo ID (id). " "E.g.: '-T id'. Default: %(default)s")) parser.add_argument('-S', '--SyncWrite', action="store_true", dest="sync_split", default=None, help=mywrap("Split up sync-write " "packets when filtering to look for contents satisfying other " "criteria. Can also be used just to create individual packets. " "Default: %(default)s")) # options = parser.parse_args() args = options.arglist if len(args) == 0: print "Command line use requires the name of a file with a packet " \ "log. (Or a string of bytes if using --quick option.)\n" \ "Use the -h option for more help." return cfg = PyDyConfigParser() cfg.read() __, __, __, __, itit = cfg.get_params() id_dict = cfg.get_id_to_device_dict() if options.timestamp is None: options.timestamp = itit do_filtering(options, args, id_dict) return
# if not titl: # words = "\n"+"\n".join(words.splitlines()[1:]) # else: # words = "\n"+titl+"\n\n"+"\n".join(words.splitlines()[1:]) #words = "\n"+"\n".join(words.splitlines()[1:]) #words = insertNewlines(words, 48) words = "".join( words.split(".")[0]) + "." #".".join(words.split(".")[:-1])+ "." # for display in Cathode tw = TextWrapper() tw.width = 30 words = "\t" + "\n\t".join(tw.wrap(words)) # Tidy up words = words.replace('“', '') words = words.replace('”', '') words = words.replace('"', '') words = words.replace('(', '') words = words.replace(')', '') words = capitalize(words) #+"\n\n"+str(args.temperature) # SCREEN OUTPUT for char in words: time.sleep(0.001) sys.stdout.write(char)
def cmd_wrap(flt_ctxt, in_obj): """Try to apply a bit smarter wrapping on lines carrying shell commands Smarter means: - standard textwrap module logic applied on comments splitting; otherwise: - do not delimit option from its argument - when line is broken vertically, append backslash for the continuation and indent subsequent lines for visual clarity - and as a side-effect: normalize whitespace occurrences Width used for rewrapping is based on three factors in precedence order: - text_width value inside the filter context (`flt_ctxt`) - 0 ~ fall-through to the value per the next item - -1 ~ apply no wrapping at all (mimicked by implying huge text_width) - positive ~ hard-limit the width (no smartness involved) - negative ~ high-limit the width, apply the inverse value only when not exceeding the value per the next item - COLUMNS environment variable, if defined and possesses integer value - hard-coded default of 72 If absolute value at this point is lower than 20, fallback to 20. """ proto, rest = head_tail(flt_ctxt.get('io_decl')) try: term = proto == 'file' and isatty(rest[0].fileno()) except AttributeError: term = False color = flt_ctxt.get('color') color = color or (term and color is not False) tw, tw_system = 0, 0 try: tw_system = int(getenv('COLUMNS')) if term else tw_system except TypeError: pass try: tw = int(flt_ctxt.get('text_width')) except TypeError: pass if tw > 0: pass elif tw < -1: tw = -tw if not tw_system or -tw < tw_system else tw_system elif tw == 0 and term: tw = tw_system else: tw = maxsize >> 1 # one order of magnitude less to avoid overflows if tw < 20: # watch out for deliberate lower limit tw = 20 if tw else 72 log.info('Text width fallback: {0}'.format(tw)) cw = TextWrapper( width=tw, subsequent_indent='# ', # wrapper for comments break_on_hyphens=False) # <-- for PY3 color_map = (dict( ((k, FancyOutput.get_color(FancyOutput.table.get('pcscmd_' + k, ''))) for k in ('comment', 'file', 'metaword', 'pcs', 'subcmd')), restore=FancyOutput.colors['restore']) if color else defaultdict(lambda: '')) ret, continuation = [], [] for line in (str_enc(l, 'utf-8') for l in (in_obj('bytestringiter', protect_safe=True))): if line.lstrip().startswith('#'): lines = cw.wrap(line) last = len(lines) - 1 ret.extend( l.join((color_map['comment'] if e == 0 else '', color_map['restore'] if e == last else '')) for e, l in enumerate(lines)) continue # rough overapproximation of what is indeed a line continuation if line.endswith('\\') and not line.endswith('\\\\'): if '#' not in line: continuation.append(line[:-1]) continue line += '\\' # XXX line = ' '.join(continuation) + line continuation = [] linecnt, rline, remains = -1, [], tw - 2 # ' \' itemgroups = cmd_args_cutter(command('bytestring', line)('separated'), color_map=color_map) itemgroups.reverse() while itemgroups: itemgroup = list(itemgroups.pop()) itemgroup.reverse() while itemgroup: curlen = 0 line = [itemgroup.pop()] curlen += len_n(line[-1]) # best match fill while itemgroup \ and remains - (curlen + 1 + len_n(itemgroup[-1])) >= 0: line.append(itemgroup.pop()) curlen += 1 + len_n(line[-1]) # compensate for ' \' tail not necessary if very last item fits if not itemgroups and len(itemgroup) == 1 \ and len_n(itemgroup[-1]) == 1: line.append(itemgroup.pop()) curlen += 1 + len_n(line[-1]) # merge previous group to the current one if it fits the length if (rline and not itemgroup and remains - (curlen + 1 + len_n(' '.join(rline))) >= 0 and (not itemgroups or not itemgroups[-1] or not itemgroups[-1][0] or not n(itemgroups[-1][0])[0] == '-' or not ismetaword(n(line[0])) or len(itemgroups) == 1 or not itemgroups[-2] or ismetaword(n(itemgroups[-2][0])))): line = rline + line rline = [] linecnt -= 1 # second pass optionally handles the terminal propagation for i in xrange(2): if rline: tail = ' \\' if rline is not line else '' rline = ' '.join(rline) if not linecnt: ret.append(rline + tail) remains -= 2 # initial indent else: ret.append(' ' + rline + tail) linecnt += 1 rline = line if itemgroups or itemgroup: break return ('bytestringiter', (bytes_enc(l, 'utf-8') for l in ret))
def output_attrib(self, k, val): ''' Output the fancy attributes, 1 at a time ''' if val is None: return aname_color = self.term.darkmagenta aval_color = self.term.bold + self.term.bright_magenta close_color = self.term.normal attrib_width = 18 if self.startx is None: self.startx = 0 attrib_plus_pad = (attrib_width + 3 + self.startx) fmtstr1 = '{}{:>%ds} {}{} {}{}\n' % attrib_width fmtstr2 = '{} {}{} {}{}\n' ts = get_terminal_size() tl = len(val) max_val_width = ts.columns - attrib_plus_pad alllines = [] repnl = '\n\n' if k == 'Summary' else '\n' val = val.replace('\n', repnl).rstrip('\n') for line in val.split('\n'): tl = len(line) lines = [] if tl < max_val_width: alllines.append(line) else: tw = TextWrapper(width=ts.columns - attrib_plus_pad, break_on_hyphens=False, break_long_words=False) for line in tw.wrap(line): alllines.append(line) totlines = len(alllines) first = True for ln in range(totlines): line = alllines[ln].strip() if first: sep = '┉' if totlines == 1 else '╭' if k == 'urls': return if k in ['Web']: line = self.term.link(line, 'Link to listing') outstr = fmtstr1.format(aname_color, k, aval_color, sep, line, close_color) first = False else: if ln + 1 == totlines: sep = '╰' else: sep = '┊' outstr = fmtstr2.format(' ' * attrib_width, aval_color, sep, line, close_color) if self.starty is not None: with self.term.location(y=self.starty, x=self.startx): sys.stdout.write(outstr) sys.stdout.flush() self.starty += 1 else: sys.stdout.write(outstr) sys.stdout.flush()
class LongWordTestCase (BaseTestCase): def setUp(self): self.wrapper = TextWrapper() self.text = '''\ Did you say "supercalifragilisticexpialidocious?" How *do* you spell that odd word, anyways? ''' def test_break_long(self): # Wrap text with long words and lots of punctuation self.check_wrap(self.text, 30, ['Did you say "supercalifragilis', 'ticexpialidocious?" How *do*', 'you spell that odd word,', 'anyways?']) self.check_wrap(self.text, 50, ['Did you say "supercalifragilisticexpialidocious?"', 'How *do* you spell that odd word, anyways?']) # SF bug 797650. Prevent an infinite loop by making sure that at # least one character gets split off on every pass. self.check_wrap('-'*10+'hello', 10, ['----------', ' h', ' e', ' l', ' l', ' o'], subsequent_indent = ' '*15) # bug 1146. Prevent a long word to be wrongly wrapped when the # preceding word is exactly one character shorter than the width self.check_wrap(self.text, 12, ['Did you say ', '"supercalifr', 'agilisticexp', 'ialidocious?', '" How *do*', 'you spell', 'that odd', 'word,', 'anyways?']) def test_nobreak_long(self): # Test with break_long_words disabled self.wrapper.break_long_words = 0 self.wrapper.width = 30 expect = ['Did you say', '"supercalifragilisticexpialidocious?"', 'How *do* you spell that odd', 'word, anyways?' ] result = self.wrapper.wrap(self.text) self.check(result, expect) # Same thing with kwargs passed to standalone wrap() function. result = wrap(self.text, width=30, break_long_words=0) self.check(result, expect) def test_max_lines_long(self): self.check_wrap(self.text, 12, ['Did you say ', '"supercalifr', 'agilisticexp', '[...]'], max_lines=4)
def email_wrapper(text): wrapper = TextWrapper() wrapper.subsequent_indent = "> " wrapper.initial_indent = "> " return "\n".join(wrapper.wrap(text))
def _jmethodGetDoc(method, cls, overloads): """Generator for _JMethod.__doc__ property Parameters: method (_JMethod): method to generate doc string for. cls (java.lang.Class): Class holding this method dispatch. overloads (java.lang.reflect.Method[]): tuple holding all the methods that are served by this method dispatch. Returns: The doc string for the method dispatch. """ jcls = _jpype.JClass(cls) if not hasattr(jcls, "__javadoc__"): jcls.__doc__ jd = getattr(jcls, "__javadoc__") if jd is not None: md = jd.methods.get(method.__name__) if md is not None: return str(md) from textwrap import TextWrapper out = [] out.append("Java method dispatch '%s' for '%s'" % (method.__name__, cls.getName())) out.append("") exceptions = [] returns = [] methods = [] classmethods = [] for ov in overloads: modifiers = ov.getModifiers() exceptions.extend(ov.getExceptionTypes()) returnName = ov.getReturnType().getCanonicalName() params = ", ".join( [str(i.getCanonicalName()) for i in ov.getParameterTypes()]) if returnName != "void": returns.append(returnName) if modifiers & 8: classmethods.append(" * %s %s(%s)" % (returnName, ov.getName(), params)) else: methods.append(" * %s %s(%s)" % (returnName, ov.getName(), params)) if classmethods: out.append(" Static Methods:") out.extend(classmethods) out.append("") if methods: out.append(" Virtual Methods:") out.extend(methods) out.append("") if exceptions: out.append(" Raises:") for exc in set(exceptions): out.append(" %s: from java" % exc.getCanonicalName()) out.append("") if returns: out.append(" Returns:") words = ", ".join([str(i) for i in set(returns)]) wrapper = TextWrapper(initial_indent=' ', subsequent_indent=' ') out.extend(wrapper.wrap(words)) out.append("") return "\n".join(out)
class ParsedTextDocument(object): def __init__(self, text_data, text_grid): if os.path.isfile(text_data): tfile = codecs.open(text_data, 'rU', 'utf-8') text_data = tfile.read() tfile.close() self._text_grid = proxy(text_grid) self._num_columns, self._max_visible_rows = text_grid._shape text_data = text_data.replace('\r\n', '\n') # if len(text_data) and text_data[-1] != u'\n': # text_data=text_data+u'\n' self._text = text_data self._children = [] self._limit_text_length = self._max_visible_rows * self._num_columns if self._limit_text_length > 0 and self._limit_text_length < len( self._text): self._text = self._text[:self._limit_text_length] self._default_parse_chunk_size = self._num_columns * ( self._max_visible_rows + 1) self._text_wrapper = TextWrapper(width=self._num_columns, drop_whitespace=False, replace_whitespace=False, expand_tabs=False) self._text_parsed_to_index = 0 self._parse(0, len(self._text)) def getDisplayedText(self): lli = min(self._max_visible_rows, self.getChildCount()) - 1 lline = self.getParsedLine(lli) return self._text[:lline._index_range[1]] def addChild(self, c): self._children.append(c) def getChildren(self): return self._children def getChildCount(self): return len(self._children) def getText(self): return self._text def getCharAtIndex(self, text_index): try: return self._text[text_index] except: print "WARNING: ParsedTextDocument.getCharAtIndex received out of bounds index: ", text_index, self.getTextLength( ) return None def getTextLength(self): return len(self._text) def deleteText(self, start_index, end_index, insertText=None): start_index = int(start_index) end_index = int(end_index) deleted_text = self._text[start_index:end_index] if insertText is None: self._text = ''.join( [self._text[:start_index], self._text[end_index:]]) else: self._text = ''.join( [self._text[:start_index], insertText, self._text[end_index:]]) self._parse(start_index) return deleted_text def insertText(self, text, start_index, end_index=None): start_index = int(start_index) if end_index is None: end_index = start_index else: end_index = int(end_index) self._text = ''.join( [self._text[:int(start_index)], text, self._text[int(end_index):]]) return self._parse(start_index) def parseTextTo(self, requested_line_index): requested_line_index = int(requested_line_index) if self.getParsedLineCount() > requested_line_index: return requested_line_index add_line_count = (requested_line_index - self.getParsedLineCount()) + 1 max_chars_to_add = add_line_count * self._num_columns start_index = self._children[-1]._index_range[0] self._parse(start_index, start_index + max_chars_to_add) if self.getParsedLineCount() >= requested_line_index: return requested_line_index return self.getParsedLineCount() - 1 def _parse(self, from_text_index, to_text_index=None): from_text_index = 0 to_text_index = self.getTextLength() line_index = None if self._children: line_index = 0 update_lines = [] if line_index is not None: update_lines = deque(self._children[:]) para_split_text = self._text[from_text_index:to_text_index].splitlines( True) if len(para_split_text) == 0: return current_index = 0 for para_text in para_split_text: current_index = self._wrapText(para_text, current_index, update_lines) if len(update_lines) > 0: self._children = self._children[:-len(update_lines)] self._text_parsed_to_index = current_index def _wrapText(self, para_text, current_index, update_lines): rewrap = False para_text_index = 0 for linestr in self._text_wrapper.wrap(para_text): if linestr[-1] != u' ' and len( self._text) > current_index + len(linestr) and self._text[ current_index + len(linestr)] == u' ': last_space = linestr.rfind(u' ') if last_space > 0: linestr = linestr[:last_space + 1] rewrap = True if len(update_lines) > 0: line = update_lines.popleft() line._text = linestr line._index_range = [ current_index, current_index + len(linestr) ] line.updateOrds(linestr) line._gl_display_list[0] = 0 else: ParsedTextLine(self, linestr, [current_index, current_index + len(linestr)]) line = self._children[-1] current_index += len(linestr) para_text_index += len(linestr) if rewrap is True: return self._wrapText(para_text[para_text_index:], current_index, update_lines) return current_index def clearCachedLineDisplayLists(self, from_char_index, to_char_index): if from_char_index < 0: from_char_index = 0 elif from_char_index >= len(self._text): from_char_index = len(self._text) - 1 if to_char_index < 0: to_char_index = 0 elif to_char_index >= len(self._text): to_char_index = len(self._text) - 1 start_line = self.getLineIndex(from_char_index) to_line = self.getLineIndex(to_char_index) for l in range(start_line, to_line + 1): self._children[l]._gl_display_list[0] = 0 def getLineInfoByIndex(self, i): c = self._children[i] return c, c._length, c._gl_display_list, c._ords def getParsedLine(self, i): return self._children[i] def getParsedLines(self): return self._children def getParsedLineCount(self): return self.getChildCount() def getTextGridCellForCharIndex(self, char_index): for line in self._children: rsi, rei = line._index_range if char_index >= rsi and char_index < rei: r = line._line_index c = char_index - rsi return c, r return None def getLineIndex(self, char_index): for line in self._children: rsi, rei = line._index_range if char_index >= rsi and char_index < rei: return line.getIndex() return None def getLineFromCharIndex(self, char_index): if char_index < 0: return None for line in self._children: rsi, rei = line._index_range if char_index >= rsi and char_index < rei: return line return None def _free(self): self._text = None self._text_wrapper = None del self._text_wrapper for c in self._children: c._free() del self._children[:] def __del__(self): if self._text is not None: self._free()
# rxnames from textwrap import TextWrapper from prettytable import PrettyTable, FRAME from pyne import rxname tw = TextWrapper(initial_indent=" ", subsequent_indent=" ", break_long_words=False) style = {"style": "margin-left:auto;margin-right:auto;"} rxtab = PrettyTable(['reaction', 'id', 'description']) rxtab.align['reaction'] = 'l' rxtab.align['id'] = 'r' rxtab.align['description'] = 'l' for name in sorted(rxname.names): rxtab.add_row(["'" + name + "'", rxname.id(name), rxname.doc(name)]) rxtab = "\n".join(tw.wrap(rxtab.get_html_string(attributes=style))) aliastab = PrettyTable(['alias', 'reaction']) aliastab.align['alias'] = 'l' aliastab.align['reaction'] = 'l' for alias, rxid in sorted(rxname.altnames.items()): aliastab.add_row(["'" + alias + "'", "'" + rxname.name(rxid) + "'"]) aliastab = "\n".join(tw.wrap(aliastab.get_html_string(attributes=style))) _rxname_rst = """**Reactions:** .. raw:: html <div> {0} </div>
class terminal(object): """ Provides a terminal-like interface to a device (or a device-like object that has :class:`mixin.capabilities` characteristics). """ def __init__(self, device, font=None, color="white", bgcolor="black", tabstop=4, line_height=None, animate=True, word_wrap=False): self._device = device self.font = font or ImageFont.load_default() self.default_fgcolor = color self.default_bgcolor = bgcolor self.animate = animate self.tabstop = tabstop self.word_wrap = word_wrap self._cw, self._ch = (0, 0) for i in range(32, 128): w, h = self.font.getsize(chr(i)) self._cw = max(w, self._cw) self._ch = max(h, self._ch) self._ch = line_height or self._ch self.width = device.width // self._cw self.height = device.height // self._ch self.size = (self.width, self.height) self.reset() self._backing_image = Image.new(self._device.mode, self._device.size, self._bgcolor) self._canvas = ImageDraw.Draw(self._backing_image) self.clear() if self.word_wrap: self.tw = TextWrapper() self.tw.width = self.width self.tw.expand_tabs = False self.tw.replace_whitespace = False self.tw.drop_whitespace = False self.tw.break_long_words = True def clear(self): """ Clears the display and resets the cursor position to ``(0, 0)``. """ self._cx, self._cy = (0, 0) self._canvas.rectangle(self._device.bounding_box, fill=self.default_bgcolor) self.flush() def println(self, text=""): """ Prints the supplied text to the device, scrolling where necessary. The text is always followed by a newline. :param text: The text to print. :type text: str """ if self.word_wrap: # find directives in complete text directives = ansi_color.find_directives(text, self) # strip ansi from text clean_text = ansi_color.strip_ansi_codes(text) # wrap clean text clean_lines = self.tw.wrap(clean_text) # print wrapped text index = 0 for line in clean_lines: line_length = len(line) y = 0 while y < line_length: method, args = directives[index] if method == self.putch: y += 1 method(*args) index += 1 self.newline() else: self.puts(text) self.newline() def puts(self, text): """ Prints the supplied text, handling special character codes for carriage return (\\r), newline (\\n), backspace (\\b) and tab (\\t). ANSI color codes are also supported. If the ``animate`` flag was set to True (default), then each character is flushed to the device, giving the effect of 1970's teletype device. :param text: The text to print. :type text: str """ for method, args in ansi_color.find_directives(text, self): method(*args) def putch(self, char): """ Prints the specific character, which must be a valid printable ASCII value in the range 32..127 only, or one of carriage return (\\r), newline (\\n), backspace (\\b) or tab (\\t). :param char: The character to print. """ if char == '\r': self.carriage_return() elif char == '\n': self.newline() elif char == '\b': self.backspace() elif char == '\t': self.tab() else: w = self.font.getsize(char)[0] if self._cx + w >= self._device.width: self.newline() self.erase() self._canvas.text((self._cx, self._cy), text=char, font=self.font, fill=self._fgcolor) self._cx += w if self.animate: self.flush() def carriage_return(self): """ Returns the cursor position to the left-hand side without advancing downwards. """ self._cx = 0 def tab(self): """ Advances the cursor position to the next (soft) tabstop. """ soft_tabs = self.tabstop - ((self._cx // self._cw) % self.tabstop) for _ in range(soft_tabs): self.putch(" ") def newline(self): """ Advances the cursor position ot the left hand side, and to the next line. If the cursor is on the lowest line, the displayed contents are scrolled, causing the top line to be lost. """ self.carriage_return() if self._cy + (2 * self._ch) >= self._device.height: # Simulate a vertical scroll copy = self._backing_image.crop( (0, self._ch, self._device.width, self._device.height)) self._backing_image.paste(copy, (0, 0)) self._canvas.rectangle( (0, copy.height, self._device.width, self._device.height), fill=self.default_bgcolor) else: self._cy += self._ch self.flush() if self.animate: sleep(0.2) def backspace(self): """ Moves the cursor one place to the left, erasing the character at the current position. Cannot move beyond column zero, nor onto the previous line. """ if self._cx + self._cw >= 0: self.erase() self._cx -= self._cw self.flush() def erase(self): """ Erase the contents of the cursor's current position without moving the cursor's position. """ bounds = (self._cx, self._cy, self._cx + self._cw, self._cy + self._ch) self._canvas.rectangle(bounds, fill=self._bgcolor) def flush(self): """ Cause the current backing store to be rendered on the nominated device. """ self._device.display(self._backing_image) def foreground_color(self, value): """ Sets the foreground color. :param value: The new color value, either string name or RGB tuple. :type value: str or tuple """ self._fgcolor = value def background_color(self, value): """ Sets the background color. :param value: The new color value, either string name or RGB tuple. :type value: str or tuple """ self._bgcolor = value def reset(self): """ Resets the foreground and background color value back to the original when initialised. """ self._fgcolor = self.default_fgcolor self._bgcolor = self.default_bgcolor def reverse_colors(self): """ Flips the foreground and background colors. """ self._bgcolor, self._fgcolor = self._fgcolor, self._bgcolor
def test(): parser = CosaArgParser() wrapper = TextWrapper(initial_indent=" - ") extra_info = [] devel = False if DEVEL_OPT in sys.argv: sys.argv = [a for a in sys.argv if a != DEVEL_OPT] devel = True extra_info.append(bold_text("\nADDITIONAL INFORMATION:")) clock_behaviors = [] for x in ClockBehaviorsFactory.get_clockbehaviors(): wrapper.subsequent_indent = " " * (len(" - \"\": " + x.get_name())) clock_behaviors.append("\n".join( wrapper.wrap("\"%s\": %s, parameters (%s)" % (x.get_name(), x.get_desc(), x.get_interface())))) extra_info.append('\nClock behaviors:\n%s' % ("\n".join(clock_behaviors))) sugars = [] for x in SyntacticSugarFactory.get_sugars(): wrapper.subsequent_indent = " " * (len(" - \"\": " + x.get_name())) sugars.append("\n".join( wrapper.wrap("\"%s\": %s, parameters (%s)" % (x.get_name(), x.get_desc(), x.get_interface())))) extra_info.append('\nSpecial operators:\n%s' % ("\n".join(sugars))) generators = [] for x in GeneratorsFactory.get_generators(): wrapper.subsequent_indent = " " * (len(" - \"\": " + x.get_name())) generators.append("\n".join( wrapper.wrap("\"%s\": %s, parameters (%s) values (%s)" % (x.get_name(), x.get_desc(), x.get_interface(), x.get_values())))) extra_info.append('\nModule generators:\n%s' % ("\n".join(generators))) modifiers = [] modifiers.append(" - \"None\": No extension") for x in ModelModifiersFactory.get_modifiers(): wrapper.subsequent_indent = " " * (len(" - \"\": " + x.get_name())) modifiers.append("\n".join( wrapper.wrap("\"%s\": %s" % (x.get_name(), x.get_desc())))) extra_info.append('\nModel modifiers:\n%s' % ("\n".join(modifiers))) parser = CosaArgParser(description=bold_text( 'CoSA: CoreIR Symbolic Analyzer\n..an SMT-based Symbolic Model Checker for Hardware Design' ), formatter_class=RawTextHelpFormatter, epilog="\n".join(extra_info)) # Main inputs # Options in the general group are options that must stay constant for all problems # in a problem file # in our architecture, the input files are compiled into a single transition system which # is then used to verify mutliple properties (problems) # thus any option regarding the encoding of said transition system must be a general option in_options = parser.add_general_group('input options') av_input_types = [" - \"%s\": %s"%(x.name, ", ".join(["*.%s"%e for e in x.extensions])) \ for x in ModelParsersFactory.get_parsers() if x.is_available()] ua_input_types = [" - \"%s\": %s"%(x.name, ", ".join(["*.%s"%e for e in x.extensions])) \ for x in ModelParsersFactory.get_parsers() if not x.is_available()] in_options.set_defaults(model_files=None) in_options.add_argument('-i', '--model_files', metavar='<model files>', type=str, required=False, help='comma separated list of input files.\nSupported types:\n%s%s'%\ ("\n".join(av_input_types), "\nNot enabled:\n%s"%("\n".join(ua_input_types)) \ if len(ua_input_types) > 0 else "")) in_options.set_defaults(problems=None) in_options.add_argument( '--problems', metavar='<problems file>', type=str, required=False, help='problems file describing the verifications to be performed.', is_config_file=True) general_encoding_options = parser.add_general_group('encoding') general_encoding_options.set_defaults(abstract_clock=False) general_encoding_options.add_argument( '--abstract-clock', dest='abstract_clock', action='store_true', help="abstracts the clock behavior. (Default is \"%s\")" % False) general_encoding_options.set_defaults(add_clock=False) general_encoding_options.add_argument( '--add-clock', dest='add_clock', action='store_true', help="adds clock behavior. (Default is \"%s\")" % False) general_encoding_options.set_defaults(cache_files=False) general_encoding_options.add_argument( '-c', '--cache-files', dest='cache_files', action='store_true', help="caches encoded files to speed-up parsing. (Default is \"%s\")" % False) general_encoding_options.set_defaults(clean_cache=False) general_encoding_options.add_argument( '--clean-cache', dest='clean_cache', action='store_true', help="deletes the stored cache. (Default is \"%s\")" % False) general_encoding_options.set_defaults(boolean=False) general_encoding_options.add_argument( '--boolean', dest='boolean', action='store_true', help= 'interprets single bits as Booleans instead of 1-bit Bitvector. (Default is \"%s\")' % False) general_encoding_options.set_defaults(run_coreir_passes=True) general_encoding_options.add_argument( '--no-run-coreir-passes', dest='run_coreir_passes', action='store_false', help='does not run CoreIR passes. (Default is \"%s\")' % True) general_encoding_options.set_defaults(model_extension=False) general_encoding_options.add_argument( '--model-extension', metavar='model_extension', type=str, nargs='?', help='select the model modifier. (Default is \"%s\")' % (False)) general_encoding_options.set_defaults(opt_circuit=False) general_encoding_options.add_argument( '--opt-circuit', action='store_true', help='Use Yosys to optimize the circuit -- can remove signals.') general_encoding_options.set_defaults(no_arrays=False) general_encoding_options.add_argument( '--no-arrays', action='store_true', help= 'For Yosys frontend, blast memories to registers instead of using arrays.\n' 'Note: This can fail -- particularly for dualport memories.') general_encoding_options.set_defaults(symbolic_init=False) general_encoding_options.add_argument( '--symbolic-init', dest='symbolic_init', action='store_true', help='removes constraints on the initial state. (Default is \"%s\")' % False) general_encoding_options.set_defaults(zero_init=False) general_encoding_options.add_argument( '--zero-init', dest='zero_init', action='store_true', help='sets initial state to zero. (Default is \"%s\")' % False) general_encoding_options.set_defaults(vcd=False) general_encoding_options.add_argument( '--vcd', dest='vcd', action='store_true', help="generate traces also in vcd format. (Default is \"%s\")" % False) general_encoding_options.add_argument( '--clock-behaviors', metavar='clock_behaviors', type=str, nargs='?', help='semi column separated list of clock behaviors instantiation.') # Verification Options ver_options = parser.add_problem_group('analysis') ver_options.set_defaults(safety=False) ver_options.add_argument('--safety', dest='safety', action='store_true', help='safety verification using BMC.') ver_options.set_defaults(ltl=False) ver_options.add_argument('--ltl', dest='ltl', action='store_true', help='ltl verification using BMC.') ver_options.set_defaults(simulate=False) ver_options.add_argument('--simulate', dest='simulate', action='store_true', help='simulate system using BMC.') ver_options.set_defaults(equivalence=None) ver_options.add_argument('--equivalence', metavar='<input files>', type=str, required=False, help='equivalence checking using BMC.') ver_options.set_defaults(fsm_check=False) ver_options.add_argument( '--fsm-check', dest='fsm_check', action='store_true', help='check if the state machine is deterministic.') ver_options.set_defaults(parametric=False) ver_options.add_argument('--parametric', dest='parametric', action='store_true', help='parametric analysis using BMC.') # Verification parameters ver_params = parser.add_problem_group('verification parameters') ver_params.set_defaults(properties=None) ver_params.add_argument('-p', '--properties', metavar='<invar list>', type=str, required=False, help='comma separated list of properties.') ver_params.set_defaults(bmc_length=5) ver_params.add_argument( '-k', '--bmc-length', metavar='<BMC length>', type=int, required=False, help="depth of BMC unrolling. (Default is \"%s\")" % 5) ver_params.set_defaults(bmc_length_min=0) ver_params.add_argument( '-km', '--bmc-length-min', metavar='<BMC length>', type=int, required=False, help="minimum depth of BMC unrolling. (Default is \"%s\")" % 0) ver_params.set_defaults(precondition=None) ver_params.add_argument('-r', '--precondition', metavar='<invar>', type=str, required=False, help='invariant properties precondition.') ver_params.set_defaults(lemmas=None) ver_params.add_argument('-l', '--lemmas', metavar='<invar list>', type=str, required=False, help='comma separated list of lemmas.') ver_params.set_defaults(assumptions=None) ver_params.add_argument( '-a', '--assumptions', metavar='<invar assumptions list>', type=str, required=False, help='semi column separated list of invariant assumptions.') ver_params.add_argument( '--generators', metavar='generators', type=str, nargs='?', help='semi column separated list of generators instantiation.') ver_params.set_defaults(prove=False) ver_params.add_argument( '--prove', dest='prove', action='store_true', help= "use indution to prove the satisfiability of the property. (Default is \"%s\")" % False) ver_params.set_defaults(assume_if_true=False) ver_params.add_argument( '--assume-if-true', dest='assume_if_true', action='store_true', help="add true properties as assumptions. (Default is \"%s\")" % False) ver_params.set_defaults(coi=False) ver_params.add_argument( '--coi', dest='coi', action='store_true', help="enables Cone of Influence. (Default is \"%s\")" % False) ver_params.set_defaults(cardinality=5) ver_params.add_argument( '--cardinality', dest='cardinality', type=int, required=False, help= "bounds number of active parameters. -1 is unbounded. (Default is \"%s\")" % 5) strategies = [ " - \"%s\": %s" % (x[0], x[1]) for x in MCConfig.get_strategies() ] defstrategy = MCConfig.get_strategies()[0][0] ver_params.set_defaults(strategy=defstrategy) ver_params.add_argument( '--strategy', metavar='strategy', type=str, nargs='?', help='select the BMC strategy between (Default is \"%s\"):\n%s' % (defstrategy, "\n".join(strategies))) ver_params.set_defaults(processes=int(multiprocessing.cpu_count() / 2)) ver_params.add_argument( '-j', dest='processes', metavar="<integer level>", type=int, help="number of multi-processes for MULTI strategy. (Default is \"%s\")" % int(multiprocessing.cpu_count() / 2)) ver_params.set_defaults(ninc=False) ver_params.add_argument( '--ninc', dest='ninc', action='store_true', help="disables incrementality. (Default is \"%s\")" % True) ver_params.set_defaults(solver_name='msat') ver_params.add_argument( '--solver-name', metavar='<Solver Name>', type=str, required=False, help="name of SMT solver to be use. (Default is \"%s\")" % 'msat') # Printing parameters print_params = parser.add_problem_group('trace printing') print_params.set_defaults(trace_vars_change=False) print_params.add_argument( '--trace-vars-change', dest='trace_vars_change', action='store_true', help= "show variable assignments in the counterexamples even when unchanged. (Default is \"%s\")" % False) print_params.set_defaults(trace_all_vars=False) print_params.add_argument( '--trace-all-vars', dest='trace_all_vars', action='store_true', help="show all variables in the counterexamples. (Default is \"%s\")" % False) print_params.set_defaults(full_trace=False) print_params.add_argument( '--full-trace', dest='full_trace', action='store_true', help= "sets trace-vars-unchanged and trace-all-vars to True. (Default is \"%s\")" % False) trace_values_base_default = TraceValuesBase.get_all()[0] print_params.set_defaults(trace_values_base=trace_values_base_default) print_params.add_argument( '--trace-values-base', metavar='trace_values_base', type=str, nargs='?', help="sets the style of Bit-Vector values printing. (Default is \"%s\")" % trace_values_base_default) print_params.set_defaults(prefix=None) print_params.add_argument( '--prefix', metavar='<prefix location>', type=str, required=False, help='write the counterexamples with a specified location prefix.') # Translation parameters trans_params = parser.add_problem_group('translation') trans_params.set_defaults(translate=None) trans_params.add_argument('--translate', metavar='<output file>', type=str, required=False, help='translate input file.') printers = [ " - \"%s\": %s" % (x.get_name(), x.get_desc()) for x in HTSPrintersFactory.get_printers_by_type(HTSPrinterType.TRANSSYS) ] printer_default = HTSPrintersFactory.get_default().get_name() trans_params.set_defaults(printer=printer_default) trans_params.add_argument( '--printer', metavar='printer', type=str, nargs='?', help='select the printer between (Default is \"%s\"):\n%s' % (printer_default, "\n".join(printers))) trans_params.set_defaults(skip_solving=False) trans_params.add_argument( '--skip-solving', dest='skip_solving', action='store_true', help="does not call the solver. (Default is \"%s\")" % False) # Debugging deb_params = parser.add_general_group('verbosity') deb_params.set_defaults(verbosity=1) deb_params.add_argument('-v', dest='verbosity', metavar="<integer level>", type=int, help="verbosity level. (Default is \"%s\")" % 1) deb_params.set_defaults(time=False) deb_params.add_argument( '--time', dest='time', action='store_true', help="prints time for every verification. (Default is \"%s\")" % False) deb_params.set_defaults(devel=False) deb_params.add_argument( '--devel', dest='devel', action='store_true', help="enables developer mode. (Default is \"%s\")" % False) problems = parser.parse_args() for problem in problems._problems: print(problem)
async def create_sticker(c: Client, m: Message): if len(m.text) < 100: body_font_size = 35 wrap_size = 30 elif len(m.text) < 200: body_font_size = 30 wrap_size = 35 elif len(m.text) < 500: body_font_size = 20 wrap_size = 40 elif len(m.text) < 1000: body_font_size = 12 wrap_size = 80 else: body_font_size = 8 wrap_size = 100 font = ImageFont.truetype("Segan-Light.ttf", body_font_size) font_who = ImageFont.truetype("TitilliumWeb-Bold.ttf", 24) img = Image.new("RGBA", (512, 512), (255, 255, 255, 0)) draw = ImageDraw.Draw(img) draw.rounded_rectangle = rounded_rectangle wrapper = TextWrapper(width=wrap_size, break_long_words=False, replace_whitespace=False) lines_list = [wrapper.wrap(i) for i in m.text.split('\n') if i != ''] text_lines = list(itertools.chain.from_iterable(lines_list)) y, line_heights = await get_y_and_heights( text_lines, (512, 512), 10, font ) in_y = y rec_y = (y + line_heights[0]) if wrap_size >= 40 else y for i, _ in enumerate(text_lines): rec_y += line_heights[i] await rounded_rectangle(draw, ((90, in_y), (512, rec_y + line_heights[-1])), 10, fill="#effcde") f_user = m.from_user.first_name + " " + m.from_user.last_name if m.from_user.last_name else m.from_user.first_name draw.text((100, y), f"{f_user}:", "#588237", font=font_who) y = (y + (line_heights[0] * (20/100))) if wrap_size >= 40 else y for i, line in enumerate(text_lines): x = 100 y += line_heights[i] draw.text((x, y), line, "#030303", font=font) try: user_profile_pic = await c.get_profile_photos(m.from_user.id) photo = await c.download_media(user_profile_pic[0].file_id, file_ref=user_profile_pic[0].file_ref) except Exception as e: photo = "default.jpg" logging.error(e) im = Image.open(photo).convert("RGBA") im.thumbnail((60, 60)) await crop_to_circle(im) img.paste(im, (20, in_y)) sticker_file = f"{secrets.token_hex(2)}.webp" img.save(sticker_file) await m.reply_sticker( sticker=sticker_file ) try: if os.path.isfile(sticker_file): os.remove(sticker_file) if os.path.isfile(photo) and (photo != "default.jpg"): os.remove(photo) except Exception as e: logging.error(e)
async def create_sticker(client, message): if len(message.text) < 100: body_font_size = 25 wrap_size = 40 elif len(message.text) < 200: body_font_size = 20 wrap_size = 45 elif len(message.text) < 500: body_font_size = 17 wrap_size = 50 elif len(message.text) < 1000: body_font_size = 15 wrap_size = 90 else: body_font_size = 8 wrap_size = 200 font = ImageFont.truetype( 'skynoid/utils/sticker/OpenSans-Regular.ttf', body_font_size, ) font_who = ImageFont.truetype( 'skynoid/utils/sticker/NotoSansDisplay-Bold.ttf', 24, ) img = Image.new( 'RGBA', (512, 512), (255, 255, 255, 0), ) draw = ImageDraw.Draw(img) draw.rounded_rectangle = rounded_rectangle wrapper = TextWrapper( width=wrap_size, break_long_words=False, replace_whitespace=False, ) lines_list = [ wrapper.wrap(i) for i in message.text.split('\n') if i != '' ] text_lines = list(itertools.chain.from_iterable(lines_list)) y, line_heights = await get_y_and_heights( text_lines, (512, 512), 10, font, ) in_y = y rec_y = (y + line_heights[0]) if wrap_size >= 40 else y for i, _ in enumerate(text_lines): rec_y += line_heights[i] await rounded_rectangle( draw, ( (90, in_y), (512, rec_y + line_heights[-1]), ), 10, fill='#e0e0e0', ) first = message.from_user.first_name f_user = ( first + ' ' + message.from_user.last_name if message.from_user.last_name else first ) draw.text( (100, y), f'{f_user}', random.choice(COLORS), font=font_who, ) y = (y + (line_heights[0] * (20/100))) if wrap_size >= 40 else y x = 100 for i, line in enumerate(text_lines): y += line_heights[i] draw.text((x, y), line, '#211536', font=font) try: user_profile_pic = await client.get_profile_photos( message.from_user.id, ) photo = await client.download_media(user_profile_pic[0].file_id) except IndexError: urlretrieve( 'https://telegra.ph/file/1d3bf9a37547be4b04dcd.jpg', 'skynoid/utils/sticker/default.jpg', ) photo = 'skynoid/utils/sticker/default.jpg' im = Image.open(photo).convert('RGBA') im.thumbnail((60, 60)) await crop_to_circle(im) img.paste(im, (20, in_y)) sticker_file = f'{secrets.token_hex(2)}.webp' img.save(sticker_file) await message.reply_sticker( sticker=sticker_file, ) if os.path.isfile(sticker_file): os.remove(sticker_file)
def cpp_dump_hex(buf): # format for CPP macro txt = ', '.join('0x%02x' % i for i in buf) tw = TextWrapper(width=60) return '\n'.join('\t%s \\' % i for i in tw.wrap(txt))
def _wrap(self, indent, s, width=70): indent_str = " " * indent t = TextWrapper(width=width, subsequent_indent=indent_str) return '\n'.join(t.wrap(s))
def message_box(message, width=79, padding=3, print_callable=print): """ Prints a message inside a box. Parameters ---------- message : unicode Message to print. width : int, optional Message box width. padding : unicode, optional Padding on each sides of the message. print_callable : callable, optional Callable used to print the message box. Returns ------- bool Definition success. Examples -------- >>> message = ('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ' ... 'sed do eiusmod tempor incididunt ut labore et dolore magna ' ... 'aliqua.') >>> message_box(message, width=75) =========================================================================== * * * Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do * * eiusmod tempor incididunt ut labore et dolore magna aliqua. * * * =========================================================================== True >>> message_box(message, width=60) ============================================================ * * * Lorem ipsum dolor sit amet, consectetur adipiscing * * elit, sed do eiusmod tempor incididunt ut labore et * * dolore magna aliqua. * * * ============================================================ True >>> message_box(message, width=75, padding=16) =========================================================================== * * * Lorem ipsum dolor sit amet, consectetur * * adipiscing elit, sed do eiusmod tempor * * incididunt ut labore et dolore magna * * aliqua. * * * =========================================================================== True """ ideal_width = width - padding * 2 - 2 def inner(text): """ Formats and pads inner text for the message box. """ return '*{0}{1}{2}{0}*'.format( ' ' * padding, text, (' ' * (width - len(text) - padding * 2 - 2))) print_callable('=' * width) print_callable(inner('')) wrapper = TextWrapper( width=ideal_width, break_long_words=False, replace_whitespace=False) lines = [wrapper.wrap(line) for line in message.split("\n")] lines = [' ' if len(line) == 0 else line for line in lines] for line in chain(*lines): print_callable(inner(line.expandtabs())) print_callable(inner('')) print_callable('=' * width) return True
def help(self): # @ReservedAssignment """Prints this help message and quits""" if self._get_prog_version(): self.version() print("") if self.DESCRIPTION: print(self.DESCRIPTION.strip() + '\n') m = six.getfullargspec(self.main) tailargs = m.args[1:] # skip self if m.defaults: for i, d in enumerate(reversed(m.defaults)): tailargs[-i - 1] = "[{0}={1}]".format(tailargs[-i - 1], d) if m.varargs: tailargs.append("{0}...".format(m.varargs, )) tailargs = " ".join(tailargs) with self.COLOR_USAGE: print(T_("Usage:")) if not self.USAGE: if self._subcommands: self.USAGE = T_( " {progname} [SWITCHES] [SUBCOMMAND [SWITCHES]] {tailargs}\n" ) else: self.USAGE = T_(" {progname} [SWITCHES] {tailargs}\n") print( self.USAGE.format(progname=colors.filter(self.PROGNAME), tailargs=tailargs)) by_groups = {} for si in self._switches_by_func.values(): if si.group not in by_groups: by_groups[si.group] = [] by_groups[si.group].append(si) def switchs(by_groups, show_groups): for grp, swinfos in sorted(by_groups.items(), key=lambda item: item[0]): if show_groups: lgrp = T_(grp) if grp in _switch_groups else grp print(self.COLOR_GROUPS[grp] | lgrp) for si in sorted(swinfos, key=lambda si: si.names): swnames = ", ".join(("-" if len(n) == 1 else "--") + n for n in si.names if n in self._switches_by_name and self._switches_by_name[n] == si) if si.argtype: if hasattr(si.argtype, '__name__'): typename = si.argtype.__name__ else: typename = str(si.argtype) argtype = " {0}:{1}".format(si.argname.upper(), typename) else: argtype = "" prefix = swnames + argtype yield si, prefix, self.COLOR_GROUPS[grp] if show_groups: print("") sw_width = max( len(prefix) for si, prefix, color in switchs(by_groups, False)) + 4 cols, _ = get_terminal_size() description_indent = " {0}{1}{2}" wrapper = TextWrapper(width=max(cols - min(sw_width, 60), 50) - 6) indentation = "\n" + " " * (cols - wrapper.width) for switch_info, prefix, color in switchs(by_groups, True): help = switch_info.help # @ReservedAssignment if switch_info.list: help += T_("; may be given multiple times") if switch_info.mandatory: help += T_("; required") if switch_info.requires: help += T_("; requires {0}").format(", ".join( (("-" if len(switch) == 1 else "--") + switch) for switch in switch_info.requires)) if switch_info.excludes: help += T_("; excludes {0}").format(", ".join( (("-" if len(switch) == 1 else "--") + switch) for switch in switch_info.excludes)) msg = indentation.join( wrapper.wrap(" ".join(l.strip() for l in help.splitlines()))) if len(prefix) + wrapper.width >= cols: padding = indentation else: padding = " " * max(cols - wrapper.width - len(prefix) - 4, 1) print( description_indent.format(color | prefix, padding, color | msg)) if self._subcommands: gc = self.COLOR_GROUPS["Subcommands"] print(gc | T_("Subcommands:")) for name, subcls in sorted(self._subcommands.items()): with gc: subapp = subcls.get() doc = subapp.DESCRIPTION if subapp.DESCRIPTION else getdoc( subapp) if self.SUBCOMMAND_HELPMSG: help = doc + "; " if doc else "" # @ReservedAssignment help += self.SUBCOMMAND_HELPMSG.format( parent=self.PROGNAME, sub=name) else: help = doc if doc else "" # @ReservedAssignment msg = indentation.join( wrapper.wrap(" ".join(l.strip() for l in help.splitlines()))) if len(name) + wrapper.width >= cols: padding = indentation else: padding = " " * max( cols - wrapper.width - len(name) - 4, 1) if colors.contains_colors(subcls.name): bodycolor = colors.extract(subcls.name) else: bodycolor = gc print( description_indent.format( subcls.name, padding, bodycolor | colors.filter(msg)))
class WrapTestCase(BaseTestCase): def setUp(self): self.wrapper = TextWrapper(width=45) def test_simple(self): # Simple case: just words, spaces, and a bit of punctuation text = "Hello there, how are you this fine day? I'm glad to hear it!" self.check_wrap(text, 12, [ "Hello there,", "how are you", "this fine", "day? I'm", "glad to hear", "it!" ]) self.check_wrap(text, 42, [ "Hello there, how are you this fine day?", "I'm glad to hear it!" ]) self.check_wrap(text, 80, [text]) def test_whitespace(self): # Whitespace munging and end-of-sentence detection text = """\ This is a paragraph that already has line breaks. But some of its lines are much longer than the others, so it needs to be wrapped. Some lines are \ttabbed too. What a mess! """ expect = [ "This is a paragraph that already has line", "breaks. But some of its lines are much", "longer than the others, so it needs to be", "wrapped. Some lines are tabbed too. What a", "mess!" ] wrapper = TextWrapper(45, fix_sentence_endings=True) result = wrapper.wrap(text) self.check(result, expect) result = wrapper.fill(text) self.check(result, '\n'.join(expect)) def test_fix_sentence_endings(self): wrapper = TextWrapper(60, fix_sentence_endings=True) # SF #847346: ensure that fix_sentence_endings=True does the # right thing even on input short enough that it doesn't need to # be wrapped. text = "A short line. Note the single space." expect = ["A short line. Note the single space."] self.check(wrapper.wrap(text), expect) # Test some of the hairy end cases that _fix_sentence_endings() # is supposed to handle (the easy stuff is tested in # test_whitespace() above). text = "Well, Doctor? What do you think?" expect = ["Well, Doctor? What do you think?"] self.check(wrapper.wrap(text), expect) text = "Well, Doctor?\nWhat do you think?" self.check(wrapper.wrap(text), expect) text = 'I say, chaps! Anyone for "tennis?"\nHmmph!' expect = ['I say, chaps! Anyone for "tennis?" Hmmph!'] self.check(wrapper.wrap(text), expect) wrapper.width = 20 expect = ['I say, chaps!', 'Anyone for "tennis?"', 'Hmmph!'] self.check(wrapper.wrap(text), expect) text = 'And she said, "Go to hell!"\nCan you believe that?' expect = ['And she said, "Go to', 'hell!" Can you', 'believe that?'] self.check(wrapper.wrap(text), expect) wrapper.width = 60 expect = ['And she said, "Go to hell!" Can you believe that?'] self.check(wrapper.wrap(text), expect) text = 'File stdio.h is nice.' expect = ['File stdio.h is nice.'] self.check(wrapper.wrap(text), expect) def test_wrap_short(self): # Wrapping to make short lines longer text = "This is a\nshort paragraph." self.check_wrap(text, 20, ["This is a short", "paragraph."]) self.check_wrap(text, 40, ["This is a short paragraph."]) def test_wrap_short_1line(self): # Test endcases text = "This is a short line." self.check_wrap(text, 30, ["This is a short line."]) self.check_wrap(text, 30, ["(1) This is a short line."], initial_indent="(1) ") def test_hyphenated(self): # Test breaking hyphenated words text = ("this-is-a-useful-feature-for-" "reformatting-posts-from-tim-peters'ly") self.check_wrap(text, 40, [ "this-is-a-useful-feature-for-", "reformatting-posts-from-tim-peters'ly" ]) self.check_wrap(text, 41, [ "this-is-a-useful-feature-for-", "reformatting-posts-from-tim-peters'ly" ]) self.check_wrap(text, 42, [ "this-is-a-useful-feature-for-reformatting-", "posts-from-tim-peters'ly" ]) def test_hyphenated_numbers(self): # Test that hyphenated numbers (eg. dates) are not broken like words. text = ("Python 1.0.0 was released on 1994-01-26. Python 1.0.1 was\n" "released on 1994-02-15.") self.check_wrap(text, 35, [ 'Python 1.0.0 was released on', '1994-01-26. Python 1.0.1 was', 'released on 1994-02-15.' ]) self.check_wrap(text, 40, [ 'Python 1.0.0 was released on 1994-01-26.', 'Python 1.0.1 was released on 1994-02-15.' ]) text = "I do all my shopping at 7-11." self.check_wrap(text, 25, ["I do all my shopping at", "7-11."]) self.check_wrap(text, 27, ["I do all my shopping at", "7-11."]) self.check_wrap(text, 29, ["I do all my shopping at 7-11."]) def test_em_dash(self): # Test text with em-dashes text = "Em-dashes should be written -- thus." self.check_wrap(text, 25, ["Em-dashes should be", "written -- thus."]) # Probe the boundaries of the properly written em-dash, # ie. " -- ". self.check_wrap(text, 29, ["Em-dashes should be written", "-- thus."]) expect = ["Em-dashes should be written --", "thus."] self.check_wrap(text, 30, expect) self.check_wrap(text, 35, expect) self.check_wrap(text, 36, ["Em-dashes should be written -- thus."]) # The improperly written em-dash is handled too, because # it's adjacent to non-whitespace on both sides. text = "You can also do--this or even---this." expect = ["You can also do", "--this or even", "---this."] self.check_wrap(text, 15, expect) self.check_wrap(text, 16, expect) expect = ["You can also do--", "this or even---", "this."] self.check_wrap(text, 17, expect) self.check_wrap(text, 19, expect) expect = ["You can also do--this or even", "---this."] self.check_wrap(text, 29, expect) self.check_wrap(text, 31, expect) expect = ["You can also do--this or even---", "this."] self.check_wrap(text, 32, expect) self.check_wrap(text, 35, expect) # All of the above behaviour could be deduced by probing the # _split() method. text = "Here's an -- em-dash and--here's another---and another!" expect = [ "Here's", " ", "an", " ", "--", " ", "em-", "dash", " ", "and", "--", "here's", " ", "another", "---", "and", " ", "another!" ] self.check_split(text, expect) text = "and then--bam!--he was gone" expect = [ "and", " ", "then", "--", "bam!", "--", "he", " ", "was", " ", "gone" ] self.check_split(text, expect) def test_unix_options(self): # Test that Unix-style command-line options are wrapped correctly. # Both Optik (OptionParser) and Docutils rely on this behaviour! text = "You should use the -n option, or --dry-run in its long form." self.check_wrap(text, 20, [ "You should use the", "-n option, or --dry-", "run in its long", "form." ]) self.check_wrap(text, 21, [ "You should use the -n", "option, or --dry-run", "in its long form." ]) expect = [ "You should use the -n option, or", "--dry-run in its long form." ] self.check_wrap(text, 32, expect) self.check_wrap(text, 34, expect) self.check_wrap(text, 35, expect) self.check_wrap(text, 38, expect) expect = [ "You should use the -n option, or --dry-", "run in its long form." ] self.check_wrap(text, 39, expect) self.check_wrap(text, 41, expect) expect = [ "You should use the -n option, or --dry-run", "in its long form." ] self.check_wrap(text, 42, expect) # Again, all of the above can be deduced from _split(). text = "the -n option, or --dry-run or --dryrun" expect = [ "the", " ", "-n", " ", "option,", " ", "or", " ", "--dry-", "run", " ", "or", " ", "--dryrun" ] self.check_split(text, expect) def test_funky_hyphens(self): # Screwy edge cases cooked up by David Goodger. All reported # in SF bug #596434. self.check_split("what the--hey!", ["what", " ", "the", "--", "hey!"]) self.check_split("what the--", ["what", " ", "the--"]) self.check_split("what the--.", ["what", " ", "the--."]) self.check_split("--text--.", ["--text--."]) # When I first read bug #596434, this is what I thought David # was talking about. I was wrong; these have always worked # fine. The real problem is tested in test_funky_parens() # below... self.check_split("--option", ["--option"]) self.check_split("--option-opt", ["--option-", "opt"]) self.check_split("foo --option-opt bar", ["foo", " ", "--option-", "opt", " ", "bar"]) def test_punct_hyphens(self): # Oh bother, SF #965425 found another problem with hyphens -- # hyphenated words in single quotes weren't handled correctly. # In fact, the bug is that *any* punctuation around a hyphenated # word was handled incorrectly, except for a leading "--", which # was special-cased for Optik and Docutils. So test a variety # of styles of punctuation around a hyphenated word. # (Actually this is based on an Optik bug report, #813077). self.check_split("the 'wibble-wobble' widget", ['the', ' ', "'wibble-", "wobble'", ' ', 'widget']) self.check_split('the "wibble-wobble" widget', ['the', ' ', '"wibble-', 'wobble"', ' ', 'widget']) self.check_split("the (wibble-wobble) widget", ['the', ' ', "(wibble-", "wobble)", ' ', 'widget']) self.check_split("the ['wibble-wobble'] widget", ['the', ' ', "['wibble-", "wobble']", ' ', 'widget']) def test_funky_parens(self): # Second part of SF bug #596434: long option strings inside # parentheses. self.check_split("foo (--option) bar", ["foo", " ", "(--option)", " ", "bar"]) # Related stuff -- make sure parens work in simpler contexts. self.check_split("foo (bar) baz", ["foo", " ", "(bar)", " ", "baz"]) self.check_split("blah (ding dong), wubba", ["blah", " ", "(ding", " ", "dong),", " ", "wubba"]) def test_initial_whitespace(self): # SF bug #622849 reported inconsistent handling of leading # whitespace; let's test that a bit, shall we? text = " This is a sentence with leading whitespace." self.check_wrap(text, 50, [" This is a sentence with leading whitespace."]) self.check_wrap(text, 30, [" This is a sentence with", "leading whitespace."]) def test_no_drop_whitespace(self): # SF patch #1581073 text = " This is a sentence with much whitespace." self.check_wrap(text, 10, [ " This is a", " ", "sentence ", "with ", "much white", "space." ], drop_whitespace=False) if test_support.have_unicode: def test_unicode(self): # *Very* simple test of wrapping Unicode strings. I'm sure # there's more to it than this, but let's at least make # sure textwrap doesn't crash on Unicode input! text = u"Hello there, how are you today?" self.check_wrap(text, 50, [u"Hello there, how are you today?"]) self.check_wrap(text, 20, [u"Hello there, how are", "you today?"]) olines = self.wrapper.wrap(text) self.assertIsInstance(olines, list) self.assertIsInstance(olines[0], unicode) otext = self.wrapper.fill(text) self.assertIsInstance(otext, unicode) def test_no_split_at_umlaut(self): text = u"Die Empf\xe4nger-Auswahl" self.check_wrap(text, 13, [u"Die", u"Empf\xe4nger-", u"Auswahl"]) def test_umlaut_followed_by_dash(self): text = u"aa \xe4\xe4-\xe4\xe4" self.check_wrap(text, 7, [u"aa \xe4\xe4-", u"\xe4\xe4"]) def test_split(self): # Ensure that the standard _split() method works as advertised # in the comments text = "Hello there -- you goof-ball, use the -b option!" result = self.wrapper._split(text) self.check(result, [ "Hello", " ", "there", " ", "--", " ", "you", " ", "goof-", "ball,", " ", "use", " ", "the", " ", "-b", " ", "option!" ]) def test_break_on_hyphens(self): # Ensure that the break_on_hyphens attributes work text = "yaba daba-doo" self.check_wrap(text, 10, ["yaba daba-", "doo"], break_on_hyphens=True) self.check_wrap(text, 10, ["yaba", "daba-doo"], break_on_hyphens=False) def test_bad_width(self): # Ensure that width <= 0 is caught. text = "Whatever, it doesn't matter." self.assertRaises(ValueError, wrap, text, 0) self.assertRaises(ValueError, wrap, text, -1)
def doit(args): logger = args.logger htmlfile = args.html if args.ttfaudit: # Special action to compare checks in profile against check_list values audit(args.fonts, logger) # args.fonts used as output file name for audit return # Process list of fonts supplied, expanding wildcards using glob if needed fonts = [] fontstype = None for pattern in args.fonts: for fullpath in glob.glob(pattern): ftype = fullpath.lower().rsplit(".", 1)[-1] if ftype == "otf": ftype = "ttf" if ftype not in ("ttf", "ufo"): logger.log( "Fonts must be OpenType or UFO - " + fullpath + " invalid", "S") if fontstype is None: fontstype = ftype else: if ftype != fontstype: logger.log( "All fonts must be of the same type - both UFO and ttf/otf fonts supplied", "S") fonts.append(fullpath) if fonts == []: logger.log( "No files match the filespec provided for fonts: " + str(args.fonts), "S") # Create the profile object if args.profile: proname = args.profile else: if fontstype == "ttf": proname = "silfont.fbtests.ttfchecks" else: logger.log("UFO fonts not yet supported", "S") try: module = get_module(proname) except Exception as e: logger.log("Failed to import profile: " + proname + "\n" + str(e), "S") profile = get_module_profile(module) psfcheck_list = module.psfcheck_list # Create the runner and reporter objetcs, then run the tests runner = CheckRunner(profile, values={"fonts": fonts}) sr = SerializeReporter( runner=runner ) # This produces results from all the tests in sr.getdoc for later analysis reporters = [sr.receive] if htmlfile: hr = HTMLReporter(runner=runner, loglevels=[SKIP]) reporters.append(hr.receive) distribute_generator(runner.run(), reporters) # Process the results results = sr.getdoc() sections = results["sections"] checks = {} maxname = 11 somedebug = False overrides = {} tempoverrides = False for section in sections: secchecks = section["checks"] for check in secchecks: checkid = check["key"][1][17:-1] fontfile = check[ "filename"] if "filename" in check else "Family-wide" path, fontname = os.path.split(fontfile) if fontname not in checks: checks[fontname] = { "ERROR": [], "FAIL": [], "WARN": [], "INFO": [], "SKIP": [], "PASS": [], "DEBUG": [] } if len(fontname) > maxname: maxname = len(fontname) status = check["logs"][0]["status"] if checkid in psfcheck_list: # Look for status overrides (changetype, temp) = ("temp_change_status", True) if "temp_change_status" in psfcheck_list[checkid]\ else ("change_status", False) if changetype in psfcheck_list[checkid]: change_status = psfcheck_list[checkid][changetype] if status in change_status: reason = change_status[ "reason"] if "reason" in change_status else None overrides[fontname + ", " + checkid] = (status + " to " + change_status[status], temp, reason) if temp: tempoverrides = True status = change_status[status] checks[fontname][status].append(check) if status == "DEBUG": somedebug = True if htmlfile: logger.log("Writing results to " + htmlfile, "P") with open(htmlfile, 'w') as hfile: hfile.write(hr.get_html()) fbstats = ["ERROR", "FAIL", "WARN", "INFO", "SKIP", "PASS"] psflevels = ["E", "E", "W", "I", "I", "V"] if somedebug: # Only have debug column if some debug statuses are present fbstats.append("DEBUG") psflevels.append("W") wrapper = TextWrapper(width=120, initial_indent=" ", subsequent_indent=" ") errorcnt = 0 failcnt = 0 summarymess = "Check status summary:\n" summarymess += "{:{pad}}ERROR FAIL WARN INFO SKIP PASS".format( "", pad=maxname + 4) if somedebug: summarymess += " DEBUG" fontlist = list(sorted(x for x in checks if x != "Family-wide")) + [ "Family-wide" ] # Sort with Family-wide last for fontname in fontlist: summarymess += "\n {:{pad}}".format(fontname, pad=maxname) for i, status in enumerate(fbstats): psflevel = psflevels[i] checklist = checks[fontname][status] cnt = len(checklist) if cnt > 0 or status != "DEBUG": summarymess += "{:6d}".format(cnt) # Suppress 0 for DEBUG if cnt: if status == "ERROR": errorcnt += cnt if status == "FAIL": failcnt += cnt messparts = [ "Checks with status {} for {}".format(status, fontname) ] for check in checklist: messparts.append(" > {}".format(check["key"][1][17:-1])) messparts += wrapper.wrap(check["logs"][0]["message"]) logger.log("\n".join(messparts), psflevel) if overrides != {}: summarymess += "\n Note: " + str( len(overrides) ) + " Fontbakery statuses were overridden - see log file for details" if tempoverrides: summarymess += "\n ******** Some of the overrides were temporary overrides ********" logger.log(summarymess, "P") if overrides != {}: for oname in overrides: override = overrides[oname] mess = "Status override for " + oname + ": " + override[0] if override[1]: mess += " (Temporary override)" logger.log(mess, "W") if override[2] is not None: logger.log("Override reason: " + override[2], "I") if errorcnt + failcnt > 0: mess = str( failcnt) + " test(s) gave a status of FAIL" if failcnt > 0 else "" if errorcnt > 0: if failcnt > 0: mess += "\n " mess += str(errorcnt) + " test(s) gave a status of ERROR which means they failed to execute properly." \ "\n " \ " ERROR probably indicates a software issue rather than font issue" logger.log(mess, "S")
userDefinedRange = JobChecker.getUserInput(len(indexListOfMatchingJobs)) listOfLatLon = [] jobCounter = 0 #for x in range(userDefinedRange): for x in indexListOfMatchingJobs: if jobCounter==userDefinedRange: break jobCounter = jobCounter + 1 #add two to not use StackOverflow site/page titles (line up the titles with everything else) print("Title: " + cleanedTitlesList[x+2]) print("Link: " + links[x]) print("Location: " + locationsString[x]) location = geolocator.geocode(locationsString[x], timeout=10) #print("Latitude, Longitude: " + str(location.latitude), str(location.longitude)) listOfLatLon = JobChecker.listOfLatLonUpdate(listOfLatLon, location.latitude, location.longitude) #add one to line up descriptions with everything else descStr = cleanedDescriptionsList[x+1] print("\n".join(tw.wrap(descStr))[:800] + "...*****TO READ REST OF DESCRIPTION GO TO LINK*****") print("\n") #pause to not overload geolocator.geocode time.sleep(.1) print("**********PLEASE WAIT UP TO 15 SECONDS FOR MAP TO LOAD**********") map = JobChecker.mapSetup() JobChecker.plotPoints(listOfLatLon, map) plt.title("Jobs within 50 miles of Bridgewater MA with keyword '" + userDefinedKeyword + "' in description") plt.show()
class VCardWriter(object): """Class to create a file with data in VCard format.""" LINELENGTH = 73 # unclear if the 75 chars of spec includes \r\n. ESCAPE_CHAR = '\\' TOBE_ESCAPED = ['\\', ',', ';'] # order is important LINE_CONTINUATION = [' ', '\t'] @staticmethod def esc(data): """Escape the special chars of the VCard protocol.""" if isinstance(data, str): for char in VCardWriter.TOBE_ESCAPED: data = data.replace(char, VCardWriter.ESCAPE_CHAR + char) return data elif type(data) == type([]): return list(map(VCardWriter.esc, data)) elif type(data) == type(()): return tuple(map(VCardWriter.esc, data)) else: raise TypeError("VCard escaping is not implemented for " "data type %s." % str(type(data))) def __init__(self, database, filename, option_box=None, user=None): self.db = database self.filename = filename self.user = user self.filehandle = None self.option_box = option_box if isinstance(self.user.callback, collections.Callable): # callback is really callable self.update = self.update_real else: self.update = self.update_empty if option_box: self.option_box.parse_options() self.db = option_box.get_filtered_database(self.db) self.txtwrp = TextWrapper(width=self.LINELENGTH, expand_tabs=False, replace_whitespace=False, drop_whitespace=False, subsequent_indent=self.LINE_CONTINUATION[0]) self.count = 0 self.total = 0 def update_empty(self): """Progress can't be reported.""" pass def update_real(self): """Report progress.""" self.count += 1 newval = int(100 * self.count / self.total) if newval != self.oldval: self.user.callback(newval) self.oldval = newval def writeln(self, text): """ Write a property of the VCard to file. Can't cope with nested VCards, section 2.4.2 of RFC 2426. """ self.filehandle.write('%s\r\n' % '\r\n'.join( [line.encode('utf-8') for line in self.txtwrp.wrap(text)])) def export_data(self): """Open the file and loop over everyone too write their VCards.""" with OpenFileOrStdout(self.filename) as self.filehandle: if self.filehandle: self.count = 0 self.oldval = 0 self.total = self.db.get_number_of_people() for key in self.db.iter_person_handles(): self.write_person(key) self.update() return True def write_person(self, person_handle): """Create a VCard for the specified person.""" person = self.db.get_person_from_handle(person_handle) if person: self.write_header() prname = person.get_primary_name() self.write_formatted_name(prname) self.write_name(prname) self.write_sortstring(prname) self.write_nicknames(person, prname) self.write_gender(person) self.write_birthdate(person) self.write_addresses(person) self.write_urls(person) self.write_occupation(person) self.write_footer() def write_header(self): """Write the opening lines of a VCard.""" self.writeln("BEGIN:VCARD") self.writeln("VERSION:3.0") self.writeln("PRODID:-//Gramps//NONSGML %s %s//EN" % (PROGRAM_NAME, VERSION)) def write_footer(self): """Write the closing lines of a VCard.""" self.writeln("END:VCARD") self.writeln("") def write_formatted_name(self, prname): """Write the compulsory FN property of VCard.""" regular_name = prname.get_regular_name().strip() title = prname.get_title() if title: regular_name = "%s %s" % (title, regular_name) self.writeln("FN:%s" % self.esc(regular_name)) def write_name(self, prname): """Write the compulsory N property of a VCard.""" family_name = '' given_name = '' additional_names = '' hon_prefix = '' suffix = '' primary_surname = prname.get_primary_surname() surname_list = prname.get_surname_list() if not surname_list[0].get_primary(): surname_list.remove(primary_surname) surname_list.insert(0, primary_surname) family_name = ','.join( self.esc([ ("%s %s %s" % (surname.get_prefix(), surname.get_surname(), surname.get_connector())).strip() for surname in surname_list ])) call_name = prname.get_call_name() if call_name: given_name = self.esc(call_name) additional_name_list = prname.get_first_name().split() if call_name in additional_name_list: additional_name_list.remove(call_name) additional_names = ','.join(self.esc(additional_name_list)) else: name_list = prname.get_first_name().split() if len(name_list) > 0: given_name = self.esc(name_list[0]) if len(name_list) > 1: additional_names = ','.join(self.esc(name_list[1:])) # Alternate names are ignored because names just don't add up: # if one name is Jean and an alternate is Paul then you can't # conclude the Jean Paul is also an alternate name of that person. # Assume all titles/suffixes that apply are present in primary name. hon_prefix = ','.join(self.esc(prname.get_title().split())) suffix = ','.join(self.esc(prname.get_suffix().split())) self.writeln( "N:%s;%s;%s;%s;%s" % (family_name, given_name, additional_names, hon_prefix, suffix)) def write_sortstring(self, prname): """Write the SORT-STRING property of a VCard.""" # TODO only add sort-string if needed self.writeln("SORT-STRING:%s" % self.esc(_nd.sort_string(prname))) def write_nicknames(self, person, prname): """Write the NICKNAME property of a VCard.""" nicknames = [ x.get_nick_name() for x in person.get_alternate_names() if x.get_nick_name() ] if prname.get_nick_name(): nicknames.insert(0, prname.get_nick_name()) if len(nicknames) > 0: self.writeln("NICKNAME:%s" % (','.join(self.esc(nicknames)))) def write_gender(self, person): """Write the X-GENDER property of a VCard (X- dropped in 4.0, we're at 3.0).""" gender = person.get_gender() gender_value = '' if gender == Person.MALE: gender_value = 'Male' elif gender == Person.FEMALE: gender_value = 'Female' log.info("gender: %s -> %s" % (gender, gender_value)) if gender_value: self.writeln("X-GENDER:%s" % (gender_value)) def write_birthdate(self, person): """Write the BDAY property of a VCard.""" birth_ref = person.get_birth_ref() if birth_ref: birth = self.db.get_event_from_handle(birth_ref.ref) if birth: b_date = birth.get_date_object() mod = b_date.get_modifier() if (mod != Date.MOD_TEXTONLY and not b_date.is_empty() and not mod == Date.MOD_SPAN and not mod == Date.MOD_RANGE): (day, month, year, slash) = b_date.get_start_date() if day > 0 and month > 0 and year > 0: self.writeln("BDAY:%s-%02d-%02d" % (year, month, day)) def write_addresses(self, person): """Write ADR and TEL properties of a VCard.""" address_list = person.get_address_list() for address in address_list: postbox = "" ext = "" street = address.get_street() city = address.get_city() state = address.get_state() zipcode = address.get_postal_code() country = address.get_country() if street or city or state or zipcode or country: self.writeln("ADR:%s;%s;%s;%s;%s;%s;%s" % self.esc( (postbox, ext, street, city, state, zipcode, country))) phone = address.get_phone() if phone: self.writeln("TEL:%s" % phone) def write_urls(self, person): """Write URL and EMAIL properties of a VCard.""" url_list = person.get_url_list() for url in url_list: href = url.get_path() if href: if url.get_type() == UrlType(UrlType.EMAIL): if href.startswith('mailto:'): href = href[len('mailto:'):] self.writeln("EMAIL:%s" % self.esc(href)) else: self.writeln("URL:%s" % self.esc(href)) def write_occupation(self, person): """ Write ROLE property of a VCard. Use the most recent occupation event. """ event_refs = person.get_primary_event_ref_list() events = [ event for event in [self.db.get_event_from_handle(ref.ref) for ref in event_refs] if event.get_type() == EventType(EventType.OCCUPATION) ] if len(events) > 0: events.sort(key=lambda x: x.get_date_object()) occupation = events[-1].get_description() if occupation: self.writeln("ROLE:%s" % occupation)
def help(self): # @ReservedAssignment """Prints this help message and quits""" if self._get_prog_version(): self.version() print("") if self.DESCRIPTION: print(self.DESCRIPTION.strip() + '\n') def split_indentation(s): """Identifies the initial indentation (all spaces) of the string and returns the indentation as well as the remainder of the line. """ i = 0 while i < len(s) and s[i] == ' ': i += 1 return s[:i], s[i:] def paragraphs(text): """Yields each paragraph of text along with its initial and subsequent indentations to be used by textwrap.TextWrapper. Identifies list items from their first non-space character being one of bullets '-', '*', and '/'. However, bullet '/' is invisible and is removed from the list item. :param text: The text to separate into paragraphs """ paragraph = None initial_indent = "" subsequent_indent = "" def current(): """Yields the current result if present. """ if paragraph: yield paragraph, initial_indent, subsequent_indent for part in text.lstrip("\n").split("\n"): indent, line = split_indentation(part) if len(line) == 0: # Starting a new paragraph for item in current(): yield item yield "", "", "" paragraph = None initial_indent = "" subsequent_indent = "" else: # Adding to current paragraph def is_list_item(line): """Returns true if the first element of 'line' is a bullet character. """ bullets = ['-', '*', '/'] return line[0] in bullets def has_invisible_bullet(line): """Returns true if the first element of 'line' is the invisible bullet ('/'). """ return line[0] == '/' if is_list_item(line): # Done with current paragraph for item in current(): yield item if has_invisible_bullet(line): line = line[1:] paragraph = line initial_indent = indent # Calculate extra indentation for subsequent lines of this list item i = 1 while i < len(line) and line[i] == ' ': i += 1 subsequent_indent = indent + " " * i else: if not paragraph: # Start a new paragraph paragraph = line initial_indent = indent subsequent_indent = indent else: # Add to current paragraph paragraph = paragraph + ' ' + line for item in current(): yield item def wrapped_paragraphs(text, width): """Yields each line of each paragraph of text after wrapping them on 'width' number of columns. :param text: The text to yield wrapped lines of :param width: The width of the wrapped output """ if not text: return width = max(width, 1) for paragraph, initial_indent, subsequent_indent in paragraphs( text): wrapper = TextWrapper( width, initial_indent=initial_indent, subsequent_indent=subsequent_indent) w = wrapper.wrap(paragraph) for line in w: yield line if len(w) == 0: yield "" cols, _ = get_terminal_size() for line in wrapped_paragraphs(self.DESCRIPTION_MORE, cols): print(line) m = six.getfullargspec(self.main) tailargs = m.args[1:] # skip self if m.defaults: for i, d in enumerate(reversed(m.defaults)): tailargs[-i - 1] = "[{0}={1}]".format(tailargs[-i - 1], d) if m.varargs: tailargs.append("{0}...".format(m.varargs, )) tailargs = " ".join(tailargs) with self.COLOR_USAGE: print(T_("Usage:")) if not self.USAGE: if self._subcommands: self.USAGE = T_( " {progname} [SWITCHES] [SUBCOMMAND [SWITCHES]] {tailargs}\n" ) else: self.USAGE = T_(" {progname} [SWITCHES] {tailargs}\n") print(self.USAGE.format( progname=colors.filter(self.PROGNAME), tailargs=tailargs)) by_groups = {} for si in self._switches_by_func.values(): if si.group not in by_groups: by_groups[si.group] = [] by_groups[si.group].append(si) def switchs(by_groups, show_groups): for grp, swinfos in sorted( by_groups.items(), key=lambda item: item[0]): if show_groups: lgrp = T_(grp) if grp in _switch_groups else grp print(self.COLOR_GROUPS[grp] | lgrp + ':') for si in sorted(swinfos, key=lambda si: si.names): swnames = ", ".join(("-" if len(n) == 1 else "--") + n for n in si.names if n in self._switches_by_name and self._switches_by_name[n] == si) if si.argtype: if hasattr(si.argtype, '__name__'): typename = si.argtype.__name__ else: typename = str(si.argtype) argtype = " {0}:{1}".format(si.argname.upper(), typename) else: argtype = "" prefix = swnames + argtype yield si, prefix, self.COLOR_GROUPS[grp] if show_groups: print("") sw_width = max( len(prefix) for si, prefix, color in switchs(by_groups, False)) + 4 description_indent = " {0}{1}{2}" wrapper = TextWrapper(width=max(cols - min(sw_width, 60), 50) - 6) indentation = "\n" + " " * (cols - wrapper.width) for switch_info, prefix, color in switchs(by_groups, True): help = switch_info.help # @ReservedAssignment if switch_info.list: help += T_("; may be given multiple times") if switch_info.mandatory: help += T_("; required") if switch_info.requires: help += T_("; requires {0}").format(", ".join( (("-" if len(switch) == 1 else "--") + switch) for switch in switch_info.requires)) if switch_info.excludes: help += T_("; excludes {0}").format(", ".join( (("-" if len(switch) == 1 else "--") + switch) for switch in switch_info.excludes)) msg = indentation.join( wrapper.wrap(" ".join(l.strip() for l in help.splitlines()))) if len(prefix) + wrapper.width >= cols: padding = indentation else: padding = " " * max(cols - wrapper.width - len(prefix) - 4, 1) print(description_indent.format(color | prefix, padding, color | msg)) if self._subcommands: gc = self.COLOR_GROUPS["Subcommands"] print(gc | T_("Sub-commands:")) for name, subcls in sorted(self._subcommands.items()): with gc: subapp = subcls.get() doc = subapp.DESCRIPTION if subapp.DESCRIPTION else getdoc( subapp) if self.SUBCOMMAND_HELPMSG: help = doc + "; " if doc else "" # @ReservedAssignment help += self.SUBCOMMAND_HELPMSG.format( parent=self.PROGNAME, sub=name) else: help = doc if doc else "" # @ReservedAssignment msg = indentation.join( wrapper.wrap(" ".join( l.strip() for l in help.splitlines()))) if len(name) + wrapper.width >= cols: padding = indentation else: padding = " " * max( cols - wrapper.width - len(name) - 4, 1) if colors.contains_colors(subcls.name): bodycolor = colors.extract(subcls.name) else: bodycolor = gc print(description_indent.format( subcls.name, padding, bodycolor | colors.filter(msg)))
def wrap_text(text, width): wrapper = TextWrapper(width=width, break_long_words=False, break_on_hyphens=False) return chain(*[wrapper.wrap(l) for l in text.split("\n")])
def __str__(self): if self.networks and len(self.networks) > 1: lines = ["Nexus dataset '%s' (#%s) with %d networks" % \ (self.sid, self.id, len(self.networks))] else: lines = ["Nexus dataset '%(sid)s' (#%(id)s)" % self.__dict__] lines.append("vertices/edges: %s" % self.vertices_edges) if self.name: lines.append("name: %s" % self.name) if self.tags: lines.append("tags: %s" % "; ".join(self.tags)) if self.rest: wrapper = TextWrapper(width=76, subsequent_indent=' ') keys = sorted(self.rest.iterkeys()) if "attribute" in self.rest: keys.remove("attribute") keys.append("attribute") for key in keys: for value in self.rest.getlist(key): paragraphs = str(value).splitlines() wrapper.initial_indent = "%s: " % key for paragraph in paragraphs: ls = wrapper.wrap(paragraph) if ls: lines.extend(wrapper.wrap(paragraph)) else: lines.append(" .") wrapper.initial_indent = " " return "\n".join(lines)