Ejemplo n.º 1
0
 def quadro_planejamento(self, planejamento_acoes):
     with self.create(
             LongTabu("|X[1,l]|X[3,l]|X[6,l]|")) as tabela_planejamento:
         tabela_planejamento.add_hline()
         tabela_planejamento.add_row(
             (MultiColumn(3, align='|c|',
                          data=bold('Cronograma de Ações')), ))
         tabela_planejamento.add_hline()
         tabela_planejamento.add_row(
             (bold('Prazo'), bold('Ação'), bold('Prioridade')))
         tabela_planejamento.add_hline()
         tabela_planejamento.end_table_header()
         tabela_planejamento.add_hline()
         tabela_planejamento.add_row(
             (MultiColumn(3, align='|r|',
                          data='Continua na próxima página'), ))
         tabela_planejamento.add_hline()
         tabela_planejamento.end_table_footer()
         tabela_planejamento.end_table_last_footer()
         for acao in planejamento_acoes:
             metas = acao['metas']
             if not len(metas):
                 continue
             col_meta = MultiRow(len(metas),
                                 data=acao['prazo'].capitalize())
             row = [col_meta, acao['acao'], '1. ' + metas[0]]
             tabela_planejamento.add_row(row)
             for meta in metas[1:]:
                 tabela_planejamento.add_row(
                     ('', '', (str(metas.index(meta) + 1) + '. ' + meta)))
             tabela_planejamento.add_hline()
Ejemplo n.º 2
0
        def InsDatosEscolares(hasImage):

            with self.doc.create(
                    Tabular(
                        NoEscape("m{0.8in}m{0.6in}m{0.9in}m{1.5in}m{2.3in}"))
            ) as table:
                if hasImage:
                    image = MultiRow(
                        3,
                        data=Command(
                            "includegraphics",
                            NoEscape(self.data["Foto"]
                                     [self.data["Foto"].rfind("/") +
                                      1:][:self.data["Foto"].rfind(".")]),
                            ["width=1.5in", "height=1in"]))
                else:
                    image = ""
                table.add_row(("", "", "", "", ""))
                table.add_row(("", "", "", "", image))
                table.add_row(
                    (bold("Matrícula: "), self.data["Matrícula"],
                     bold("Licenciatura: "), self.data["Licenciatura"], ""))
                table.add_row(
                    (bold("Semestre: "), self.data["Semestre"],
                     bold("Generación: "), self.data["Generación"], ""))
Ejemplo n.º 3
0
    def LED_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('LEDs')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the 4 LEDs on RFFEuC\'s edge.\n'
                )
                self.doc.append(
                    'A large LDR (20mm) is positioned in front of all LEDs and is connected to one of the Analogic-to-Digital converter ports - routed through the TestBoard Jn connector.\n'
                )
                self.doc.append(
                    'Each LED is activated separately and the LDR voltage is read and compared to a predefined mask.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row(bold('LED'), bold('LDR read [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['led'].items():
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key), (val['value']),
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
Ejemplo n.º 4
0
    def PowerSupply_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('Power Supply')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the Voltage regulation circuit.\n'
                )
                self.doc.append(
                    'Both power supply lines (5V and 3.3V) are tested using a simple voltage divider circuit present on the TestBoard. Given that the voltage divider provides a half of the real value to the RFFEuC ADC circuit, the following convertion is applied: \n'
                )
                with self.doc.create(Alignat(numbering=False,
                                             escape=False)) as agn:
                    agn.append(r'V_{PS} = ADC_{read} * 3.3 * 2 \\')

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row(bold('Power Supply'), bold('Measured [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['powerSupply'].items(
                        ):
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key + 'V'),
                                    val['value'],
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
Ejemplo n.º 5
0
 def quadro_epis(self, fichas_exposicao):
     with self.create(LongTabu("|X[l]|X[l]|")) as tabela_epi:
         tabela_epi.add_hline()
         tabela_epi.add_row(
             (MultiColumn(2,
                          align='|c|',
                          data=bold('Quadro Demonstrativo de EPIs')), ))
         tabela_epi.add_hline()
         tabela_epi.add_row((bold('Função'), bold('EPIs Indicados')))
         tabela_epi.add_hline()
         tabela_epi.end_table_header()
         tabela_epi.add_row(
             (MultiColumn(2, align='|c|',
                          data='Continua na próxima página'), ))
         tabela_epi.add_hline()
         tabela_epi.end_table_footer()
         tabela_epi.end_table_last_footer()
         for ficha in fichas_exposicao:
             epis = ficha['epis']
             if not len(epis):
                 continue
             col_cargo = MultiRow(len(epis), data=ficha['cargo'])
             row = [col_cargo, epis[0]]
             tabela_epi.add_row(row)
             for epi in epis[1:]:
                 tabela_epi.add_row(('', epi))
             tabela_epi.add_hline()
    def create_platform_unit_legend():
        rows = '|c|'
        title_row = [bold('Metric')]
        unit_row = [bold('Unit')]

        rows2 = '|c|'
        title_row2 = [bold('Metric')]
        unit_row2 = [bold('Unit')]
        i = 0
        for metric in metrics.MetricLegends:
            if i < 10:
                rows += 'c|'
                title_row.append(metrics.MetricLegends[metric]['name'])
                unit_row.append(metrics.MetricLegends[metric]['unit'])
            else:
                rows2 += 'c|'
                title_row2.append(metrics.MetricLegends[metric]['name'])
                unit_row2.append(metrics.MetricLegends[metric]['unit'])
            i += 1
        table = Tabular(rows)
        table.add_hline()
        table.add_row(tuple(title_row))
        table.add_hline()
        table.add_row(tuple(unit_row))
        table.add_hline()

        table2 = Tabular(rows2)
        table2.add_hline()
        table2.add_row(tuple(title_row2))
        table2.add_hline()
        table2.add_row(tuple(unit_row2))
        table2.add_hline()

        return table, table2
Ejemplo n.º 7
0
 def _document_init_params(self) -> None:
     """Add initialization parameters to the traceability document.
     """
     with self.doc.create(Section("Parameters")):
         model_ids = {
             FEID(id(model))
             for model in self.system.network.models
             if isinstance(model, (tf.keras.Model, torch.nn.Module))
         }
         datasets = {
             FEID(id(self.system.pipeline.data.get(title, None))):
             (title, self.system.pipeline.data.get(title, None))
             for title in ['train', 'eval', 'test']
         }
         for tbl in self.config_tables:
             name_override = None
             toc_ref = None
             extra_rows = None
             if issubclass(tbl.type, Estimator):
                 toc_ref = "Estimator"
             if issubclass(tbl.type, BaseNetwork):
                 toc_ref = "Network"
             if issubclass(tbl.type, Pipeline):
                 toc_ref = "Pipeline"
             if tbl.fe_id in model_ids:
                 # Link to a later detailed model description
                 name_override = Hyperref(
                     Marker(name=str(tbl.name), prefix="subsec"),
                     text=NoEscape(r'\textcolor{blue}{') + bold(tbl.name) +
                     NoEscape('}'))
                 toc_ref = tbl.name
             if tbl.fe_id in datasets:
                 title, dataset = datasets[tbl.fe_id]
                 name_override = bold(f'{tbl.name} ({title.capitalize()})')
                 toc_ref = f"{title.capitalize()} Dataset"
                 # Enhance the dataset summary
                 if isinstance(dataset, FEDataset):
                     extra_rows = list(
                         dataset.summary().__getstate__().items())
                     for idx, (key, val) in enumerate(extra_rows):
                         key = f"{prettify_metric_name(key)}:"
                         if isinstance(val, dict) and val:
                             if isinstance(
                                     list(val.values())[0],
                                 (int, float, str, bool, type(None))):
                                 val = jsonpickle.dumps(val,
                                                        unpicklable=False)
                             else:
                                 subtable = Tabular('l|l')
                                 for k, v in val.items():
                                     if hasattr(v, '__getstate__'):
                                         v = jsonpickle.dumps(
                                             v, unpicklable=False)
                                     subtable.add_row((k, v))
                                 val = subtable
                         extra_rows[idx] = (key, val)
             tbl.render_table(self.doc,
                              name_override=name_override,
                              toc_ref=toc_ref,
                              extra_rows=extra_rows)
