コード例 #1
0
    def __init__(self, lda_based_context):
        self.lda_based_context = lda_based_context
        self.doc =\
            Document(Constants.ITEM_TYPE + '-topic-models-nouns-complete')
        self.num_cols = 5
        self.num_topics = Constants.LDA_NUM_TOPICS
        self.rgb_tuples = None
        self.automatic_context_topic_colors = None
        self.keyword_context_topic_colors = None
        self.manual_context_topic_colors = None
        self.automatic_context_topic_ids = None
        self.keyword_context_topic_ids = None
        self.manual_context_topic_ids = None
        self.automatic_context_topic_words = None
        self.keyword_context_topic_words = None
        self.manual_context_topic_words = None
        self.headers = None
        self.topic_words_map = None
        self.table_format = '|c|' + 'c|' * (self.num_cols + 1)
        self.tagger = nltk.PerceptronTagger()
        self.tag_count_map = {'NN': 0, 'JJ': 0, 'VB': 0}

        self.init_colors()
        self.init_headers()
        self.init_topic_words()
        self.init_topic_ids()
        new_comm = UnsafeCommand(
            'newcommand', '\exampleCommand', options=4,
            extra_arguments=r'\colorbox[rgb]{#1,#2,#3}{#4} \color{black}')
        self.doc.append(new_comm)
        new_comm2 = UnsafeCommand('tiny')
        self.doc.append(new_comm2)
コード例 #2
0
    def addCustomCommands(self):
        EduEntry = UnsafeCommand('newcommand', r'\EducationEntry', options=1,
                                 extra_arguments=r"""
                            \fbox{\bf California Polytechnic State University}
                            \hfill
                             \fbox{\em September {#1} - Present}
                        """)

        BoldHeading = UnsafeCommand('newcommand', r'\BoldHeading', options=1,
                                    extra_arguments=r"""
                             \fbox{\bf{#1}}
                        """)

        FirstDatedEntry = UnsafeCommand('newcommand', r'\FirstDatedEntry', options=2,
                                        extra_arguments=r"""
                            \text\fbox{#1} 
                            \hfill
                            \fbox{\em{#2}}
                        """)

        DatedEntry = UnsafeCommand('newcommand', r'\DatedEntry', options=2,
                                   extra_arguments=r"""
                            \item\fbox{#1} 
                            \hfill
                            \fbox{\em{#2}}
                        """)

        self.doc.append(EduEntry)
        self.doc.append(BoldHeading)
        self.doc.append(DatedEntry)
        self.doc.append(FirstDatedEntry)
コード例 #3
0
 def addReferences(self, font, spacing, size, item_spacing):
     """
     This function can randomly insert a batch of references
     with randomly choiced font, size and line spacing
     """
     self.doc.append(UnsafeCommand('balance',
                                   packages=[Package('balance')]))
     item_spacing = str(spacing * float(item_spacing))
     item_spacing = item_spacing + 'ex'
     refs = self.getReferences(font)
     mode = random.choice([1, 2])
     with self.doc.create(SPACING(arguments=spacing)):
         self.doc.append(Command(size))
         if mode == 1:
             with self.doc.create(THEBIBLIOGRAPHY(arguments='99')):
                 self.doc.append(
                     UnsafeCommand('addtolength',
                                   '\itemsep',
                                   extra_arguments=item_spacing))
                 for ref in refs:
                     ref = '\\bibitem{ref}' + ref
                     self.doc.append(ref)
         else:
             i = 0
             with self.doc.create(Section('References', numbering=False)):
                 for ref in refs:
                     i += 1
                     ref = '{[}' + str(i) + '{]}' + ref
                     self.doc.append(NoEscape(ref))
     self.doc.append(Command('clearpage'))
コード例 #4
0
    def create_manual_context_topics(self):
        with self.doc.create(Section(
                Constants.ITEM_TYPE.title() +
                ' context-rich topic models (manual)')):

            with self.doc.create(Tabular(self.table_format)) as table:
                table.add_hline()
                table.add_row(self.headers, mapper=bold_mapper)
                table.add_hline()

                for topic in context_words[Constants.ITEM_TYPE]:
                    color_id = self.manual_context_topic_colors[topic]
                    color = self.rgb_tuples[color_id]
                    id_cell = str(topic)+str('|||')+str(color[0]) + \
                        '|||'+str(color[1])+'|||'+str(color[2])
                    row = [id_cell]
                    for word in list(context_words[Constants.ITEM_TYPE][topic])[:self.num_cols + 1]:
                        word_color = word+str('|||')+str(color[0])+'|||' + \
                            str(color[1])+'|||'+str(color[2])
                        row.append(word_color)
                    table.add_row(row, mapper=background_color_mapper)

                table.add_hline()

            self.doc.append(UnsafeCommand('par'))
            # self.doc.append(
            #     'Number of context-rich topics: %d' %
            #     len(context_words[Constants.ITEM_TYPE]))
            self.doc.append(ColorBoxCommand(
                arguments=Arguments(
                    1, 1, 1, 'Number of context-rich topics: ' +
                            str(len(context_words[Constants.ITEM_TYPE])))))
コード例 #5
0
def configuracoes_preambulo(doc):
    doc.preamble.append(
        Command('setmainfont', 'TeX Gyre Heros',
                ['Scale=0.9', 'Ligatures=TeX']))

    doc.preamble.append(Command(
        'MakeOuterQuote',
        '\"'))  # coverte aspas automaticamente, sem precisar de `` e ''

    # Diretório das imagens
    img_dir = '{}/base/static/img/'.format(
        BASE_DIR)  # necessário barra no final
    doc.preamble.append(UnsafeCommand('graphicspath',
                                      '{{{}}}'.format(img_dir)))

    # Configuração das listas
    # TODO: substituir por enumeration_symbol
    doc.preamble.append(
        NoEscape(r'''
\setlist[enumerate, 1]{label*=\textbf{\arabic*}, leftmargin=*}
\setlist[enumerate, 2]{label*=\textbf{.\arabic*}, leftmargin=*}
    '''))

    # Configuração dos cabeçalhos
    doc.preamble.append(Command('pagestyle', 'fancy'))
コード例 #6
0
 def __init__(self):
     with config.active.change(indent=True):
         self.doc = Document(documentclass='journal',
                             document_options='twocolumn',
                             geometry_options={
                                 "top": "2cm",
                                 "bottom": "2cm",
                                 "left": "2cm",
                                 "right": "2cm"
                             })
     self.doc.preamble.append(
         Command('DeclareUnicodeCharacter', 'FB00', extra_arguments='ff'))
     self.doc.preamble.append(
         Command('DeclareUnicodeCharacter', 'FB01', extra_arguments='fi'))
     self.doc.preamble.append(
         Command('DeclareUnicodeCharacter', 'FB02', extra_arguments='fl'))
     self.doc.preamble.append(
         Command('DeclareUnicodeCharacter', 'FF1A', extra_arguments=':'))
     self.doc.preamble.append(
         Command('DeclareUnicodeCharacter', '2212', extra_arguments='-'))
     self.doc.preamble.append(
         Command('DeclareUnicodeCharacter', '1', extra_arguments=' '))
     self.doc.preamble.append(
         Command('DeclareUnicodeCharacter', 'F8EF', extra_arguments=' '))
     self.doc.append(
         UnsafeCommand(
             'newcommand',
             '\myfont',
             extra_arguments=r'\textit{\textbf{\textsf{Fancy Text}}}'))
     self.doc.append(Command('pagestyle', 'plain'))