Ejemplo n.º 8
0
def prepareDoc(course):
    geometry = settings.geometry
    title = "{} DERSİ DERS DEĞERLENDİRME ANKETİ SONUÇLARI".format(course.course_name)
    
    doc = Document(indent=False, geometry_options=geometry)
    doc.preamble.append(Command("usepackage","babel","turkish"))
    doc.preamble.append(Command("usepackage","float"))
    doc.preamble.append(Command("usepackage","framed"))
    doc.preamble.append(Command("title", title))
    doc.preamble.append(NoEscape(r"\date{\vspace{-1.5cm}\today}"))
    
    doc.append(NoEscape(r"\maketitle"))
    doc.append(Command("shorthandoff","="))
    
    doc.append(Command("begin", "framed"))
    doc.append(bold("Dersin Kodu : "))
    doc.append("{}".format(course.course_code))
    doc.append(NoEscape(r"\quad"))
    doc.append("({}. sınıf)".format(course.course_grade))
    doc.append(NewLine())
    doc.append(bold("Dersin Türü : "))
    doc.append("{}".format(course.course_type))
    doc.append(NewLine())
    doc.append(bold("Dersin Grubu : "))
    doc.append("{}".format(course.course_group))
    doc.append(NewLine())
    doc.append(bold("Dersin Dönemi : "))
    doc.append("{}".format(course.course_term))
    doc.append(NewLine())
    doc.append(bold("Öğretim Üyesi : "))
    lname = course.lecturer_name + ' ' + course.lecturer_middle + ' ' + course.lecturer_surname
    doc.append(lname)
    doc.append(Command("end", "framed"))
    
    return doc
Ejemplo n.º 9
0
 def create_pdf(self) -> Document:
     questions = functools.reduce(
         lambda a, b: a + b, map(lambda x: x.get_questions(),
                                 self.questions), [])
     doc = Document()
     doc.preamble.append(Package('titling'))
     for i in range(1, self.count + 1):
         random.shuffle(questions)
         with doc.create(Center()):
             doc.append(HugeText(self.header))
         doc.append(bold('Nombre:'))
         doc.append(LineBreak())
         doc.append(bold('ID:'))
         doc.append(LineBreak())
         with doc.create(FlushRight()):
             doc.append(LargeText(f'Examen tipo {i}'))
         enum = Enumerate()
         for question in questions:
             question.append_to_document(doc, enum)
         doc.append(NewPage())
         doc.append('Guía de respuestas')
         doc.append(enum)
         doc.append(NewPage())
         doc.append(Command('setcounter', ['section', '0']))
     return doc
def create_long_table(
    doc,
    parameters,
    skip_parameters=[],
    table_specs=r"|p{0.45\linewidth}|p{0.45\linewidth}|",
    header=[bold("Parameter"), bold("Value")],
):
    """
    Helper function to create long table for parameters
    Arguments:
         doc: document to add table
         parameters: parameters dict
         skip_parameters: list of parameters to skip
         table_specs: latex specific table settings
         header: list with column names
    """
    columns = len(header)
    with doc.create(LongTable(table_spec=table_specs)) as data_table:
        # Table header
        data_table.add_hline()
        data_table.add_row(header)
        data_table.add_hline()
        data_table.end_table_header()
        data_table.add_row((MultiColumn(columns,
                                        align="r",
                                        data="Continued on Next Page"), ))
        data_table.end_table_footer()
        data_table.add_row((MultiColumn(columns,
                                        align="r",
                                        data="End of Table"), ))
        data_table.end_table_last_footer()
        for item in parameters:
            if item not in skip_parameters:
                data_table.add_row([item, str(parameters[item])])
                data_table.add_hline()
Ejemplo n.º 11
0
    def gen_smpl(self, idx, n_digits, n_nums, var_digits=0):
        """ generate an example of a simple addition 
        """
        assert (n_digits >= 1)
        assert (var_digits < n_digits)
        q_tab = Tabular(' c r ', row_height=1.2)

        # contents...
        nums = [gen_rnd(n_digits, var_digits) for n in range(0, n_nums)]
        sgns = [sign(randint(-1000000, 1000000)) for n in range(0, n_nums)]

        sign_syms = list(map(lambda x: '+' if x == 1 else '-', sgns))

        sum_str = ''.join(
            [sign_syms[n] + str(nums[n]) for n in range(0, n_nums)])
        if sum_str[0] == '+':
            sum_str = sum_str[1:]  # tail if leading with a '+'

        mth = Math(escape=False, inline=True)
        mth.append(NoEscape(sum_str + '='))
        q_tab.add_row((bold(str(idx) + ':'), mth))

        a_tab = Tabular(' l l ', row_height=1.1)
        a_idx = bold(str(idx) + ":")
        res = sum(multiply(nums, sgns))
        a_tab.add_row((a_idx, res))

        #print(sum_str, '=', res)
        return (q_tab, a_tab)
Ejemplo n.º 12
0
def produce_header_footer():
    """
    Adds a generic header/footer to the report. Includes the date and CFIA logo in the header + legend in the footer.
    """
    header = pl.PageStyle("header", header_thickness=0.1)

    image_filename = get_image()
    with header.create(pl.Head("L")) as logo:
        logo.append(
            pl.StandAloneGraphic(image_options="width=110px",
                                 filename=image_filename))

    # Date
    with header.create(pl.Head("R")):
        header.append("Date Report Issued: " +
                      datetime.today().strftime('%Y-%m-%d'))

    # Footer
    with header.create(pl.Foot("C")):
        with header.create(pl.Tabular('lcr')) as table:
            table.add_row(
                '',
                bold(
                    'Data interpretation guidelines can be found in RDIMS document ID: 10401305'
                ), '')
            table.add_row(
                '', bold('This report was generated with OLC AutoROGA v1.2'),
                '')
    return header
Ejemplo n.º 13
0
    def add_to_book(self, book: Book):
        with book.create(MdFramed()) as box:
            box.append(bold(self.name))
            box.append(NoEscape("\\hspace*{\\fill}"))
            box.append(bold(self.__get_cost()))
            box.append(" ¥€$\n")
            box.append(NoEscape(r"\noindent\rule{\columnwidth}{1pt}"))
            box.append(LineBreak())
            box.append(NoEscape(self.desc))
            box.append(LineBreak())
            box.append(LineBreak())
            with box.create(Tabularx("X|l|r")) as tab:
                for effect, perma_effect, effector in itertools.zip_longest(self.effects, self.permanent_effects, self.effectors):
                    row = []

                    if effect is not None:
                        row.append(effect + ":" + get_effect_str(self.effects[effect]))
                    else:
                        row.append("")

                    if perma_effect is not None:
                        row.append(perma_effect + ":" + get_effect_str(self.permanent_effects[perma_effect]))
                    else:
                        row.append("")

                    if effector is not None:
                        row.append(italic(effector.name))
                    else:
                        row.append("")

                    tab.add_row(row)
Ejemplo n.º 14
0
def genenerate_longtabu():
    geometry_options = {
        "landscape": True,
        "margin": "0.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    # Generate data table
    with doc.create(LongTabu("X[r] X[r] X[r] X[r] X[r] X[r]")) as data_table:
        header_row1 = ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"]
        data_table.add_row(header_row1, mapper=[bold])
        data_table.add_hline()
        data_table.add_empty_row()
        data_table.end_table_header()
        data_table.add_row(
            ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"])
        row = [
            "PDADASDASDSADSADSADASDASDSADASDASA", "9", "$100", "%10", "$1000",
            "Test"
        ]
        for i in range(50):
            data_table.add_row(row)

    doc.append(bold("Grand Total:"))
    doc.append(HFill())
    doc.append(bold("Total"))

    doc.generate_pdf("longtabu", clean_tex=False)
Ejemplo n.º 15
0
        def InsDatosFamiliares():
            with self.doc.create(SectionUnnumbered("Datos Familiares")):
                Command("vspace", NoEscape("-1ex"))
                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\{}: {} {}: {}\\"\
                 .format(bold("Nombre del Padre"), makeUnderline(self.data["Nombre del Padre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Padre"], 1.65),\
                  bold("Domicilio"), makeUnderline(self.data["Dirección Padre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Padre"], 1.63))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Padre"],
                                   self.data["Celular Padre"],
                                   self.data["Correo Padre"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))

                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\{}: {} {}: {}\\"\
                 .format(bold("Nombre de la Madre"), makeUnderline(self.data["Nombre de la Madre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Madre"], 1.55),\
                  bold("Domicilio"), makeUnderline(self.data["Dirección Madre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Madre"], 1.63))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Madre"],
                                   self.data["Celular Madre"],
                                   self.data["Correo Madre"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))
def add_center_column(doc):
    with column_with_margin(doc) as page:
        make_heading_divider(page, "ownership details")
        table = Tabular("l l", row_height=1.5, col_space="1em")
        table.add_row(MultiRow(2, data="Owner"), bold("GRADIA Laboratory"))
        table.add_row("", "(as of 8-Sep-20)")
        table.add_row("Goldway Ref", bold("SIOT202007002-R"))
        table.add_row("GIA Ref", bold("1231233345"))
        table.add_row("Blockchain Ref", bold("123154647sdiuyfh"))
        page.append(table)

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "macro image")
        macro_file = os.path.join(BASE_DIR, "macro.png")
        page.append(
            StandAloneGraphic(image_options="width=200px",
                              filename=macro_file))

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "nano etching")

        table = Tabular("l l l", row_height=1.3, col_space="0.3em")
        nano_picture = StandAloneGraphic(image_options="width=70px",
                                         filename=os.path.join(
                                             BASE_DIR, "nano.png"))
        table.add_row("", "", MultiRow(3, data=nano_picture))
        table.add_row("Etched ID no.", bold("G00000013"), "")
        table.add_empty_row()
        page.append(table)
Ejemplo n.º 17
0
        def InsDatosDomicilio():
            with self.doc.create(SectionUnnumbered("Domicilio Particular")):
                Command("vspace", NoEscape("-1ex"))
                with self.doc.create(
                        Tabular(NoEscape(
                            "m{1.33in}m{0.6in}m{2in}m{1.9in}"))) as table:
                    table.add_row(
                        (self.data["Calle"], self.data["Número"],
                         self.data["Colonia"], self.data["Población"]))
                    table.add_hline()
                    table.add_row((bold("Calle"), bold("Número"),
                                   bold("Colonia"), bold("Poblacion")))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Municipio"], self.data["Estado"],
                                   self.data["C.P."]))
                    table.add_hline()
                    table.add_row(
                        (bold("Municipio"), bold("Estado"), bold("C.P.")))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row(
                        (self.data["Teléfono Particular"],
                         self.data["Teléfono Celular"], self.data["Correo"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))
Ejemplo n.º 18
0
def print_workout(doc, lift, one_rm, no, accessorys):
    """Print one workout routine.

    Arguments:
        lift
        one_rm
        no
        accessorys

    Returns:
        One workout
    """
    doc.append(VerticalSpace("20pt"))
    doc.append(LineBreak())

    main_lift = gen_main_lift(lift, one_rm, no)
    access = gen_accessory_table(accessorys)

    with doc.create(MiniPage(width=r"0.5\textwidth")):
        doc.append(bold('Main Lift\n\n'))
        doc.append(main_lift)
        doc.append(VerticalSpace("20pt"))
        doc.append(LineBreak())
        doc.append(bold('Accessory Exercises\n\n'))
        doc.append(access)
        # doc.append(main_lift)

    doc.append(VerticalSpace("20pt"))
    doc.append(LineBreak())
    return doc
Ejemplo n.º 19
0
def generate_eva_report():

    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    reportStyle = PageStyle("reportStyle")

    with reportStyle.create(Head("R")) as left_header:
        with left_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='l')) as title_wrapper:
            title_wrapper.append(LargeText(bold("RiMEA-Projekt")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Anlyse")))

    doc.preamble.append(reportStyle)

    doc.change_document_style("reportStyle")

    with doc.create(LongTabu("X[c] X[c]", row_height=1.5)) as report_table:
        report_table.add_row(["Test", "evacuation time(s)"], mapper=bold)
        report_table.add_hline()

    for i in range(1, 4):
        report_table.add_row(i, get_evac_time(i)[0])

    doc.append(NewPage())

    doc.generate_pdf("RiMEA-Projekt-Evacution-Analyse", clean_tex=False)
Ejemplo n.º 20
0
    def GPIOLoopback_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('GPIO Loopback')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the GPIO pins on both RFFEuC\'s headers.'
                )
                self.doc.append(
                    'In the TestBoard all GPIO pins are connected in pairs via a 1K1 resistor, so they\'re logically binded.\n'
                )
                self.doc.append(
                    'Each pin in the loopback pair is tested as an Input and Output, changing the logic level of its pair to assert the electrical connection.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row((MultiColumn(2,
                                                 align='|c|',
                                                 data=bold('Loopback Pair')),
                                     bold('Result')))
                        tbl.add_hline()
                        for key, val in self.test_results['gpio'].items():
                            if isinstance(val, dict):
                                tbl.add_row(
                                    val['pin1'],
                                    val['pin2'],
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
Ejemplo n.º 21
0
def printSalary(request, id):
    teacher = Teacher.objects.get(pk=id)
    all_add = tAddEntry.objects.filter(teacher__id=id)
    all_del = tDelEntry.objects.filter(teacher__id=id)
    salary = Salary.objects.get(teacher=teacher)
    length = len(all_add) + 1
    length2 = len(all_del) + 1
    user = User.objects.get(pk=1)
    add = 0
    sub = 0
    total = 0

    geometry_options = {
        "margin": "1in",
        "textwidth": "2in",
        "textheight": "2in",
        "headheight": "0pt",
        "headsep": "0pt",
        "footskip": "0pt"
    }

    doc = Document(geometry_options=geometry_options)
    doc.preamble.append(Command("usepackage", "times"))
    doc.preamble.append(Command("usepackage", "graphicx"))
    doc.documentclass = Command('documentclass',
                                options=['11pt'],
                                arguments=['article'])

    with doc.create(Tabu(" X[c]  X[2r]  ")) as table:
        table.add_row(
            (LargeText(bold(teacher.lastname + "," + teacher.firstname))), "")
        table.add_empty_row()

    with doc.create(Tabu(" | X[c] |  X[2r] | ")) as table:

        table.add_hline()
        table.add_row(bold("Allowance"), "PHP " + str(user.amount))
        table.add_hline()
        table.add_row(bold("Additional"), "")
        for i in all_add:
            table.add_empty_row()
            table.add_row(i.name, "PHP " + str(i.value))
            table.add_hline()
            add = add + i.value
        table.add_row(bold("Deduction"), "")
        for i in all_del:
            table.add_empty_row()
            table.add_row(i.name, "PHP " + str(i.value))
            table.add_hline()
            sub = sub + i.value

        total = user.amount + add - sub
        table.add_row(bold("TOTAL"), "PHP " + str(total))
        table.add_hline()

    doc.generate_pdf(teacher.lastname + "_salary", clean_tex=False)
    image_data = open(teacher.lastname + "_salary.pdf", "rb")
    return HttpResponse(image_data, content_type='application/pdf')
Ejemplo n.º 22
0
    def constroiCorpo(self):

        with self.documento.create(Tabu("X[l] X[r]")) as first_page_table:
            customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
            customer.append(bold("Nome fantasia: "))
            customer.append(self.usuarioModel.nomeFantasia)
            customer.append("\n")
            customer.append(bold("CNPJ: "))
            customer.append(mascaraCNPJ(self.usuarioModel.cnpj))
            customer.append("\n")
            customer.append(bold("Endereço: "))
            if self.usuarioModel.endereco == 'None':
                customer.append('---')
            else:
                customer.append(self.usuarioModel.endereco)

            # Add branch information
            branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                              pos='t!',
                              align='r')
            branch.append(f"Total de clientes: {self.totalClientes}")
            branch.append(LineBreak())
            branch.append(f"Total de clientes Ativos: {self.clientesAtivos}")
            branch.append(LineBreak())
            branch.append(
                f"Média de clientes ativos: {round((self.clientesAtivos / self.totalClientes)*100)} % "
            )
            branch.append(LineBreak())

            first_page_table.add_row([customer, branch])
            first_page_table.add_empty_row()

        self.documento.change_document_style("firstpage")

        with self.documento.create(
                LongTabu("X[1.5l] X[2l] X[r] X[r] X[r]",
                         row_height=1.5)) as data_table:
            data_table.add_row([
                "Última atualização", "Nome do cliente", "Turma", "credits($)",
                "balance($)"
            ],
                               mapper=bold,
                               color="lightgray")
            data_table.add_empty_row()
            data_table.add_hline()
            for i, cliente in enumerate(self.clientesList):
                clienteRow = list()
                clienteRow.append(mascaraMeses(cliente[13]))
                clienteRow.append(cliente[1] + ' ' + cliente[2])
                clienteRow.append('Teste 1')
                clienteRow.append('Teste 2')
                clienteRow.append('Teste 3')
                if (i % 2) == 0:
                    data_table.add_row(clienteRow, color="lightgray")
                else:
                    data_table.add_row(clienteRow)