コード例 #7
0
ファイル: basic_green.py プロジェクト: shakyShaky123/scapp
def header_and_footer(doc, year, month1):
    #====================
    #  header and footer
    #====================
    insert_logo_command = Command("includegraphics", ruta + "bulletfiles/sgc2",
                                  "width=120px")
    # add fancy package
    doc.preamble.append(Command("usepackage", "fancyhdr"))

    # add left header (sgc logo)
    doc.preamble.append(Command("fancyhead", insert_logo_command, "L"))
    # add right header
    doc.preamble.append(
        Command("fancyhead", Command("small SERVICIO GEOLOGICO COLOMBIANO"),
                "R"))
    # add page style
    doc.preamble.append(Command("pagestyle", "fancy"))
    # add footer line
    doc.preamble.append(
        UnsafeCommand('renewcommand',
                      r'\footrulewidth',
                      extra_arguments='0.5pt'))
    # clear off all default fancyhdr footers
    doc.preamble.append(Command("fancyfoot", ""))
    # add left footer
    doc.preamble.append(
        Command(
            "fancyfoot",
            Command("textbf",
                    "Boletin de sismicidad %s %s" % (month1, str(year))), "L"))
    # add rigth footer
    doc.preamble.append(Command("fancyfoot", Command("thepage"),
                                "R"))  # \fancyfoot[R]{\thepage}
コード例 #8
0
ファイル: sitges.py プロジェクト: codingluke/cv_generator
 def _format_courses(self):
     if self.cv.courses and len(self.cv.courses) > 0:
         self.doc.append(Command('cvsidebarsection', _('SITGES_COURSES_TITLE')))
         for i, courses_item in enumerate(self.cv.courses):
             href_escaped = cv_generator.utils.escape_link(courses_item.diploma.href)
             anchor_escaped = pylatex.utils.escape_latex(courses_item.diploma.anchor)
             course_diploma = UnsafeCommand('href', [href_escaped, anchor_escaped])
             self.doc.append(
                 Command('courseitem', [courses_item.name, courses_item.institution, course_diploma])
             )
             if i < len(self.cv.languages) - 1:
                 self.doc.append(Command('medskip'))
コード例 #9
0
ファイル: sitges.py プロジェクト: codingluke/cv_generator
 def _format_publication_subtitle(self, publication_item):
     container = self.MultiCommandContainer()
     if publication_item.authors:
         container.append(publication_item.authors)
     if publication_item.manuscript_link:
         if len(container) > 0:
             container.append(Command('quad'))
             container.append(pylatex.NoEscape('\\,|\\,'))
             container.append(Command('quad'))
         href_escaped = cv_generator.utils.escape_link(publication_item.manuscript_link.href)
         anchor_escaped = pylatex.utils.escape_latex(publication_item.manuscript_link.anchor)
         container.append(Command('texttt', UnsafeCommand('href', [href_escaped, anchor_escaped])))
     if publication_item.code_link:
         if len(container) > 0:
             container.append(Command('quad'))
             container.append(pylatex.NoEscape('\\,|\\,'))
             container.append(Command('quad'))
         href_escaped = cv_generator.utils.escape_link(publication_item.code_link.href)
         anchor_escaped = pylatex.utils.escape_latex(publication_item.code_link.anchor)
         container.append(Command('texttt', UnsafeCommand('href', [href_escaped, anchor_escaped])))
     return container
コード例 #10
0
ファイル: helpme.py プロジェクト: buckbaskin/paPYrus
def myusual(doc):
    stuff(doc.preamble, NoEscape(r'\usepackage[english]{babel}'))
    stuff(doc.preamble, NoEscape(r'\usepackage[margin=0.69in]{geometry}'))

    for package in default_package_list:
        doc.preamble.append(Command('usepackage', package))

    stuff(doc.preamble, NoEscape(r'\definecolor{dkgreen}{rgb}{0, 0.6, 0}'))
    stuff(doc.preamble, NoEscape(r'\definecolor{gray}{rgb}{0.5, 0.5, 0.5}'))
    stuff(doc.preamble, NoEscape(r'\definecolor{mauve}{rgb}{0.58, 0, 0.82}'))
    stuff(doc.preamble, NoEscape(
'''\\lstset{frame=tb,
  language=Matlab,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\\small\\ttfamily},
  numbers=none,
  numberstyle=\\tiny\\color{gray},
  keywordstyle=\\color{blue},
  commentstyle=\\color{dkgreen},
  stringstyle=\\color{mauve},
  breaklines=true,
  breakatwhitespace=true,
  tabsize=3
}'''))

    '''
    UnsafeCommand('newcommand', '\exampleCommand', options=3,
                             extra_arguments=r'\color{#1} #2 #3 \color{black}')
    >>>
    \newcommand{\exampleCommand}[3]{\color{#1} #2 #3 \color{black}}%
    '''

    '''
        \DeclareMathOperator*{\argmax}{arg\,max}
        \DeclareMathOperator*{\argmin}{arg\,min}
    '''
    doc.preamble.append(UnsafeCommand('DeclareMathOperator*', arguments=(r'\argmax', r'arg\,max')))
    doc.preamble.append(UnsafeCommand('DeclareMathOperator*', arguments=(r'\argmin', r'arg\,min')))

    doc.preamble.append(UnsafeCommand('newcommand', '\subsubsubsection', extra_arguments=('\paragraph',)))

    doc.preamble.append(UnsafeCommand('newcommand', r'\bbs', options=1, extra_arguments=('\section{#1}',)))
    doc.preamble.append(UnsafeCommand('newcommand', r'\bbbs', options=1, extra_arguments=('\subsection{#1}',)))
    doc.preamble.append(UnsafeCommand('newcommand', r'\bbbbs', options=1, extra_arguments=('\subsubsection{#1}',)))
    doc.preamble.append(UnsafeCommand('newcommand', r'\bbbbbs', options=1, extra_arguments=('\subsubsubsection{#1}',)))
    doc.preamble.append(UnsafeCommand('newcommand', r'\norm', options=1, extra_arguments=(r'\left\lVert#1\right\rVert',)))