Ejemplo n.º 23
0
 def add_to_book(self, book: Book):
     book.append(NoEscape("\\noindent\\makebox[\\linewidth]{\\rule{\\columnwidth}{0.4pt}}"))
     book.append(LineBreak())
     book.append(bold(self.name))
     book.append(NoEscape("\\hspace*{\\fill}"))
     book.append(bold("x " + str(self.cost_effect)))
     book.append(LineBreak())
     book.append(self.desc)
     book.append(NewLine())
     book.append(NewLine())
Ejemplo n.º 24
0
    def get_packaging_table_as_tabularx(self):
        table = Tabularx("|X|X|X|", row_height=1.25)
        table.add_hline()
        table.add_row(bold("Type"), bold("Størrelse"), bold("Antall"))
        for child_id in self.packaging_table.get_children():
            child = self.packaging_table.item(child_id)
            if (text := child["text"]):
                table.add_hline()

            table.add_row(text, child["values"][0], child["values"][1])
Ejemplo n.º 25
0
    def get_general_info_as_tabularx(self):
        table = Tabularx("|X|X|X|X|", row_height=1.25)
        table.add_hline()
        table.add_row(bold("Kundenavn"), self.customer_name.get(),
                      bold("Ordrenummer"), self.order_number.get())

        table.add_hline()
        total_lengde = str(self.get_total_length_l())
        if (total_length_r := self.get_total_length_r()):
            total_lengde += f" x {total_length_r}"
Ejemplo n.º 26
0
		def InsDatosEscolares(hasImage):

			with self.doc.create(Tabular(NoEscape("m{0.8in}m{0.6in}m{0.9in}m{1.5in}m{2.3in}"))) as table:
				if hasImage:
					image = MultiRow(3, data=Command("includegraphics", NoEscape(self.data["Foto"][self.data["Foto"].rfind("/") + 1:][:self.data["Foto"].rfind(".")]),["width=1.5in", "height=1in"]))					
				else:
					image = ""
				table.add_row(("","","","",""))
				table.add_row(("","","","", image))
				table.add_row((bold("Matrícula: "), self.data["Matrícula"], bold("Licenciatura: "), self.data["Licenciatura"], ""))
				table.add_row((bold("Semestre: "),self.data["Semestre"], bold("Generación: "), self.data["Generación"], ""))
Ejemplo n.º 27
0
    def _write_tables(self, tables: List[FeSummaryTable], model_ids: Set[FEID],
                      datasets: Dict[FEID, Tuple[Set[str], Any]]) -> None:
        """Insert a LaTeX representation of a list of tables into the current doc.

        Args:
            tables: The tables to write into the doc.
            model_ids: The ids of any known models.
            datasets: A mapping like {ID: ({modes}, dataset)}. Useful for augmenting the displayed information.
        """
        for tbl in tables:
            name_override = None
            toc_ref = None
            extra_rows = None
            if tbl.fe_id in model_ids:
                # Link to a later detailed model description
                name_override = Hyperref(Marker(name=str(tbl.name),
                                                prefix="subsec"),
                                         text=NoEscape(r'\textcolor{blue}{') +
                                         bold(tbl.name) + NoEscape('}'))
            if tbl.fe_id in datasets:
                modes, dataset = datasets[tbl.fe_id]
                title = ", ".join([s.capitalize() for s in modes])
                name_override = bold(f'{tbl.name} ({title})')
                # Enhance the dataset summary
                if isinstance(dataset, FEDataset):
                    extra_rows = list(dataset.summary().__getstate__().items())
                    for idx, (key, val) in enumerate(extra_rows):
                        key = f"{prettify_metric_name(key)}:"
                        if isinstance(val, dict) and val:
                            if isinstance(
                                    list(val.values())[0],
                                (int, float, str, bool, type(None))):
                                val = jsonpickle.dumps(val, unpicklable=False)
                            else:
                                subtable = Tabularx(
                                    'l|X',
                                    width_argument=NoEscape(r'\linewidth'))
                                for k, v in val.items():
                                    if hasattr(v, '__getstate__'):
                                        v = jsonpickle.dumps(v,
                                                             unpicklable=False)
                                    subtable.add_row((k, v))
                                # To nest TabularX, have to wrap it in brackets
                                subtable = ContainerList(data=[
                                    NoEscape("{"), subtable,
                                    NoEscape("}")
                                ])
                                val = subtable
                        extra_rows[idx] = (key, val)
            tbl.render_table(self.doc,
                             name_override=name_override,
                             toc_ref=toc_ref,
                             extra_rows=extra_rows)
def generate_header():
    """
    """
    global doc, doc_correction
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("Universite Cergy Pontoise")
        header.append(LineBreak())
        header.append("*****@*****.**")
    # Create center header
    with header.create(Head("C")):
        header.append("Annee 2021")
    # Create right header
    with header.create(Head("R")):
        header.append("Automates et langages reguliers")
        header.append(LineBreak())
        header.append("L2")
    # # Create left footer
    # with header.create(Foot("L")):
    #     header.append("Left Footer")
    # # Create center footer
    # with header.create(Foot("C")):
    #     header.append("Center Footer")
    # # Create right footer
    # with header.create(Foot("R")):
    #     header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    doc_correction.preamble.append(header)
    doc_correction.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='c')):
        doc.append(
            LargeText(
                bold("Examen de deuxieme session - Langages et automates")))
        doc.append(LineBreak())
        doc.append(MediumText(bold("Mardi 16 avril 2021")))

    # Add Heading
    with doc_correction.create(MiniPage(align='c')):
        doc_correction.append(
            LargeText(
                bold(
                    "Correctoin de l'examen de deuxieme session - Langages et automates"
                )))
        doc_correction.append(LineBreak())
        doc_correction.append(MediumText(bold("Mardi 16 avril 2021")))
Ejemplo n.º 29
0
def test_utils():
    # Utils
    escape_latex(s="")

    fix_filename(path="")

    dumps_list(l=[], escape=False, token="\n")

    bold(s="")

    italic(s="")

    verbatim(s="", delimiter="|")
Ejemplo n.º 30
0
def test_utils():
    # Utils
    escape_latex(s='')

    fix_filename(path='')

    dumps_list(l=[], escape=False, token='\n')

    bold(s='')

    italic(s='')

    verbatim(s='', delimiter='|')
Ejemplo n.º 31
0
def gen_party_flat(party, designation):
    cnt = []
    cnt.append(f'{bold(party["name"])}, with registered offices at ' +
               bold(', '.join(party["address"])) + ', ' +
               bold(party['country']))
    if 'regno' in party:
        cnt.append(
            f'registered with {bold(party["authority"])}; {bold(party["regno"])}'
        )
    if 'email' in party:
        cnt.append(f'with the email address {bold(party["email"])}')
    cnt.append(f'hereinafter "{bold(designation)}"')
    return ', '.join(cnt)
Ejemplo n.º 32
0
def test_utils():
    # Utils
    escape_latex(s='')

    fix_filename(path='')

    dumps_list(l=[], escape=False, token='\n')

    bold(s='')

    italic(s='')

    verbatim(s='', delimiter='|')
Ejemplo n.º 33
0
def add_question(doc, desire, attributes):
    with doc.create(Center()) as centered:
        with centered.create(MiniPage(width=r"0.85\textwidth")) as page:
            page.append(SmallText(attributes['title']))
            wealth = "- " + attributes['choices'][WEALTH]
            control = "- " + attributes['choices'][CONTROL]
            if desire == CONTROL:
                wealth = bold(wealth + " (your choice)")
            if desire == WEALTH:
                control = bold(control + " (your choice)")

            for a in random.sample([wealth, control], 2):
                page.append(NewLine())
                page.append(SmallText(a))
Ejemplo n.º 34
0
		def InsDatosDomicilio():
			with self.doc.create(SectionUnnumbered("Domicilio Particular")):
				Command("vspace", NoEscape("-1ex"))
				with self.doc.create(Tabular(NoEscape("m{1.33in}m{0.6in}m{2in}m{1.9in}"))) as table:
					table.add_row((self.data["Calle"], self.data["Número"], self.data["Colonia"], self.data["Población"]))
					table.add_hline()
					table.add_row((bold("Calle"), bold("Número"), bold("Colonia"), bold("Poblacion")))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Municipio"], self.data["Estado"], self.data["C.P."]))
					table.add_hline()
					table.add_row((bold("Municipio"), bold("Estado"), bold("C.P.")))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Particular"], self.data["Teléfono Celular"], self.data["Correo"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))