コード例 #11
0
def generate_symbols(container, trackers):

    legend = StyleManager.default().legend(Tracker)

    container.append(Command("makeatletter"))
    for tracker in trackers:
        container.append(
            UnsafeCommand('DefineTracker', [tracker.reference, TRACKER_GROUP],
                          extra_arguments=insert_mplfigure(
                              legend.figure(tracker), False) +
                          r' \replunderscores{%s}' % tracker.label))

    container.append(Command("makeatother"))
コード例 #12
0
ファイル: sitges.py プロジェクト: codingluke/cv_generator
 def _format_award_subtitle(self, award_item):
     container = self.MultiCommandContainer()
     container.append(award_item.date.strftime('%B %Y'))
     container.append(Command('quad'))
     container.append('|')
     container.append(Command('quad'))
     container.append(award_item.institution)
     if award_item.diploma is not None:
         href_escaped = cv_generator.utils.escape_link(award_item.diploma.href)
         anchor_escaped = pylatex.utils.escape_latex(award_item.diploma.anchor)
         container.append(Command('quad'))
         container.append(pylatex.NoEscape('\\,|\\,'))
         container.append(Command('quad'))
         container.append(Command('texttt', UnsafeCommand('href', [href_escaped, anchor_escaped])))
     return container
コード例 #13
0
def generate_style(schema: PLDSchema, locale: LocaleDictionary,
                   document: Document) -> Document:
    document.preamble.append(
        UnsafeCommand("newcommand",
                      Command("rowWidth"),
                      extra_arguments=NoEscape("\\linewidth-(\\tabcolsep*2)")))
    document.preamble.append(
        Command('renewcommand',
                NoEscape('\\familydefault'),
                extra_arguments=NoEscape('\\sfdefault')))
    document.preamble.append(
        Command("graphicspath", NoEscape("{assets/}{../assets/}")))
    header = PageStyle("header")
    with header.create(Head("L")) as left_header:
        left_header: Head
        left_header.create(
            StandAloneGraphic("primary_logo.pdf", NoEscape("width=30pt")))
    with header.create(Head("R")) as right_header:
        right_header: Head
        right_header.append(LargeText(locale.project_log_document))
    with header.create(Foot("R")) as right_footer:
        right_footer: Foot
        right_footer.append(
            NoEscape(
                f"{locale.page} \\thepage\\ {locale.of} \\pageref{{LastPage}}")
        )
    with header.create(Foot("L")) as left_footer:
        left_footer: Foot
        left_footer.append(
            StandAloneGraphic("secondary_logo.pdf", NoEscape("width=100pt")))
    document.preamble.append(
        Command(
            "title",
            NoEscape(
                StandAloneGraphic("primary_logo.pdf", NoEscape(
                    "width=100pt")).dumps() + "~\\\\[1cm]\n" +
                locale.project_log_document)))
    now = datetime.date.today()
    document.preamble.append(
        Command("date", f"{now.day}/{now.month}/{now.year}"))
    document.preamble.append(
        Command("author", NoEscape("\\and ".join(schema.authors))))
    document.preamble.append(header)
    document.change_document_style("header")

    return document
コード例 #14
0
    def create_automatic_context_topics(self):

        with self.doc.create(
                Section(Constants.ITEM_TYPE.title() +
                        ' context-rich topic models (automatic)')):
            num_context_topics = len(
                self.lda_based_context.context_rich_topics)

            with self.doc.create(LongTabu(self.table_format)) as table:
                table.add_hline()
                table.add_row(self.headers, mapper=bold_mapper)
                table.add_hline()

                for topic in self.lda_based_context.context_rich_topics:
                    topic_id = topic[0]
                    ratio = topic[1]
                    color_id = self.automatic_context_topic_colors[topic_id]
                    color = self.rgb_tuples[color_id]
                    id_cell = str(topic_id) + str('|||') + str(color[0]) + \
                        '|||' + str(color[1]) + '|||' + str(color[2])
                    ratio_cell = str(ratio) + str('|||') + str(color[0]) + \
                        '|||' + str(color[1]) + '|||' + str(color[2])
                    row = [id_cell, ratio_cell]
                    # row = [str(topic_id + 1)]
                    topic_words =\
                        self.lda_based_context.print_topic(
                            topic_id, self.num_cols).split(' + ')
                    for word in topic_words:
                        word_color = word + str('|||') + str(color[0]) +\
                                     '|||' + str(color[1]) + '|||' +\
                                     str(color[2])
                        row.append(word_color)
                    # row.extend(topic_words)
                    table.add_row(row, mapper=background_color_mapper)

                table.add_hline()

            self.doc.append(UnsafeCommand('par'))
            self.doc.append('Number of context-rich topics: %d' %
                            num_context_topics)
コード例 #15
0
ファイル: generate.py プロジェクト: loelkes/InvoiceTool
 def fill_document(self):
     self.doc.append(
         Command('begin',
                 arguments='letter',
                 extra_arguments=self.client.getaddress()))
     self.doc.append(Command('opening', ' '))
     self.doc.append(UnsafeCommand('vspace', '-1.0cm'))
     self.doc.append(Command('STautoround*', '2'))  # Round 2 decimals
     self.doc.append(Command('STsetdecimalsep',
                             ','))  # Decimal separator sign
     self.doc.append(NoEscape(self.statictext['tdef']))  # Table definition
     self.doc.append(NoEscape(self.statictext['thead']))  # Table head
     self.doc.append(NoEscape(self.statictext['temptyrow']))  # Empty row
     self.additems()  # All the items
     self.doc.append(NoEscape(self.statictext['tsep']))  # Seperator row
     self.doc.append(NoEscape(self.statictext['tsum']))  # Sum of all items
     if self.discount != 0:
         self.doc.append(NoEscape(self.statictext['tdiscount']))
     self.doc.append(NoEscape(self.statictext['tvat']))  # VAT
     self.doc.append(NoEscape(
         self.statictext['ttotal']))  # Total = VAT + sum
     self.doc.append(Command('end', 'spreadtab'))  # End of table
     self.doc.append(Command('end', 'letter'))  # End of document
コード例 #16
0
ファイル: export.py プロジェクト: ShipFlyFish/LConvNet
def get_latex_table_type2(
    doc,
    results=None,
    dataset_name=CIFAR10Repr,
    config_names=["Clean", "PGD", "FGSM"],
    eps="0.1411764706",
):
    arch_names = ["Small", "Large"]
    method_names = ["KW", "BCOP"]
    num_archs = len(arch_names)
    num_methods = len(method_names)
    fmt = "l" + "c" * num_methods
    num_cols = 1 + num_methods
    with doc.create(Tabularx(fmt)) as data_table:
        headers = tuple(
            map(lambda x: NoEscape(boldify(x)), ("", ) + tuple(method_names)))
        data_table.add_row(headers)
        cmidrule(data_table, 1, num_cols)
        for i, arch_name in enumerate(arch_names):
            data_table.add_row((arch_name, ) + ("", ) * num_methods)
            data_table.append(
                UnsafeCommand("cmidrule", "{}-{}".format(1, num_cols)))
            for j, config_name in enumerate(config_names):
                row = (config_name, )
                row += populate_numbers([
                    results[(
                        dataset_name,
                        arch_name,
                        method_name,
                        None,
                        config_name,
                        eps,
                    )] for method_name in method_names
                ])
                data_table.add_row(row)
            if i != num_archs - 1:
                cmidrule(data_table, 1, num_cols)
コード例 #17
0
def wrap_table_in_latex_document(table: str,
                                 landscape: bool = False,
                                 margin: float = 1.5) -> str:
    """
    Wraps a table inside a proper latex document.

    Uses ``\\longtable`` instead of ``\\tabular`` to fit data on multiple pages.

    Args:
        table: table string to wrap the document around
        landscape: whether to layout the table in landscape mode
        margin: margin around the table in cm

    Returns:
        the resulting latex document as a string
    """
    doc = Document(documentclass="scrbook",
                   document_options="paper=a4",
                   geometry_options={
                       "margin": f"{margin}cm",
                       "landscape": "true" if landscape else "false"
                   })
    # set monospace font
    monospace_comm = UnsafeCommand('renewcommand',
                                   r'\familydefault',
                                   extra_arguments=r'\ttdefault')
    doc.preamble.append(monospace_comm)

    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('booktabs'))

    doc.change_document_style("empty")

    # embed latex table inside document
    doc.append(NoEscape(table))

    return tp.cast(str, doc.dumps())
コード例 #18
0
    def create_keyword_context_topics(self):
        with self.doc.create(Section(
                Constants.ITEM_TYPE.title() +
                ' context-rich topic models (keyword)')):

            num_context_topics = 0

            with self.doc.create(Tabular(self.table_format)) as table:
                table.add_hline()
                table.add_row(self.headers, mapper=bold_mapper)
                table.add_hline()

                for topic_id in range(self.num_topics):
                    topic_score = split_topic(
                        self.lda_based_context.topic_model.print_topic(
                            topic_id, topn=self.num_cols))
                    if topic_score['score'] > 0:
                        color_id = self.keyword_context_topic_colors[topic_id]
                        color = self.rgb_tuples[color_id]
                        id_cell = str(topic_id)+str('|||')+str(color[0]) + \
                            '|||'+str(color[1])+'|||'+str(color[2])
                        row = [id_cell]
                        for column_index in range(self.num_cols):
                            word = topic_score['word' + str(column_index)]
                            word_color = word+str('|||')+str(color[0])+'|||' + \
                                str(color[1])+'|||'+str(color[2])
                            row.append(word_color)
                        table.add_row(row, mapper=background_color_mapper)

                        num_context_topics += 1

                table.add_hline()

            self.doc.append(UnsafeCommand('par'))
            self.doc.append(
                'Number of context-rich topics: %d' % num_context_topics)