Ejemplo n.º 35
0
def generate_eva_report():
		"""
    Generate a report which contains the evacution time for every test
    """
		geometry_options = {
		"head": "40pt",
		"margin": "0.5in",
		"bottom": "0.6in",
		"includeheadfoot": True
		}
		doc = Document(geometry_options=geometry_options)

		## Define style of report
		reportStyle = PageStyle("reportStyle")

		with reportStyle.create(Head("R")) as left_header:
				with left_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
				                                  pos='c', align='l')) as title_wrapper:
					title_wrapper.append(LargeText(bold("RiMEA-Projekt")))
					title_wrapper.append(LineBreak())
					title_wrapper.append(MediumText(bold("Anlyse")))

		doc.preamble.append(reportStyle)

		## Apply Pagestyle
		doc.change_document_style("reportStyle")

		## Create table
		with doc.create(LongTabu("X[c] X[c]",
		                       row_height=1.5)) as report_table:
				report_table.add_row(["Test",
				                    "evacuation time(s)"],
				                   mapper=bold)
				report_table.add_hline()

		## Write the results of 3 tests in table
		for i in range(1,4):
			report_table.add_row(i, get_evac_time(i)[0])

		doc.append(NewPage())

		doc.generate_pdf("RiMEA-Projekt Evacution Analyse", clean_tex=False)
Ejemplo n.º 36
0
def write_header(table, config):
    """
        Function that write the first lines of the document.
    """
    # Static datas
    data_row1 = ne('Column ') + bold('type') + \
        ne(' shows how the initial det. aut. was obtained: T = translation'
           ' produces DTGBA; W = WDBA minimization works; P = powerset '
           'construction transforms TBA to DTBA; R = DRA to DBA.')
    data_row2 = ne('Column ') + bold('C.') + \
        ne(' tells whether the output automaton is complete: rejecting '
           'sink states are always omitted (add 1 state when C=0 if you '
           'want the size of the complete automaton).')
    row3 = [MultiColumn(14)]
    row4 = ['', '', '', '', 'DRA',
            MultiColumn(4, align='|c', data='DTGBA'),
            MultiColumn(3, align='|c', data='DBA'),
            MultiColumn(2, align='|c',
                        data=ne('DBA\\footnotesize minimizer'))]
    row5 = ['formula', 'm', 'type', 'C.', 'st.', 'st.', 'tr.',
            'acc.', 'time', 'st.', 'tr.', 'time', 'st.', 'time']

    # Datas that depends on the configuration file
    len_l = len(config.l)
    for i in range(0, len_l):
        row3.append(MultiColumn(7, align='|c', data=config.l[i].name))
        row4.append(MultiColumn(3, align='|c', data='minDBA'))
        row4.append(MultiColumn(4, align='|c', data='minDTGBA'))
        row5.extend(['st.', 'tr.', 'time', 'st.', 'tr.', 'acc.', 'time'])

    # Add the first 5 lines of the document.
    n = 14 + len_l * 7
    table.add_row((MultiColumn(n, align='c', data=data_row1),))
    table.add_row((MultiColumn(n, align='c', data=data_row2),))
    table.add_row((MultiColumn(n, align='l', data=''),))  # add empty line
    table.add_row(tuple(row3))
    table.add_row(tuple(row4))
    table.add_row(tuple(row5))
    table.add_hline()
Ejemplo n.º 37
0
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("Page date: ")
        header.append(LineBreak())
        header.append("R3")
    # Create center header
    with header.create(Head("C")):
        header.append("Company")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold("Title")))
        doc.append(LineBreak())
        doc.append(MediumText(bold("As at:")))

    doc.generate_pdf("header", clean_tex=False)
Ejemplo n.º 38
0
		def InsDatosPersonales():
			with self.doc.create(SectionUnnumbered("Datos Personales")):
				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Apellido Paterno"], self.data["Apellido Materno"], self.data["Nombre"]))
					table.add_hline()
					table.add_row((bold("Apellido Paterno"), bold("Apellido Materno"), bold("Nombre")))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Lugar de Nacimiento"], self.data["Fecha de Nacimiento"], self.data["Nacionalidad"]))
					table.add_hline()
					table.add_row((bold("Lugar de Nacimiento"), bold("Fecha de Nacimiento"), bold("Nacionalidad")))
Ejemplo n.º 39
0
		def InsDatosTrabajo():
			with self.doc.create(SectionUnnumbered("Datos del Trabajo")):
				Command("vspace", NoEscape("-1ex"))
				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\"\
					.format(bold("Empresa o Institución"), makeUnderline(self.data["Empresa"], 2.5),bold("Teléfono"), makeUnderline(self.data["Teléfono Empresa"], 1.65))
					))

				with self.doc.create(Tabular(NoEscape("m{1.3in}m{0.6in}m{2in}m{1.9in}"))) as table:
					table.add_row((self.data["Calle Empresa"], self.data["Número Empresa"], self.data["Colonia Empresa"], self.data["Municipio Empresa"]))
					table.add_hline()
					table.add_row((bold("Calle"), bold("Número"), bold("Colonia"), bold("Municipio")))
Ejemplo n.º 40
0
		def InsDatosEmergencia():
			with self.doc.create(SectionUnnumbered("En caso de emergencia")):
				Command("vspace", NoEscape("-1ex"))
				self.doc.append(NoEscape(\
					r"{}{} {}: {} \\{}: {}\\"\
					.format(bold("¿Padece alguna enfermedad?"), makeUnderline(self.data["¿Enfermedad?"], 0.2),bold("Especifique"), makeUnderline(self.data["Enfermedad"], 3.4), bold("Tipo de Sangre"), makeUnderline(self.data["Tipo de Sangre"], .5))
					))

				self.doc.append(NoEscape(\
					r"{}:\\{}: {} {}: {}\\ "\
					.format(bold("Contactar a"), bold("Nombre"), makeUnderline(self.data["Nombre Contacto"], 3.52),bold("Parentesco"), makeUnderline(self.data["Parentesco"], 1.5))
					))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Contacto"], self.data["Celular Contacto"], self.data["Correo Contacto"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))

				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\"\
					.format(bold("Domicilio"), makeUnderline(self.data["Dirección Contacto"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Contacto"], 1.63))
					))