コード例 #19
0
ファイル: report.py プロジェクト: dioph/elegant
def latex_report(system, curves, grid, filename):
    lines = system.lines
    trafos = system.trafos
    buses = system.buses
    geometry_options = {"tmargin": "1cm",
                        "lmargin": "1cm",
                        "rmargin": "1cm",
                        "bmargin": "1cm",
                        "includeheadfoot": True}
    doc = Document(page_numbers=True, geometry_options=geometry_options)
    doc.preamble.append(Command('usepackage', 'cmbright'))
    doc.preamble.append(Command('usepackage', 'tikz'))
    doc.preamble.append(Command('usepackage', 'amsmath'))
    doc.preamble.append(Command('usepackage', 'graphicx'))
    now = datetime.datetime.now()
    doc.append(f'Report auto-generated by Elegant at '
               f'{now.day:02d}/{now.month:02d}/{now.year:02d} '
               f'{now.hour:02d}:{now.minute:02d}:{now.second:02d}')
    wye_comm = UnsafeCommand(
        'newcommand', '\\wye',
        extra_arguments=r'\mathbin{\text{\begin{tikzpicture}'
                        r'[x=1pt, y=1pt, scale=2]'
                        r'\draw '
                        r'(-0.9, 0) -- (0.9, 0) '
                        r'(-0.6, -0.5) -- (0.6, -0.5) '
                        r'(-0.3, -1) -- (0.3, -1) '
                        r'(0, 0) -- ++(0, 1.5) -- ++(1.2, 0) coordinate (tmp)'
                        r'-- +(0, -2) '
                        r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;'
                        r'\end{tikzpicture}}}'
    )
    why_comm = UnsafeCommand(
        'newcommand', '\\why',
        extra_arguments=r'\mathbin{\text{\begin{tikzpicture}'
                        r'[x=1pt, y=1pt, scale=2]'
                        r'\draw '
                        r'(1.2, 1.5) coordinate (tmp)'
                        r'-- +(0, -2) '
                        r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;'
                        r'\end{tikzpicture}}}'
    )
    doc.append(wye_comm)
    doc.append(why_comm)
    doc.add_color(name="lightgray", model="gray", description="0.80")
    with doc.create(Section('Buses')):
        with doc.create(Subsection('Load-Flow Solution')):
            with doc.create(LongTable('c|ccccccc')) as tbl:
                tbl.add_hline()
                tbl.add_row(('Bus', NoEscape('$|V|$ (pu)'), NoEscape('$\\delta$ (deg)'),
                             NoEscape('$P_G$ (MW)'), NoEscape('$Q_G$ (Mvar)'),
                             NoEscape('$P_L$ (MW)'), NoEscape('$Q_L$ (Mvar)'),
                             NoEscape('$Z_L$ (pu)')))
                tbl.add_hline()
                tbl.end_table_header()
                tbl.add_hline()
                tbl.add_row((MultiColumn(8, align='r', data='Continued on Next Page'),))
                tbl.add_hline()
                tbl.end_table_footer()
                tbl.add_hline()
                tbl.end_table_last_footer()

                for i, b in enumerate(buses):
                    if i % 2 == 0:
                        color = 'lightgray'
                    else:
                        color = None
                    tbl.add_row((b.bus_id + 1,
                                 NoEscape('{:.04f}'.format(b.v)),
                                 NoEscape('${:.02f}$'.format(b.delta * 180 / np.pi)),
                                 NoEscape('{:.02f}'.format(b.pg * 100)),
                                 NoEscape('{:.02f}'.format(b.qg * 100)),
                                 NoEscape('{:.02f}'.format(b.pl * 100)),
                                 NoEscape('{:.02f}'.format(b.ql * 100)),
                                 safe_repr(b.Z)),
                                color=color)
        with doc.create(Subsection('Fault Calculations')):
            with doc.create(LongTable('c|cccccccccc')) as tbl:
                tbl.add_hline()
                tbl.add_row((MultiRow(2, data='Bus'),
                             MultiColumn(2, align='c', data=NoEscape('TPG')),
                             MultiColumn(2, align='c', data=NoEscape('SLG')),
                             MultiColumn(4, align='c', data=NoEscape('DLG')),
                             MultiColumn(2, align='c', data=NoEscape('LL'))))
                tbl.add_hline(2, 11)
                tbl.add_row(('', NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'),
                             NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'),
                             NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)'),
                             NoEscape('$I_C$ (pu)'), NoEscape('$\\delta_C$ (deg)'),
                             NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)')))
                tbl.add_hline()
                tbl.end_table_header()
                tbl.add_hline()
                tbl.add_row((MultiColumn(11, align='r', data='Continued on Next Page'),))
                tbl.add_hline()
                tbl.end_table_footer()
                tbl.add_hline()
                tbl.end_table_last_footer()

                for i, b in enumerate(buses):
                    if i % 2 == 0:
                        color = 'lightgray'
                    else:
                        color = None
                    tbl.add_row((b.bus_id + 1,
                                 safe_repr(np.abs(b.iTPG)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iTPG) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iSLG)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iSLG) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iDLGb)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iDLGb) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iDLGc)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iDLGc) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iLL)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iLL) * 180 / np.pi))),
                                color=color)
    with doc.create(Section('Lines')):
        with doc.create(LongTable('c|cccccccc')) as tbl:
            tbl.add_hline()
            tbl.add_row((MultiRow(2, data='Line'),
                         MultiColumn(3, align='c', data='Parametrization'),
                         MultiColumn(2, align='c', data='Loss'),
                         MultiColumn(3, align='c', data='Flow')))
            tbl.add_hline(2, 9)
            tbl.add_row(('', NoEscape('$R$ (\\%pu)'), NoEscape('$X_L$ (\\%pu)'),
                         NoEscape('$B_C$ (\\%pu)'), NoEscape('$P_{loss}$ (MW)'),
                         NoEscape('$Q_{loss}$ (Mvar)'), NoEscape('$P$ (MW)'),
                         NoEscape('$Q$ (Mvar)'), NoEscape('$I/I_{max}$ (\\%)')))
            tbl.add_hline()
            tbl.end_table_header()
            tbl.add_hline()
            tbl.add_row((MultiColumn(9, align='r', data='Continued on Next Page'),))
            tbl.add_hline()
            tbl.end_table_footer()
            tbl.add_hline()
            tbl.end_table_last_footer()

            for i, lt in enumerate(lines):
                if i % 2 == 0:
                    color = 'lightgray'
                else:
                    color = None
                tbl.add_row((NoEscape('{} -- {}'.format(lt.orig.bus_id + 1, lt.dest.bus_id + 1)),
                             NoEscape('{:.04f}'.format(lt.Zpu.real * 100)),
                             NoEscape('{:.04f}'.format(lt.Zpu.imag * 100)),
                             NoEscape('{:.04f}'.format(lt.Ypu.imag * 100)),
                             NoEscape('{:.02f}'.format(lt.Sper.real * 100)),
                             NoEscape('{:.02f}'.format(lt.Sper.imag * 100)),
                             NoEscape('{:.02f}'.format(lt.S2.real * 100)),
                             NoEscape('{:.02f}'.format(lt.S2.imag * 100)),
                             NoEscape('{:.02f}'.format(np.abs(lt.Ia) / lt.imax * 100))),
                            color=color)
    with doc.create(Section('Trafos')):
        with doc.create(LongTable('c|ccccccc')) as tbl:
            tbl.add_hline()
            tbl.add_row((MultiRow(2, data='Trafo'),
                         MultiColumn(3, align='c', data='Parametrization'),
                         MultiColumn(1, align='c', data='Loss'),
                         MultiColumn(3, align='c', data='Flow')))
            tbl.add_hline(2, 8)
            tbl.add_row(('', NoEscape('$x^+$ (\\%pu)'), NoEscape('$x^0$ (\\%pu)'),
                         'Configuration', NoEscape('$Q_{loss}$ (Mvar)'),
                         NoEscape('$P$ (MW)'), NoEscape('$Q$ (Mvar)'), NoEscape('$S/S_N$ (\\%)')))
            tbl.add_hline()
            tbl.end_table_header()
            tbl.add_hline()
            tbl.add_row((MultiColumn(8, align='r', data='Continued on Next Page'),))
            tbl.add_hline()
            tbl.end_table_footer()
            tbl.add_hline()
            tbl.end_table_last_footer()

            for i, tr in enumerate(trafos):
                if i % 2 == 0:
                    color = 'lightgray'
                else:
                    color = None
                tbl.add_row((NoEscape('{} -- {}'.format(tr.orig.bus_id + 1, tr.dest.bus_id + 1)),
                             NoEscape('{:.02f}'.format(tr.Z1.imag * 100)),
                             NoEscape('{:.02f}'.format(tr.Z0.imag * 100)),
                             get_scheme(tr),
                             NoEscape('{:.02f}'.format(tr.Sper.imag * 100)),
                             NoEscape('{:.02f}'.format(tr.S2.real * 100)),
                             NoEscape('{:.02f}'.format(tr.S2.imag * 100)),
                             NoEscape('{:.02f}'.format(np.abs(tr.S2) * 1e8 / tr.snom * 100))),
                            color=color)

    filepath = filename.strip('.pdf')
    make_system_schematic(curves, grid, initial_fontsize=9)
    doc.append(NewPage())
    with doc.create(Section('System')):
        with doc.create(Figure(position='h')) as system_pic:
            system_pic.add_plot(bbox_inches='tight', width=NoEscape('\\textwidth'))
    doc.generate_pdf(filepath, clean_tex=True, compiler='latexmk', compiler_args=['-pdf'])
コード例 #20
0
def generate_latex_document(trackers: List[Tracker],
                            sequences: List[Sequence],
                            results,
                            storage: Storage,
                            build=False,
                            multipart=True):

    order_marks = {1: "first", 2: "second", 3: "third"}

    def format_cell(value, order):
        cell = format_value(value)
        if order in order_marks:
            cell = Command(order_marks[order], cell)
        return cell

    logger = logging.getLogger("vot")

    table_header, table_data, table_order = extract_measures_table(
        trackers, results)
    plots = extract_plots(trackers, results)

    doc = Document(page_numbers=True)

    doc.preamble.append(Package('pgf'))
    doc.preamble.append(Package('xcolor'))
    doc.preamble.append(Package('fullpage'))

    doc.preamble.append(NoEscape(read_resource("commands.tex")))

    doc.preamble.append(
        UnsafeCommand('newcommand',
                      r'\first',
                      options=1,
                      extra_arguments=r'{\color{red} #1 }'))
    doc.preamble.append(
        UnsafeCommand('newcommand',
                      r'\second',
                      options=1,
                      extra_arguments=r'{\color{green} #1 }'))
    doc.preamble.append(
        UnsafeCommand('newcommand',
                      r'\third',
                      options=1,
                      extra_arguments=r'{\color{blue} #1 }'))

    if multipart:
        container = Chunk()
        generate_symbols(container, trackers)
        with storage.write("symbols.tex") as out:
            container.dump(out)
        doc.preamble.append(Command("input", "symbols.tex"))
    else:
        generate_symbols(doc.preamble, trackers)

    doc.preamble.append(Command('title', 'VOT report'))
    doc.preamble.append(
        Command('author', 'Toolkit version ' + toolkit_version()))
    doc.preamble.append(Command('date', datetime.datetime.now().isoformat()))
    doc.append(NoEscape(r'\maketitle'))

    if len(table_header[2]) == 0:
        logger.debug("No measures found, skipping table")
    else:

        # Generate data table
        with doc.create(LongTable("l " *
                                  (len(table_header[2]) + 1))) as data_table:
            data_table.add_hline()
            data_table.add_row([" "] + [
                MultiColumn(c[1], data=c[0].identifier)
                for c in merge_repeats(table_header[0])
            ])
            data_table.add_hline()
            data_table.add_row([" "] + [
                MultiColumn(c[1], data=c[0].title)
                for c in merge_repeats(table_header[1])
            ])
            data_table.add_hline()
            data_table.add_row(
                ["Tracker"] +
                [" " + c.abbreviation + " " for c in table_header[2]])
            data_table.add_hline()
            data_table.end_table_header()
            data_table.add_hline()

            for tracker, data in table_data.items():
                data_table.add_row([
                    UnsafeCommand("Tracker",
                                  [tracker.reference, TRACKER_GROUP])
                ] + [
                    format_cell(x,
                                order[tracker] if not order is None else None)
                    for x, order in zip(data, table_order)
                ])

    for experiment, experiment_plots in plots.items():
        if len(experiment_plots) == 0:
            continue

        doc.append(Section("Experiment " + experiment.identifier))

        for title, plot in experiment_plots:

            with doc.create(Figure(position='htbp')) as container:
                if multipart:
                    plot_name = plot.identifier + ".pdf"
                    with storage.write(plot_name, binary=True) as out:
                        plot.save(out, "PDF")
                    container.add_image(plot_name)
                else:
                    container.append(insert_figure(plot))
                container.add_caption(title)

    if build:
        temp = tempfile.mktemp()
        logger.debug("Generating to tempourary output %s", temp)
        doc.generate_pdf(temp, clean_tex=True)
        storage.copy(temp + ".pdf", "report.pdf")
    else:
        with storage.write("report.tex") as out:
            doc.dump(out)
コード例 #21
0
    def set_up(self):
        """Add packages, set preliminary settings for this doc."""
        # Add packages
        self.preamble.append(NoEscape(r'\usepackage[noprint,1to1]{booklet}'))
        self.preamble.append(Package('titlesec'))
        self.preamble.append(Package('pdfpages'))
        self.preamble.append(Package('makeidx'))
        self.preamble.append(Package('hyperref'))
        self.preamble.append(Package('graphicx'))
        self.preamble.append(Package('afterpage'))

        self.preamble.append(NoEscape(r'\graphicspath{ {resources/} }'))

        self.preamble.append(NoEscape(r'\source{\magstep0}{5.5in}{8.5in}'))
        self.preamble.append(NoEscape(r'\target{\magstep0}{11in}{8.5in}'))
        self.preamble.append(NoEscape(r'\setpdftargetpages'))

        self.preamble.append(
            NoEscape(r'\setulmarginsandblock{1.65cm}{1.65cm}{*}'))
        self.preamble.append(NoEscape(r'\setlrmarginsandblock{1cm}{1cm}{*}'))
        self.preamble.append(NoEscape(r'\checkandfixthelayout'))

        ### Custom commands

        # Use sections so that we can easily generate a TOC... but make them
        # invisible to keep things pretty.
        invis_section = UnsafeCommand(
            'newcommand',
            '\invisiblesection',
            options=1,
            extra_arguments=r'\refstepcounter{section}'
            r'\sectionmark{#1}'
            r'\addcontentsline{toc}{section}{#1}')
        self.append(invis_section)

        add_song = UnsafeCommand(
            'newcommand',
            '\song',
            options=2,
            extra_arguments=r'\invisiblesection{#1}'
            r'\includepdf[pages={1-},pagecommand=\thispagestyle{plain}]{#2}')
        self.append(add_song)

        blank_page = UnsafeCommand('newcommand',
                                   '\\blankpage',
                                   extra_arguments=r'\clearpage'
                                   r'\begingroup'
                                   r'\null'
                                   r'\thispagestyle{empty}'
                                   r'\addtocounter{page}{-1}'
                                   r'\hypersetup{pageanchor=false}'
                                   r'\clearpage'
                                   r'\endgroup')
        self.append(blank_page)

        # So we can change margins for a single page at a time
        self.preamble.append(
            NoEscape(r'''
\newenvironment{changemargin}[2]{%
\begin{list}{}{%
\setlength{\topsep}{0pt}%
\setlength{\leftmargin}{#1}%
\setlength{\rightmargin}{#2}%
\setlength{\listparindent}{\parindent}%
\setlength{\itemindent}{\parindent}%
\setlength{\parsep}{\parskip}%
}%
\item[]}{\end{list}}
        '''))

        # Ignore chapter numbering in order for section numbering to be reasonable
        self.preamble.append(
            NoEscape(r'\renewcommand{\thesection}{\arabic{section}}'))

        # Title Info
        self.preamble.append(Command('title', 'Christmas Carols'))
        self.preamble.append(Command('author', 'compiled by Maia McCormick'))
        self.preamble.append(Command('date', NoEscape(r'\today')))

        # Ignore page numbers until we get to the actual body
        self.append(NoEscape(r'\pagenumbering{gobble}'))

        # Silly cover image (will be in 'resources/coverImg.xxx')
        coverImg = r"""
            \begin{figure}[h]
            \vspace{3.0cm}
            \includegraphics[width=\textwidth]{coverImg}
            \centering
            \end{figure}
        """

        self.append(NoEscape(r'\begin{changemargin}{1.5cm}{1.5cm}'))
        self.append(NoEscape(r'\maketitle'))
        self.append(NoEscape(coverImg))
        self.append(NoEscape(r'\clearpage'))
        self.append(NoEscape(r'\tableofcontents'))
        self.append(NoEscape(r'\end{changemargin}'))
        self.append(NoEscape(r'\clearpage'))
        self.append(NoEscape(
            r'\blankpage'))  # need this so the 2pg carols are on facing pages

        # Okay, show page numbers again
        self.append(NoEscape(r'\pagenumbering{arabic}'))
コード例 #22
0
    _latex_name = 'exampleCommand'
    packages = [Package('color')]


# Create a new document
doc = Document()
with doc.create(Section('Custom commands')):
    doc.append(
        NoEscape(r"""
        The following is a demonstration of a custom \LaTeX{}
        command with a couple of parameters.
        """))

    # Define the new command
    new_comm = UnsafeCommand('newcommand',
                             '\exampleCommand',
                             options=3,
                             extra_arguments=r'\color{#1} #2 #3 \color{black}')
    doc.append(new_comm)

    # Use our newly created command with different arguments
    doc.append(ExampleCommand(arguments=Arguments('blue', 'Hello', 'World!')))
    doc.append(ExampleCommand(arguments=Arguments('green', 'Hello', 'World!')))
    doc.append(ExampleCommand(arguments=Arguments('red', 'Hello', 'World!')))