Ejemplo n.º 41
0
    def tabulateVariables(self):
        """
        Create a table that summarises all input variables.
        """
        ks = self.best1d[:]
        ks.append(self.constker)
        ks.sort(key=lambda k: round(k.getNLML(), 2))
        ks.sort(key=lambda k: round(k.error(), 4))
        data = ks[0].data
        ds = data.getDataShape()

        nlml_min = round(min([k.getNLML() for k in ks]), 2)
        error_min = round(min([k.error() for k in ks]), 4)

        doc = self.doc
        with doc.create(pl.Table(position='htbp!')) as tab:
            tab.add_caption(ut.NoEscape("Input variables"))

            t = pl.Tabular('rlrrrcrr')
            # Header
            t.add_hline()
            t.add_row((
                '',
                '',
                pl.MultiColumn(3, align='c', data='Statistics'),
                pl.MultiColumn(3, align='c', data='Classifier Performance')
                ))
            t.add_hline(start=3, end=8)
            t.add_row((
                pl.MultiColumn(1, align='c', data='Dimension'),
                pl.MultiColumn(1, align='c', data='Variable'),
                pl.MultiColumn(1, align='c', data='Min'),
                pl.MultiColumn(1, align='c', data='Max'),
                pl.MultiColumn(1, align='c', data='Mean'),
                pl.MultiColumn(1, align='c', data='Kernel'),
                pl.MultiColumn(1, align='c', data='NLML'),
                pl.MultiColumn(1, align='c', data='Error') ))
            t.add_hline()

            # Entries
            for k in ks:
                if k is self.constker:
                    row = [
                        ut.italic('--', escape=False),
                        ut.italic('Baseline', escape=False),
                        ut.italic('--', escape=False),
                        ut.italic('--', escape=False),
                        ut.italic('--', escape=False),
                        ut.italic(k.shortInterp(), escape=False),
                        ut.italic('{0:.2f}'.format(k.getNLML()), escape=False),
                        ut.italic(r'{0:.2f}\%'.format(k.error()*100), escape=False) ]
                else:
                    dim = k.getActiveDims()[0]
                    row = [
                        dim+1,
                        data.XLabel[dim],
                        '{0:.2f}'.format(ds['x_min'][dim]),
                        '{0:.2f}'.format(ds['x_max'][dim]),
                        '{0:.2f}'.format(ds['x_mu'][dim]),
                        k.shortInterp(),
                        ut.NoEscape('{0:.2f}'.format(k.getNLML())),
                        ut.NoEscape(r'{0:.2f}\%'.format(k.error()*100)) ]
                if round(k.getNLML(), 2) == nlml_min:
                    row[6] = ut.bold(row[6])
                if round(k.error(), 4) == error_min:
                    row[7] = ut.bold(row[7])

                t.add_row(tuple(row))

            t.add_hline()

            tab.append(ut.NoEscape(r'\centering'))
            tab.append(t)
    def create_pdf(self):
        """Creates the PDF using the PyLatex module.


        """
        r1_summary_trim_dict, r1_stats_trim_dict, r2_summary_trim_dict = self.get_trimmed_data()
        r1_stats_dict = self.get_original_data()

        doc = Document()
        doc.packages.append(Package('geometry', options=['margin=0.75in']))
        doc.packages.append(Package('subcaption'))
        doc.packages.append(Package('xcolor'))
        doc.packages.append(Package('placeins'))
        doc.append(Command('makeatletter'))
        doc.append(Command('setlength', NoEscape(r'\@fptop}{0pt')))
        doc.append(Command('makeatother'))
        doc.append(Command(NoEscape(r'renewcommand{\baselinestretch}'), '1.0'))
        doc.append(Command('begin', 'center'))
        doc.append(Command('Large', bold('Sample Quality Results')))
        doc.append(Command('end', 'center'))

        with doc.create(Section('Basic Statistics')):
            with doc.create(Description()) as desc:
                desc.add_item("Sample:", "%s" % r1_stats_dict.get('Filename')[:-16])
                desc.add_item("File type:", "%s" % r1_stats_dict.get('File type'))
                desc.add_item("Encoding:", "%s" % r1_stats_dict.get('Encoding'))
            with doc.create(Tabular(NoEscape(r'p{5.5cm}|c|c'))) as table:
                table.add_row(('', 'Before trimming', 'After trimming'))
                table.add_hline()
                table.add_row(('Total Sequences',
                               '%s' % r1_stats_dict.get('Total Sequences'),
                               '%s' % r1_stats_trim_dict.get('Total Sequences')))
                table.add_row(('Sequences flagged as poor quality',
                               '%s' % r1_stats_dict.get('Sequences flagged as poor quality'),
                               '%s' % r1_stats_trim_dict.get('Sequences flagged as poor quality')))
                table.add_row(('Sequence length',
                               '%s' % r1_stats_dict.get('Sequence length'),
                               '%s' % r1_stats_trim_dict.get('Sequence length')))
                table.add_row(('%GC',
                               '%s' % r1_stats_dict.get('%GC'),
                               '%s' % r1_stats_trim_dict.get('%GC')))

        with doc.create(Section('FastQC')):
            with doc.create(Figure(position='!htb', placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Per base sequence quality')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%sR1_001_fastqc/Images/per_base_quality.png' % self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r1_summary_trim_dict.get('Per base sequence quality') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get('Per base sequence quality') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get('Per base sequence quality') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR1_001.qfilter_fastqc/Images/per_base_quality.png' % self.sample)
                    plot.add_caption(NoEscape(r'R1 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r1_summary_trim_dict.get('Per base sequence quality'))))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%sR2_001_fastqc/Images/per_base_quality.png' % self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r2_summary_trim_dict.get('Per base sequence quality') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get('Per base sequence quality') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get('Per base sequence quality') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR2_001.qfilter_fastqc/Images/per_base_quality.png' % self.sample)
                    plot.add_caption(NoEscape(r'R2 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r2_summary_trim_dict.get('Per base sequence quality'))))

            with doc.create(Figure(position='!htb', placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Per sequence GC content')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    plot.add_image('%sR1_001_fastqc/Images/per_sequence_gc_content.png' % self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    if r1_summary_trim_dict.get('Per sequence GC content') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get('Per sequence GC content') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get('Per sequence GC content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR1_001.qfilter_fastqc/Images/per_sequence_gc_content.png' % self.sample)
                    plot.add_caption(NoEscape(r'R1 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r1_summary_trim_dict.get('Per sequence GC content'))))
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    plot.add_image('%sR2_001_fastqc/Images/per_sequence_gc_content.png' % self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    if r2_summary_trim_dict.get('Per sequence GC content') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get('Per sequence GC content') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get('Per sequence GC content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR2_001.qfilter_fastqc/Images/per_sequence_gc_content.png' % self.sample)
                    plot.add_caption(NoEscape(r'R2 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r2_summary_trim_dict.get('Per sequence GC content'))))

            with doc.create(Figure(position='!htb', placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Sequence Length Distribution')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%sR1_001_fastqc/Images/sequence_length_distribution.png' % self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r1_summary_trim_dict.get('Sequence Length Distribution') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get('Sequence Length Distribution') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get('Sequence Length Distribution') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR1_001.qfilter_fastqc/Images/sequence_length_distribution.png' % self.sample)
                    plot.add_caption(NoEscape(r'R1 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r1_summary_trim_dict.get('Sequence Length Distribution'))))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%sR2_001_fastqc/Images/sequence_length_distribution.png' % self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r2_summary_trim_dict.get('Sequence Length Distribution') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get('Sequence Length Distribution') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get('Sequence Length Distribution') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR2_001.qfilter_fastqc/Images/sequence_length_distribution.png' % self.sample)
                    plot.add_caption(NoEscape(r'R2 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r2_summary_trim_dict.get('Sequence Length Distribution'))))

            with doc.create(Figure(position='!htb', placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Adapter Content')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%sR1_001_fastqc/Images/adapter_content.png' % self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r1_summary_trim_dict.get('Adapter Content') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get('Adapter Content') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get('Adapter Content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR1_001.qfilter_fastqc/Images/adapter_content.png' % self.sample)
                    plot.add_caption(NoEscape(r'R1 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r1_summary_trim_dict.get('Adapter Content'))))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%sR2_001_fastqc/Images/adapter_content.png' % self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r2_summary_trim_dict.get('Adapter Content') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get('Adapter Content') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get('Adapter Content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image('%sR2_001.qfilter_fastqc/Images/adapter_content.png' % self.sample)
                    plot.add_caption(NoEscape(r'R2 AFTER trimming \textcolor{%s}{%s}'
                                              % (colour, r2_summary_trim_dict.get('Adapter Content'))))

        doc.append(Command('FloatBarrier'))
        with doc.create(Section('BamStats')):
            with doc.create(Figure(position='htbp', placement=NoEscape(r'\centering'))):
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%s.bwa.drm.sorted.bam.stats-quals-hm.png' % self.sample)
                    plot.add_caption('Base quality per cycle')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('hspace', '10 mm'))
                    plot.add_image('%s.bwa.drm.sorted.bam.stats-insert-size.png' % self.sample)
                    plot.add_caption('Fragment size')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '10 mm'))
                    plot.add_image('%s.bwa.drm.sorted.bam.stats-quals2.png' % self.sample)
                    plot.add_caption('Quality per cycle')

        doc.generate_pdf('%ssample_quality' % self.sample, clean_tex=False, compiler=self.pdflatex)
Ejemplo n.º 43
0
geometry_options = {"margin": "0.5in"}
doc = Document(indent=False, geometry_options=geometry_options)
doc.change_length("\TPHorizModule", "1mm")
doc.change_length("\TPVertModule", "1mm")

with doc.create(MiniPage(width=r"\textwidth")) as page:
    with page.create(TextBlock(100, 0, 0)):
        page.append("**** Ten Thousand Dollars")

    with page.create(TextBlock(100, 0, 30)):
        page.append("COMPANY NAME")
        page.append("\nSTREET, ADDRESS")
        page.append("\nCITY, POSTAL CODE")

    with page.create(TextBlock(100, 150, 40)):
        page.append(HugeText(bold("VOID")))

    with page.create(TextBlock(80, 150, 0)):
        page.append("DATE")
        page.append(MediumText(bold("2016 06 07\n")))
        page.append(HorizontalSpace("10mm"))
        page.append(SmallText("Y/A M/M D/J"))

    with page.create(TextBlock(70, 150, 30)):
        page.append(MediumText(bold("$***** 10,000.00")))

    page.append(VerticalSpace("100mm"))

doc.generate_pdf("textblock", clean_tex=False)
Ejemplo n.º 44
0
    def create_pdf(self):
        """Creates a LaTeX PDF using the Python module PyLatex (https://jeltef.github.io/PyLaTeX/latest/).

            Note: LaTeX must be installed in /usr/local/. Development employed TexLive 2015.


        """
        doc = Document()
        doc.packages.append(Package('geometry', options=['tmargin=0.75in', 'lmargin=0.75in', 'rmargin=0.75in']))
        doc.packages.append(Package('datetime', options=['ddmmyyyy']))
        doc.packages.append(Package('needspace'))
        doc.preamble.append(Command('newdateformat',
                                    NoEscape(r'mydate}{\twodigit{\THEDAY}/\twodigit{\THEMONTH}/\THEYEAR')))
        doc.append(Command('begin', 'center'))
        doc.append(Command('Large', bold('MiSeq Quality Check')))
        doc.append(Command('end', 'center'))
        doc.append(Command('begin', 'flushright'))
        doc.append(Command('Large', '%s' % self.worksheet))
        doc.append(Command('end', 'flushright'))
        doc.append(Command('begin', 'flushright'))
        doc.append(Command('Large', NoEscape(r'\mydate\today')))
        doc.append(Command('end', 'flushright'))

        avg_qual = self.get_avg_qual()
        self.get_qual_graph(avg_qual)
        first_read, second_read = self.get_avg_qual_per_read()
        doc.append(Command('needspace', '20em'))
        with doc.create(Section('Quality data')):
            with doc.create(Tabular(NoEscape(r'p{5cm}|c|c'))) as table:
                table.add_row(('Data', 'Value', 'Pass/Fail'))
                table.add_hline()
                table.add_row(
                    ('Mean Cluster Density (k/mm2)', format(self.tile.mean_cluster_density / 1000, '.2f'), ''))
                table.add_row(('Clusters passed filter (%)', '%s' % (format(self.tile.percent_pf_clusters, '.2f')),
                               ''))
                table.add_row(('Average >= Q30', '%s' % (format(avg_qual, '.2f')), ''))
                table.add_row(('1st full read >= Q30', '%s' % (format(first_read, '.2f')), ''))
                table.add_row(('2nd full read >= Q30', '%s' % (format(second_read, '.2f')), ''))

            with doc.create(Figure(position='htbp', placement=NoEscape(r'\centering'))):
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_plot()
                    plot.add_caption('Q-score distribution plot (all reads all cycles)')
                self.get_qual_heatmap()
                with doc.create(SubFigure()) as plot:
                    plot.add_plot()
                    plot.add_caption('Q-score heat map')
                self.get_clusters_heatmap()
                with doc.create(SubFigure()) as plot:
                    plot.add_plot()
                    plot.add_caption('Cluster density per tile')
        read_1_phas, read_1_prephas, read_2_phas, read_2_prephas = self.get_phas_prephas()
        with doc.create(Section('Phas/Prephas data')):
            with doc.create(Tabular(NoEscape(r'p{5cm}|c|c'))) as table:
                table.add_row(('Data', 'Value', 'Pass/Fail'))
                table.add_hline()
                table.add_row(
                    ('1st full read', '%s / %s' % (format(read_1_phas, '.3f'), format(read_1_prephas, '.3f')), ''))
                table.add_row(
                    ('2nd full read', '%s / %s' % (format(read_2_phas, '.3f'), format(read_2_prephas, '.3f')), ''))
        sample_id, index1, index2, percent_clusters, percent_pf, total_aligned_clusters, pf_aligned_clusters = \
            self.get_indexing()
        total_samples = len(sample_id)

        doc.append(Command('needspace', '10em'))
        with doc.create(Section('Indexing')):
            doc.append(Command('begin', 'center'))
            with doc.create(Tabular(NoEscape(r'c|c|c|c|c'))) as table:
                table.add_row(('Total Reads', 'PF Reads', '% Reads Identified (PF)', 'Min', 'Max'))
                table.add_hline()
                table.add_row(
                    ('%s' % int(total_aligned_clusters), '%s' % int(pf_aligned_clusters), '%s' % percent_pf,
                     '%s' % min(percent_clusters), '%s' % max(percent_clusters)))
            doc.append(Command('end', 'center'))
            with doc.create(Figure(position='htbp', placement=NoEscape(r'\centering'))):
                with doc.create(Tabular(NoEscape(r'c|c|c|c'))) as table:
                    table.add_row(('Sample_ID', 'Index', 'Index2', '% Reads  Identified (PF)'))
                    table.add_hline()
                    item = 0
                    while item < total_samples:
                        table.add_row(('%s' % sample_id[item], '%s' % index1[item], '%s' % index2[item], '%s'
                                       % percent_clusters[item]))
                        item += 1
                with doc.create(SubFigure()) as plot:
                    plot.add_plot()

        doc.generate_pdf('%s_InterOp_Results' % self.worksheet, clean_tex=False, compiler=self.pdflatex)
Ejemplo n.º 45
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
                                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(StandAloneGraphic(image_options="width=120px",
                                filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
                                 pos='c', align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Bank Account Statement")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Date")))

    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(Tabularx(
                           "X X X X",
                           arguments=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_row(
                [MultiColumn(4, align='l', data=TextColor("blue", message))])
            footer_table.add_hline(color="blue")
            footer_table.add_empty_row()

            branch_address = MiniPage(
                width=NoEscape(r"0.25\textwidth"),
                pos='t')
            branch_address.append("960 - 22nd street east")
            branch_address.append("\n")
            branch_address.append("Saskatoon, SK")

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t', align='r')
            document_details.append("1000")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([branch_address, branch_address,
                                  branch_address, document_details])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        customer.append("Verna Volcano")
        customer.append("\n")
        customer.append("For some Person")
        customer.append("\n")
        customer.append("Address1")
        customer.append("\n")
        customer.append("Address2")
        customer.append("\n")
        customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
                          align='r')
        branch.append("Branch no.")
        branch.append(LineBreak())
        branch.append(bold("1181..."))
        branch.append(LineBreak())
        branch.append(bold("TIB Cheque"))

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(["date",
                            "description",
                            "debits($)",
                            "credits($)",
                            "balance($)"],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()
        row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
        for i in range(30):
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.append(NewPage())

    # Add cheque images
    with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
        cheque_file = os.path.join(os.path.dirname(__file__),
                                   'chequeexample.png')
        cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
        for i in range(0, 20):
            cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
Ejemplo n.º 46
0
	def CreateDoc(self, outputNameRef=[""], outputDir=""):
		
		def InsDatosEscolares(hasImage):

			with self.doc.create(Tabular(NoEscape("m{0.8in}m{0.6in}m{0.9in}m{1.5in}m{2.3in}"))) as table:
				if hasImage:
					image = MultiRow(3, data=Command("includegraphics", NoEscape(self.data["Foto"][self.data["Foto"].rfind("/") + 1:][:self.data["Foto"].rfind(".")]),["width=1.5in", "height=1in"]))					
				else:
					image = ""
				table.add_row(("","","","",""))
				table.add_row(("","","","", image))
				table.add_row((bold("Matrícula: "), self.data["Matrícula"], bold("Licenciatura: "), self.data["Licenciatura"], ""))
				table.add_row((bold("Semestre: "),self.data["Semestre"], bold("Generación: "), self.data["Generación"], ""))

		def InsDatosPersonales():
			with self.doc.create(SectionUnnumbered("Datos Personales")):
				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Apellido Paterno"], self.data["Apellido Materno"], self.data["Nombre"]))
					table.add_hline()
					table.add_row((bold("Apellido Paterno"), bold("Apellido Materno"), bold("Nombre")))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Lugar de Nacimiento"], self.data["Fecha de Nacimiento"], self.data["Nacionalidad"]))
					table.add_hline()
					table.add_row((bold("Lugar de Nacimiento"), bold("Fecha de Nacimiento"), bold("Nacionalidad")))
			
		def InsDatosDomicilio():
			with self.doc.create(SectionUnnumbered("Domicilio Particular")):
				Command("vspace", NoEscape("-1ex"))
				with self.doc.create(Tabular(NoEscape("m{1.33in}m{0.6in}m{2in}m{1.9in}"))) as table:
					table.add_row((self.data["Calle"], self.data["Número"], self.data["Colonia"], self.data["Población"]))
					table.add_hline()
					table.add_row((bold("Calle"), bold("Número"), bold("Colonia"), bold("Poblacion")))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Municipio"], self.data["Estado"], self.data["C.P."]))
					table.add_hline()
					table.add_row((bold("Municipio"), bold("Estado"), bold("C.P.")))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Particular"], self.data["Teléfono Celular"], self.data["Correo"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))

		def InsDatosTrabajo():
			with self.doc.create(SectionUnnumbered("Datos del Trabajo")):
				Command("vspace", NoEscape("-1ex"))
				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\"\
					.format(bold("Empresa o Institución"), makeUnderline(self.data["Empresa"], 2.5),bold("Teléfono"), makeUnderline(self.data["Teléfono Empresa"], 1.65))
					))

				with self.doc.create(Tabular(NoEscape("m{1.3in}m{0.6in}m{2in}m{1.9in}"))) as table:
					table.add_row((self.data["Calle Empresa"], self.data["Número Empresa"], self.data["Colonia Empresa"], self.data["Municipio Empresa"]))
					table.add_hline()
					table.add_row((bold("Calle"), bold("Número"), bold("Colonia"), bold("Municipio")))

		def InsDatosFamiliares():
			with self.doc.create(SectionUnnumbered("Datos Familiares")):
				Command("vspace", NoEscape("-1ex"))
				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\{}: {} {}: {}\\"\
					.format(bold("Nombre del Padre"), makeUnderline(self.data["Nombre del Padre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Padre"], 1.65),\
						bold("Domicilio"), makeUnderline(self.data["Dirección Padre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Padre"], 1.63))
					))
			
				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Padre"], self.data["Celular Padre"], self.data["Correo Padre"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))

				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\{}: {} {}: {}\\"\
					.format(bold("Nombre de la Madre"), makeUnderline(self.data["Nombre de la Madre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Madre"], 1.55),\
						bold("Domicilio"), makeUnderline(self.data["Dirección Madre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Madre"], 1.63))
					))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Madre"], self.data["Celular Madre"], self.data["Correo Madre"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))
		
		def InsDatosEmergencia():
			with self.doc.create(SectionUnnumbered("En caso de emergencia")):
				Command("vspace", NoEscape("-1ex"))
				self.doc.append(NoEscape(\
					r"{}{} {}: {} \\{}: {}\\"\
					.format(bold("¿Padece alguna enfermedad?"), makeUnderline(self.data["¿Enfermedad?"], 0.2),bold("Especifique"), makeUnderline(self.data["Enfermedad"], 3.4), bold("Tipo de Sangre"), makeUnderline(self.data["Tipo de Sangre"], .5))
					))

				self.doc.append(NoEscape(\
					r"{}:\\{}: {} {}: {}\\ "\
					.format(bold("Contactar a"), bold("Nombre"), makeUnderline(self.data["Nombre Contacto"], 3.52),bold("Parentesco"), makeUnderline(self.data["Parentesco"], 1.5))
					))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Contacto"], self.data["Celular Contacto"], self.data["Correo Contacto"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))

				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\"\
					.format(bold("Domicilio"), makeUnderline(self.data["Dirección Contacto"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Contacto"], 1.63))
					))

		if outputDir is "":
			outputDir = os.sys.path[0]
		#self.doc = Document()

		hasImage = self.data["Foto"] != ""
		
		self.doc.packages.append(Package("geometry", options=["a4paper"]))
		self.doc.packages.append(Package("array"))
		self.doc.packages.append(Package("fullpage"))

		self.doc.preamble.append(Command("title", bold(NoEscape(r"Solicitud de Inscripción"))))
		self.doc.preamble.append(Command('date', Command("vspace", NoEscape("-15ex"))))
		self.doc.preamble.append(Command("pagenumbering", "gobble"))
		self.doc.preamble.append(Command("hfuzz=2cm"))
		if hasImage:
			self.doc.packages.append(Package("graphicx"))
			self.doc.preamble.append(Command("graphicspath", NoEscape("{}".format("{" + self.data["Foto"][:self.data["Foto"].rfind("/")] +"/}"))))
		
		self.doc.append(NoEscape(r'\maketitle'))

		self.doc.append(NoEscape(r"\noindent"))
		InsDatosEscolares(hasImage)
		InsDatosPersonales()
		InsDatosDomicilio()
		InsDatosTrabajo()
		InsDatosFamiliares()
		InsDatosEmergencia()

		self.doc.append(NoEscape("{} {}: {}".format(Command("hfill").dumps(), bold("Fecha"), self.data["Fecha"])))

		outputName = "Inscripción_" + str("{}_" * len(outputNameRef)).format(*[self.data[x] for x in outputNameRef])[:-1]
		outputName = outputName.replace(" ", "_")

		self.doc.generate_tex("{}/{}".format("Outputs", outputName))
		os.system("{} {}/{}.tex -output-directory={}".format("pdflatex", "Outputs", outputName, outputDir))
		os.startfile("{}/{}.pdf".format(outputDir, outputName))
		os.remove("{}/{}.AUX".format(outputDir, outputName))
		os.remove("{}/{}.log".format(outputDir, outputName))
Ejemplo n.º 47
0
		def InsDatosFamiliares():
			with self.doc.create(SectionUnnumbered("Datos Familiares")):
				Command("vspace", NoEscape("-1ex"))
				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\{}: {} {}: {}\\"\
					.format(bold("Nombre del Padre"), makeUnderline(self.data["Nombre del Padre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Padre"], 1.65),\
						bold("Domicilio"), makeUnderline(self.data["Dirección Padre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Padre"], 1.63))
					))
			
				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Padre"], self.data["Celular Padre"], self.data["Correo Padre"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))

				self.doc.append(NoEscape(\
					r"{}: {} {}: {}\\{}: {} {}: {}\\"\
					.format(bold("Nombre de la Madre"), makeUnderline(self.data["Nombre de la Madre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Madre"], 1.55),\
						bold("Domicilio"), makeUnderline(self.data["Dirección Madre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Madre"], 1.63))
					))

				with self.doc.create(Tabular(NoEscape("m{2in}m{2in}m{2in}"))) as table:
					table.add_row((self.data["Teléfono Madre"], self.data["Celular Madre"], self.data["Correo Madre"]))
					table.add_hline()
					table.add_row((bold("Teléfono Particular"), bold("Teléfono Celular"), bold("Correo Electrónico")))
Ejemplo n.º 48
0
v = VectorName(name='')

M = np.matrix([[2, 3, 4],
               [0, 0, 1],
               [0, 0, 2]])
m = Matrix(matrix=M, name='', mtype='p', alignment=None)

# Package
p = Package(name='', base='usepackage', options=None)

# PGFPlots
tikz = TikZ(data=None) 

a = Axis(data=None, options=None) 

p = Plot(name=None, func=None, coordinates=None, options=None)

# Utils
escape_latex(s='')

fix_filename(filename='')

dumps_list(l=[], escape=False, token='\n')

bold(s='')

italic(s='')

verbatim(s='', delimiter='|')

Ejemplo n.º 49
0
    def tabulateAll(self):
        """
        Create a table that summarises all input variables and additive
        components, including the constant kernel as baseline and the final
        full additive model.
        """
        # 1-D variables
        ks = self.best1d[:]
        # Baseline: constant kernel
        ks.append(self.constker)
        # Additive components, if not 1-D
        for k in self.summands:
            if len(k.getActiveDims()) > 1:
                ks.append(k)
        # Full additive model, if involves more than one additive term
        best = self.history[-1]
        if len(self.summands) > 1:
            ks.append(best)

        ks.sort(key=lambda k: round(k.getNLML(), 2))
        ks.sort(key=lambda k: round(k.error(), 4))
        data = ks[0].data
        ds = data.getDataShape()

        nlml_min = round(min([k.getNLML() for k in ks]), 2)
        error_min = round(min([k.error() for k in ks]), 4)

        doc = self.doc
        with doc.create(pl.Table(position='htbp!')) as tab:
            caption_str = "Classification performance of the full model, its additive components (if any), all input variables, and the baseline."
            tab.add_caption(ut.NoEscape(caption_str))

            t = pl.Tabular('rlrr')
            # Header
            t.add_hline()
            t.add_row((
                pl.MultiColumn(1, align='c', data='Dimensions'),
                pl.MultiColumn(1, align='c', data='Kernel expression'),
                pl.MultiColumn(1, align='c', data='NLML'),
                pl.MultiColumn(1, align='c', data='Error') ))
            t.add_hline()

            # Entries
            for k in ks:
                if k is self.constker:
                    row = [
                        ut.italic('--', escape=False),
                        ut.italic('$' + k.latex() + '$ (Baseline)', escape=False),
                        ut.italic('{0:.2f}'.format(k.getNLML()), escape=False),
                        ut.italic(r'{0:.2f}\%'.format(k.error()*100), escape=False) ]
                else:
                    dims = sorted(k.getActiveDims())
                    row = [
                        ut.NoEscape(', '.join([str(d + 1) for d in dims])),
                        ut.NoEscape('$' + k.latex() + '$'),
                        ut.NoEscape('{0:.2f}'.format(k.getNLML())),
                        ut.NoEscape(r'{0:.2f}\%'.format(k.error()*100)) ]
                if round(k.getNLML(), 2) == nlml_min:
                    row[2] = ut.bold(row[2])
                if round(k.error(), 4) == error_min:
                    row[3] = ut.bold(row[3])

                t.add_row(tuple(row))

            t.add_hline()

            tab.append(ut.NoEscape(r'\centering'))
            tab.append(t)