with doc.create(Section('Custom environments')):
    doc.append(
        NoEscape(r"""
        The following is a demonstration of a custom \LaTeX{}
        environment using the mdframed package.
        """))
コード例 #23
0
ファイル: pdfs.py プロジェクト: yssmcl/fly
def gerar_pdf_certificado(certificado):

    # Configurações da classe
    geometry_options = {'landscape': True,
                        'left': '2cm',
                        'right': '1cm'}
    doc = Document(geometry_options=geometry_options, lmodern=False, document_options=['a4paper', 'brazil'],
                   inputenc=None, fontenc=None, font_size='footnotesize')

    # Pacotes
    doc.packages.add(Package('microtype'))
    doc.packages.add(Package('indentfirst'))
    doc.packages.add(Package('graphicx'))
    doc.packages.add(Package('calc'))
    doc.packages.add(Package('fontspec'))
    options_background = ['scale=1',
                          'opacity=1',
                          'angle=0']
    doc.packages.add(Package('background', options=options_background))
    doc.packages.add(Package('csquotes'))

    # Configurações (preâmbulo)
    doc.preamble.append(Command('MakeOuterQuote', '\"'))  # coverte aspas automaticamente, sem precisar de `` e ''
    doc.preamble.append(Command('renewcommand', arguments=[Command('baselinestretch'), '1.5']))
    doc.preamble.append(Command('setlength', arguments=[Command('parindent'), NoEscape(r'.35\textwidth')]))
    doc.preamble.append(Command('setlength', arguments=[Command('parskip'), '0.2cm']))
    doc.preamble.append(Command('setlength', arguments=[Command('emergencystretch'), '5pt']))

    # Imagem de fundo
    doc.preamble.append(NoEscape(r'\backgroundsetup{ contents=\includegraphics{modelo-certificado-20.pdf} }'))

    # Diretório das imagens
    img_dir = '{}/base/static/img/'.format(BASE_DIR)  # necessário barra no final
    doc.preamble.append(UnsafeCommand('graphicspath', '{{{}}}'.format(img_dir)))

    # Início do documento
    doc.append(UnsafeCommand('setmainfont', 'Latin Modern Sans', ['SizeFeatures={Size=16}', 'Ligatures=TeX']))

    doc.append(Command('pagestyle', 'empty'))
    doc.append(Command('BgThispage'))

    doc.append(VerticalSpace(size='2cm', star=True))

    with doc.create(FlushRight()) as fr:
        fr.append(StandAloneGraphic('titulo-certificado.pdf', 'width=6.5cm'))
        fr.append(LineBreak())

    doc.append(VerticalSpace(size=NoEscape('-1cm'), star=True))
    doc.append(Command('Large'))

    # Usado para o nome dos meses ('%B')
    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

    inicio = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower()
    fim = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower()
    # TODO: tá faltando coisa
    texto_principal = r'''

    Certificamos que \textbf{{{nome}}} atuou como {funcao}, {sob_coordenacao}no período de {inicio} a {fim}, na cidade de Foz do Iguaçu -- Paraná, com a atividade de extensão: "\textbf{{{titulo}}}", com carga horária de {carga_horaria_total} horas.

    '''

    if certificado.funcao.nome == 'Coordenador(a)':
        sob_coordenacao = ''
    else:
        nome_coordenador = certificado.relatorio.projeto_extensao.coordenador.nome_completo
        sob_coordenacao = r'sob a coordenação de \textbf{{{}}}, '.format(escape_latex(nome_coordenador))

    texto_principal = texto_principal.format(nome=escape_latex(certificado.nome),
                                             funcao=certificado.funcao.nome.lower(),
                                             sob_coordenacao=sob_coordenacao,
                                             inicio=inicio,
                                             fim=fim,
                                             titulo=escape_latex(certificado.relatorio.projeto_extensao.titulo),
                                             carga_horaria_total=str(certificado.carga_horaria_total).split('.')[0])

    # texto_principal = NoEscape(r'''

    # Certificamos que \textbf{Adriana de Oliveira Gomes} participou como bolsista do Programa de Apoio a Inclusão Social em Atividades de Extensão -- Convênio No 750/2014 -- Fundação Araucária, Edital 05/2014-PROEX, sob a orientação do (a) professor (a) \textbf{Fernando Amâncio Aragão}, no período de outubro/2014 a setembro/2015, com a atividade de extensão: \textbf{''Atendimento fisioterapêutico para pacientes com sequelas neurológicas baseada em tarefas funcionais.''}, com carga horária de 960 (novecentas e sessenta) horas.

    # ''')

    doc.append(NoEscape(texto_principal))

    doc.append(VerticalSpace(size='1.5cm', star=True))

    doc.append(HorizontalSpace(size='7cm', star=True))
    dia = timezone.now().strftime('%d')
    mes = timezone.now().strftime('%B')
    ano = timezone.now().strftime('%Y')

    data = NoEscape(r'Foz do Iguaçu, {} de {} de {}'.format(dia, mes, ano))
    largura = Command('widthof', data).dumps()
    with doc.create(MiniPage(width=largura)) as mini:
        with mini.create(Center()) as center:
            center.append(data)
            center.append(NewLine())
            center.append(NewLine())
            center.append(NewLine())
            center.append('Coordenador do Projeto de Extensão')
            center.append(NewLine())
            center.append(NewLine())
            center.append(NewLine())
            center.append('Diretor de Centro')

    os.system('mkdir -p ' + PDF_DIR)

    filepath = '{}/certificado_{}'.format(PDF_DIR, str(certificado.id))
    doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS)

    return filepath
コード例 #24
0
ファイル: export.py プロジェクト: ShipFlyFish/LConvNet
def cmidrule(table, start, end):
    table.append(UnsafeCommand("cmidrule", "{}-{}".format(start, end)))
コード例 #25
0
def tabela_previsao_orcamentaria(doc, enum, previsao_orcamentaria):
    item(doc, enum, NoEscape(r'PREVISÃO ORÇAMENTÁRIA: \\'))

    # TODO: blank=True para os DecimalField
    inscricoes = previsao_orcamentaria.inscricoes or 0
    convenios = previsao_orcamentaria.convenios or 0
    patrocinios = previsao_orcamentaria.patrocinios or 0
    fonte_financiamento = previsao_orcamentaria.fonte_financiamento or 0
    honorarios = previsao_orcamentaria.honorarios or 0
    passagens = previsao_orcamentaria.passagens or 0
    alimentacao = previsao_orcamentaria.alimentacao or 0
    hospedagem = previsao_orcamentaria.hospedagem or 0
    divulgacao = previsao_orcamentaria.divulgacao or 0
    material_consumo = previsao_orcamentaria.material_consumo or 0
    xerox = previsao_orcamentaria.xerox or 0
    certificados = previsao_orcamentaria.certificados or 0
    outros = previsao_orcamentaria.outros or 0
    outros_especificacao = previsao_orcamentaria.outros_especificacao or ''
    # TODO: não estão sendo usadas
    # fundacao           = previsao_orcamentaria.fundacao or ''
    # outro_orgao_gestor = previsao_orcamentaria.outro_orgao_gestor or ''

    total_receitas = (inscricoes + convenios + patrocinios +
                      fonte_financiamento)

    total_despesas = (honorarios + passagens + alimentacao + hospedagem +
                      divulgacao + material_consumo + xerox + certificados +
                      outros)

    with doc.create(Tabularx('|' + 'X|' * 4,
                             width_argument=WIDTH_ARGUMENT)) as tab:
        tab.add_hline()

        tab.add_row(MultiColumn(2, data=bold('Receitas'), align='|c|'),
                    MultiColumn(2, data=bold('Despesas'), align='c|'))
        tab.add_hline()

        tab.add_row('Inscrições', inscricoes, 'Honorários', honorarios)
        tab.add_hline()

        tab.add_row('Convênios', convenios, 'Passagens', passagens)
        tab.add_hline()

        tab.add_row('Patrocínios', patrocinios, 'Alimentação', alimentacao)
        tab.add_hline()

        tab.add_row('Fonte(s) de financiamento', fonte_financiamento,
                    'Hospedagem', hospedagem)
        tab.add_hline()

        tab.add_row('', '', 'Divulgação', divulgacao)
        tab.add_hline()

        tab.add_row('', '', 'Material de consumo', material_consumo)
        tab.add_hline()

        tab.add_row('', '', 'Xerox', xerox)
        tab.add_hline()

        tab.add_row('', '', 'Certificados', certificados)
        tab.add_hline()

        tab.add_row('', '', 'Outros (especificar)',
                    '{}\n{}'.format(str(outros), outros_especificacao))
        tab.add_hline()

        tab.add_row(bold('Total'), total_receitas,
                    MultiRow(2, data=bold('Total')),
                    MultiRow(2, data=total_despesas))
        doc.append(UnsafeCommand('cline', '1-2'))

        # TODO: não tem atributo para saldo previsto na classe PrevisaoOrcamentaria_CursoExtensao
        tab.add_row(bold('Saldo previsto'), '', '', '')
        tab.add_hline()
コード例 #26
0
    doc.append(Command("settowidth", [Command("spacebox"), "8888888888"]))

    # \newlength{\spacebox}
    # \settowidth{\spacebox}{8888888888}

    ###########################

    ###########################

    # # Use our newly created command with different arguments
    # doc.append(ExampleCommand(arguments=Arguments('blue', 'Hello', 'World!')))

    sepspace = UnsafeCommand('newcommand',
                             r'\sepspace',
                             extra_arguments=r"""
                             \vspace*{1em}
""")

    doc.append(sepspace)

    ###########################

    ###########################

    MyName = UnsafeCommand('newcommand',
                           r'\MyName',
                           options=1,
                           extra_arguments=r"""
            \Huge \usefont{OT1}{phv}{b}{n} \hfill #1
            \par \normalsize \normalfont
コード例 #27
0
    def addCustomCommands(self):
        NameEntry = UnsafeCommand('newcommand',
                                  r'\NameEntry',
                                  options=1,
                                  extra_arguments=r"""
                            \noindent \LARGE{\textbf{#1}}
                            \linebreak
                            \vspace{-2ex}
                            \hrule
                            \normalsize
                        """)

        PageSpacing = UnsafeCommand('newcommand',
                                    r'\PageSpacing',
                                    options=0,
                                    extra_arguments=r"""
                            \vspace{1em}
                            \noindent
                        """)

        EducationEntry = UnsafeCommand('newcommand',
                                       r'\EducationEntry',
                                       options=3,
                                       extra_arguments=r"""
                            \Large{Education}
                            & \textbf{California Polytechnic State University, San Luis Obispo}
                            & \linebreak
                            & B.S. {#1}
                            & \linebreak
                            & September {#2} - June {#3} \\
                            \\
                        """)

        WorkEntry = UnsafeCommand('newcommand',
                                  r'\WorkEntry',
                                  options=1,
                                  extra_arguments=r"""
                            & \parbox{5.0in}{#1} \\
                            \\
                        """)

        WorkEntryTitle = UnsafeCommand('newcommand',
                                       r'\WorkEntryTitle',
                                       options=1,
                                       extra_arguments=r"""
                            & \textbf{#1}
                            \\
                        """)

        ItemEntry = UnsafeCommand('newcommand',
                                  r'\ItemEntry',
                                  options=1,
                                  extra_arguments=r"""
                            & {#1} \\
                        """)

        EndSection = UnsafeCommand('newcommand',
                                   r'\EndSection',
                                   options=0,
                                   extra_arguments=r"""
                            & \\
                        """)

        self.doc.append(NameEntry)
        self.doc.append(PageSpacing)
        self.doc.append(EducationEntry)
        self.doc.append(WorkEntryTitle)
        self.doc.append(WorkEntry)
        self.doc.append(ItemEntry)
        self.doc.append(EndSection)
コード例 #28
0
from pylatex.base_classes import CommandBase
from pylatex import UnsafeCommand, Package, NoEscape

from data_generation.constants import BOX_COLOR_NAME, BOX_TEXT_COLOR_NAME


class BoxedEquationCommand(CommandBase):
    _latex_name = "boxedEquation"
    packages = [Package("color")]


def BoxedEquation(equation):
    return BoxedEquationCommand(NoEscape(equation))


boxed_equation_code = fr"""\colorbox{{{BOX_COLOR_NAME}}}{{\textcolor{{{BOX_TEXT_COLOR_NAME}}}{{#1}}}}"""

BoxedEquationDefinition = UnsafeCommand("newcommand",
                                        r"\boxedEquation",
                                        options=1,
                                        extra_arguments=boxed_equation_code)
コード例 #29
0
ファイル: sitges.py プロジェクト: codingluke/cv_generator
 def _format_project_subtitle(self, project_item):
     container = self.MultiCommandContainer()
     href_escaped = cv_generator.utils.escape_link(project_item.link.href)
     anchor_escaped = pylatex.utils.escape_latex(project_item.link.anchor)
     container.append(Command('texttt', UnsafeCommand('href', [href_escaped, anchor_escaped])))
     return container
コード例 #30
0
ファイル: reportscript.py プロジェクト: zeroset/jpscore
def get_test_description(doc, testnumber):
    doc.append(NewPage())
    description = UnsafeCommand(
        'input', 'test_description/test_{}.tex'.format(testnumber))
    doc.append(description)