def to_report(self, file_name):
     replace_word = {
         'articleTitle': 'Literature Report',
         'arcticleabstract': 'Abstract'
     }
     doc = Article(
         r'D:\github\pluto\lib\base\pylatex\template\article_template_02.tex',
         replace_word)
     for item in self.literatures:
         title = escape_latex(item['title'])
         doc.document.add_section(title, 3)
         doc.document.add_list([
             '---'.join([
                 item['journal'],
                 str(item['year']), ','.join(item['authors'])
             ])
         ],
                               type=1)
         abstract = item.get('abstract')
         if abstract is not None:
             abstract = escape_latex(abstract)
             doc.document.append(abstract)
     #doc.document.generate_tex(r'E:\github\latexdoc\latexdoc\template\academicjournal\wlscirep\plutopaper.tex')
     doc.document.generate_pdf(
         r'D:\github\pluto\lib\base\pylatex\template\output\{}'.format(
             file_name))
예제 #2
0
def dot_to_vgroup(source):
    A = pgv.AGraph(source)
    A.layout(prog='dot')

    # DEBUG: draw the dot layout in png files
    global rendered_graphs
    A.draw(f'{rendered_graphs}.png')
    rendered_graphs += 1

    ratio, shift = scale_ratio_and_shift(A)

    # spawn each node in manim using the graphviz positions and our rescaling
    # ratio
    mnodes = []
    for node in A.iternodes():
        # 'point' shaped nodes aren't real nodes, they often represent the
        # origin of the arrow of an initial stat or the destination of the
        # arrow of a final state
        if node.attr['shape'] == 'point':
            continue

        x, y = map(lambda s: float(s), node.attr['pos'].split(','))
        pos = np.array([x * ratio, y * ratio, 0])

        # Try to translate graphviz color to manim, fallback to white
        color = dot_to_manim_colors.get(node.attr.get('fillcolor', 'white'),
                                        mn.WHITE)

        # Render the node's label and circle
        mlabel = mn.TextMobject(escape_latex(node.name)).move_to(pos)
        mcircle = Node(arc_center=pos, color=color)
        mnodes.append(mn.VGroup(mcircle, mlabel))

    # spawn each edges in a similar way
    medges = []
    for edge in A.edges():
        # edge.attr['pos'] contains a list of spline control points of the
        # form: 'e,x1,y1 x2,y2 x3,y3 x4,y4 […]'
        spline_points = [
            np.array([float(x) * ratio, float(y) * ratio, 0]) for x, y in
            [point.split(',') for point in edge.attr['pos'][2:].split()[1:]]
        ]

        # Try to translate graphviz color to manim, fallback to white
        color = dot_to_manim_colors.get(edge.attr.get('color', 'white'),
                                        mn.WHITE)

        # Render the edge's label and path
        mpath = mn.VMobject(color=color).set_points_smoothly(spline_points)
        if 'label' in edge.attr and edge.attr['label']:
            (labelx, labely) = map(float, edge.attr['lp'].split(','))
            mlabel = mn.TextMobject(escape_latex(edge.attr['label']))
            mlabel.scale(0.65)
            mlabel.move_to(np.array([labelx * ratio, labely * ratio, 0]))
            medges.append(mn.VGroup(mpath, mlabel))
        else:
            medges.append(mpath)
        print(len(spline_points))
    return mn.VGroup(*mnodes, *medges).shift(shift)
예제 #3
0
    def render_table(self,
                     doc: Document,
                     name_override: Optional[LatexObject] = None,
                     toc_ref: Optional[str] = None,
                     extra_rows: Optional[List[Tuple[str, Any]]] = None) -> None:
        """Write this table into a LaTeX document.

        Args:
            doc: The LaTeX document to be appended to.
            name_override: An optional replacement for this table's name field.
            toc_ref: A reference to be added to the table of contents.
            extra_rows: Any extra rows to be added to the table before the kwargs.
        """
        with doc.create(Table(position='htp!')) as table:
            table.append(NoEscape(r'\refstepcounter{table}'))
            table.append(Label(Marker(name=str(self.fe_id), prefix="tbl")))
            if toc_ref:
                table.append(NoEscape(r'\addcontentsline{toc}{subsection}{' + escape_latex(toc_ref) + '}'))
            with doc.create(Tabularx('|lX|', booktabs=True)) as tabular:
                package = Package('xcolor', options='table')
                if package not in tabular.packages:
                    # Need to invoke a table color before invoking TextColor (bug?)
                    tabular.packages.append(package)
                package = Package('seqsplit')
                if package not in tabular.packages:
                    tabular.packages.append(package)
                tabular.add_row((name_override if name_override else bold(self.name),
                                 MultiColumn(size=1, align='r|', data=TextColor('blue', self.fe_id))))
                tabular.add_hline()
                type_str = f"{self.type}"
                match = re.fullmatch(r'^<.* \'(?P<typ>.*)\'>$', type_str)
                type_str = match.group("typ") if match else type_str
                tabular.add_row(("Type: ", escape_latex(type_str)))
                if self.path:
                    if isinstance(self.path, LatexObject):
                        tabular.add_row(("", self.path))
                    else:
                        tabular.add_row(("", escape_latex(self.path)))
                for k, v in self.fields.items():
                    tabular.add_hline()
                    tabular.add_row((f"{k.capitalize()}: ", v))
                if self.args:
                    tabular.add_hline()
                    tabular.add_row(("Args: ", self.args))
                if extra_rows:
                    for (key, val) in extra_rows:
                        tabular.add_hline()
                        tabular.add_row(key, val)
                if self.kwargs:
                    tabular.add_hline()
                    for idx, (kwarg, val) in enumerate(self.kwargs.items()):
                        tabular.add_row((italic(kwarg), val), color='white' if idx % 2 else 'black!5')
예제 #4
0
파일: args.py 프로젝트: Neraste/PyLaTeX
def test_utils():
    # Utils
    escape_latex(s="")

    fix_filename(path="")

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

    bold(s="")

    italic(s="")

    verbatim(s="", delimiter="|")
예제 #5
0
파일: args.py 프로젝트: ycchen1989/PyLaTeX
def test_utils():
    # Utils
    escape_latex(s='')

    fix_filename(path='')

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

    bold(s='')

    italic(s='')

    verbatim(s='', delimiter='|')
예제 #6
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='|')
예제 #7
0
파일: pdfs.py 프로젝트: yssmcl/fly
def gerar_pdf_parecer(parecer):
    doc = pdfutils.init_document()

    pdfutils.pacotes(doc)

    # Configurações (preâmbulo)
    pdfutils.configuracoes_preambulo(doc)

    pdfutils.cabecalho(doc)

    frase_anexo = 'ANEXO XI DA RESOLUÇÃO Nº 236/2014-CEPE, DE 13 DE NOVEMBRO DE 2014.'
    pdfutils.rodape(doc, NoEscape(r'\texttt{' + frase_anexo + '}%'))
    doc.append(NoEscape(r'{\normalsize\texttt{' + frase_anexo + '}}%'))

    pdfutils.titulo(doc, 'RELATÓRIOS ESPECÍFICOS PARA ATIVIDADES DE EXTENSÃO',
                    'FORMULÁRIO ÚNICO DE PARECER DE ATIVIDADES DE EXTENSÃO')

    # Início do formulário
    with doc.create(Enumerate()) as enum:
        pdfutils.item(doc, enum, 'PARECER CONCLUSIVO DA COMISSÃO DE EXTENSÃO DE CENTRO')

    doc.append(bold('IDENTIFICAÇÃO:'))
    doc.append(NewLine())
    doc.append(NoEscape(r'Coordenador(a): {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.nome_completo))))
    doc.append(NoEscape(r'Colegiado: {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.colegiado))))
    doc.append(NoEscape(r'Centro: {} \\'.format(parecer.projeto_extensao.centro.nome)))
    doc.append(NoEscape(r'Campus: {} \\'.format(parecer.projeto_extensao.campus.nome)))
    doc.append(NoEscape(r'Título da atividade: {} \\ \\'.format(escape_latex(parecer.projeto_extensao.titulo))))
    # TODO: referente a portaria?
    # doc.append(NoEscape(r'Parecer referente a: \\ \\'))

    doc.append(bold(NoEscape(r'COMENTÁRIOS: \\')))
    pdfutils.tabela_alternativas(doc, EstadoProjeto, '|c|X|X|c|c|', id=parecer.estado_parecer.id)
    doc.append(NewLine())
    doc.append(NewLine())
    doc.append(NoEscape(r'Ata nº: {} \\'.format(escape_latex(parecer.numero_ata))))
    data = parecer.data.strftime('%d/%m/%Y')
    doc.append(NoEscape(r'Data: {} \\'.format(data)))

    texto = 'Carimbo e Assinatura do Coordenador(a) da Comissão de Extensão ou Representante Legal'
    largura = Command('widthof', texto).dumps()
    pdfutils.assinatura(doc, texto, largura, Center())

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

    filepath = '{}/parecer_{}_projeto_{}'.format(PDF_DIR, str(parecer.id), str(parecer.projeto_extensao.id))
    doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS)

    return filepath
예제 #8
0
def de_raw(s: tokens.Raw):
    if isinstance(s.parent, (lines.Raw, tokens.InFormula)):
        return NoEscape(''.join(s.inner_token))
    elif isinstance(s.parent.parent, (env.Formula)):
        return NoEscape(''.join(s.inner_token))
    else:  # 当 父节点不是 lines.Raw 时, Raw 中的字符需要 escape,如 InFormula,InCode
        return escape_latex(''.join(s.inner_token))
예제 #9
0
def make_projects(data={}):
    """
    make_projects

    This function obtains all the information needed from the
    @data dictionary to construct the projects section.

    @data should have this dictionary structure:
    data = {
        ...,
        "Projects": [
            ...,
            {
                "name": "",             # string
                "description": "",      # string
                "link": "URL"           # string
            },
            ...,
        ],
        ...,
    }

    Returns a string with the LaTex code of this section
    """
    if not data or data == {}:
        return ""
    s = ""
    if data.get("Projects") and len(data.get("Projects")) != 0:
        project_tags = [
            'role',
            'company',
            'start_year',
            'location',
            # 'description'
        ]
        s = s + """\\cvsection{Projects}"""
        for idx, project in enumerate(data.get("Projects")):
            if idx != 0:
                s = s + "\n\\divider"
            description = "\n\\cvevent"
            for tag in project_tags:
                if tag == 'start_year':
                    description = description + "{{{} -- {}}}".format(project.get("start_year"),
                                                                      project.get("end_year"))
                    continue
                if tag in project and project.get(tag):
                    description = description + \
                        "{{{}}}".format(project.get(tag))
                else:
                    description = description + "{}"

            s = s + description
            if project.get("description") is not None:
                project['description'] = r'{}'.format(project['description'])
                project['description'] = project['description'].replace(
                    '\n\n', '\n')
                project['description'] = escape_latex(project['description'])
                s = s + """\n\\begin{{itemize}}\n \\item {}\n\\end{{itemize}}""".format(
                    project.get("description"))
    return s
예제 #10
0
def test():
    doc = Document("utils_escape_latex")
    section = Section('Escape LaTeX characters test')

    text = escape_latex('''\
    & (ampersand)
    % (percent)
    $ (dollar)
    # (number)
    _ (underscore)
    { (left curly brace)
    } (right curly brace)
    ~ (tilde)
    ^ (caret)
    \\ (backslash)
    --- (three minuses)
    a\xA0a (non breaking space)
    [ (left bracket)
    ] (right bracket)
    ''')

    section.append(text)
    doc.append(section)

    doc.generate_pdf()
예제 #11
0
 def iter_rows_heads(self):
     row_idx = 0
     for path_idx, (path, outer_docs) in enumerate(
         key_group_by(self.docs, lambda doc: doc["path"])
     ):
         row_head = []
         if path_idx > 0:
             row_head.append("\\midrule\n")
         doc_groups = list(key_group_by(outer_docs, lambda doc: doc["disp"]))
         prefix = (
             r"\multirow{"
             + str(len(doc_groups))
             + "}{*}{"
             + " ".join(p.title() for p in path)
             + "}"
         )
         padding = len(prefix)
         row_head.append(prefix)
         for idx, (disp, inner_docs) in enumerate(doc_groups):
             if idx != 0:
                 row_head = []
                 row_head.append(" " * padding)
             row_head.append(r" & ")
             row_head.append(escape_latex(disp) + " & ")
             yield row_idx, InFilter(inner_docs), "".join(row_head)
         row_idx += 1
예제 #12
0
def test():
    doc = Document("utils_escape_latex")
    section = Section('Escape LaTeX characters test')

    text = escape_latex('''\
    & (ampersand)
    % (percent)
    $ (dollar)
    # (number)
    _ (underscore)
    { (left curly brace)
    } (right curly brace)
    ~ (tilde)
    ^ (caret)
    \\ (backslash)
    --- (three minuses)
    a\xA0a (non breaking space)
    [ (left bracket)
    ] (right bracket)
    ''')

    section.append(text)
    doc.append(section)

    doc.generate_pdf()
예제 #13
0
 def _construct_title_page(self):
     authors = '\\\\ '.join([escape_latex(a) for a in self.authors()])
     return [
         Command('title', [self.title]),
         NoEscape('\\author{{ \\textbf{{Authors}} \\\\ {} }}'.format(authors)),
         Command('maketitle'),
     ]
예제 #14
0
def make_education(data={}):
    """
    make_education

    This function obtains all the information needed from the
    @data dictionary to construct the Education section.

    @data should have this dictionary structure:
    data = {
        ...,
        "Education": {
            "degree": "",           # string
            "school": "",           # string
            "start_year":  0,       # num - YYYY
            "end_year":  0,         # num - YYYY
            "description": ""       # string
        }
        ...,
    }

    Returns a string with the LaTex code of this section
    """
    if not data or data == {}:
        return ""
    s = ""
    if data.get("Education") and len(data.get("Education")) != 0:
        edu_tags = [
            'degree',
            'school',
            'start_year',
            'location',
            # 'description'
        ]
        s = s + """\n\\cvsection{Education}"""
        for idx, edu in enumerate(data.get("Education")):
            if idx != 0:
                s = s + "\n\\divider"
            description = "\n\\cvevent"
            for tag in edu_tags:
                if tag == 'start_year':
                    description = description + "{{{} -- {}}}".format(edu.get("start_year"),
                                                                      edu.get("end_year"))
                    continue
                if tag in edu and edu.get(tag):
                    description = description + "{{{}}}".format(edu.get(tag))
                else:
                    description = description + "{}"

            s = s + description
            if edu.get("description") is not None:
                # Information in description may have multiple newlines, and escape characters
                # so it needs to be pre-parsed to an understandable sytanxis for LaTex
                edu['description'] = r'{}'.format(edu['description'])
                edu['description'] = edu['description'].replace('\n\n', '\n')
                # Parsing descripton to LaTex sytanxis
                edu['description'] = escape_latex(edu['description'])
                s = s + """\n\\begin{{itemize}}\n \\item {} \n\\end{{itemize}}""".format(
                    edu.get("description"))
    return s
예제 #15
0
    def _generate_latex_for_act(self, act):
        act_latex = []

        act_date = act['date'].strftime("%B %Y")
        act_latex.append(NoEscape('\\newact{{ {} }}\n\n'.format(escape_latex(act_date))))

        for scene in act['scenes']:
            act_latex.extend(self._generate_latex_for_scene(scene))
        
        return act_latex
예제 #16
0
 def iter_rows_heads(self):
     row_headings = self.get_nested_row_headings()
     for row_num, (comb, filter, row_heading) in enumerate(
         zip(self.combs, self.iter_filters(), row_headings)
     ):
         if self.spec.flat_headings:
             head_latex = escape_latex(str_of_comb(comb)) + " & "
         else:
             head_latex = row_heading_latex(row_heading)
         yield row_num, filter, head_latex
예제 #17
0
 def __hyperlink(url, description):
     """
     Construct a LaTeX hyperref from the URL and its description provided.
     :param url: URL address
     :param description: URL description
     :return: Raw string representing hyperref
     """
     description = escape_latex(description)
     return NoEscape(r"\href{" + url + r"}{\underline{" + description +
                     "}}")
예제 #18
0
파일: basic.py 프로젝트: rfilmyer/PyLaTeX
def fill_document(doc):
    """Add a section, a subsection and some text to the document.

    :param doc: the document
    :type doc: :class:`pylatex.document.Document` instance
    """
    with doc.create(Section('A section')):
        doc.append('Some regular text and some ' + italic('italic text. '))

        with doc.create(Subsection('A subsection')):
            doc.append(escape_latex('Also some crazy characters: $&#{}'))
예제 #19
0
파일: basic.py 프로젝트: Hydex/PyLaTeX
def fill_document(doc):
    """Adds a section, a subsection and some text to the document.

        :param doc: the document
        :type doc: :class:`pylatex.Document` instance
    """
    with doc.create(Section('A section')):
        doc.append('Some regular text and some ' + italic('italic text. '))

        with doc.create(Subsection('A subsection')):
            doc.append(escape_latex('Also some crazy characters: $&#{}'))
예제 #20
0
 def print(self, outf=sys.stdout):
     if self.spec.flat_headings:
         row_headings_columns = "l "
     else:
         row_headings_columns = "l " * self.x_groups.num_tiers()
     col_headings = ""
     y_sep_slices = self.y_groups.get_sep_slices(self.spec.flat_headings)
     for idx in range(self.y_groups.num_combs()):
         if idx > 0 and idx % y_sep_slices == 0:
             col_headings += "| "
         col_headings += "r "
     x_sep_slices = self.x_groups.get_sep_slices(self.spec.flat_headings)
     outf.write(r"\begin{tabular}{ " + row_headings_columns + col_headings + "}\n")
     outf.write("\\toprule\n")
     outf.write(self.y_groups.col_heads_latex(self.x_groups.num_tiers()))
     for row_num, x_filter, head_latex in self.x_groups.iter_rows_heads():
         if (
             not self.spec.flat_headings
             and row_num > 0
             and row_num % x_sep_slices == 0
         ):
             min_div_idx = self.x_groups.min_div_idx(row_num)
             outf.write(
                 "\\cline{"
                 + str(min_div_idx + 1)
                 + "-"
                 + str(len(self.x_groups.divs) + self.y_groups.num_combs())
                 + "}\n"
             )
         outf.write(head_latex)
         for col_num, y_filter in enumerate(self.y_groups.iter_filters()):
             opts = AndFilter(x_filter, y_filter)
             picked_doc = filter_docs(self.docs, opts)
             if len(picked_doc) == 1:
                 with doc_highlights(picked_doc[0], outf):
                     outf.write(
                         escape_latex(
                             str(
                                 pick_str(
                                     picked_doc[0]["measures"],
                                     self.spec.measure.get_measures(picked_doc[0])[
                                         0
                                     ],
                                 )
                             )
                         )
                     )
             else:
                 outf.write("---")
             if col_num < self.y_groups.num_combs() - 1:
                 outf.write(" & ")
         outf.write(" \\\\\n")
     outf.write("\\bottomrule\n")
     outf.write("\\end{tabular}")
예제 #21
0
def tabela_discentes(doc, projeto_extensao):
    table_spec = NoEscape(r'''|>{\centering\arraybackslash}X|
                              >{\centering\arraybackslash}X|
                              @{  }c@{  }|
                              @{  }c@{  }|
                              >{\centering\arraybackslash}X|
                              @{  }c@{  }|
                          ''')
    cabecalho_tabela = [
        'NOME COMPLETO', 'CURSO', 'SÉRIE', 'TURNO', 'C/H SEMANAL',
        'TELEFONE E E-MAIL'
    ]

    doc.append(NoEscape('{\scriptsize'))

    with doc.create(Tabularx(table_spec,
                             width_argument=WIDTH_ARGUMENT)) as tab:
        tab.add_hline()
        tab.add_row(cabecalho_tabela)
        tab.add_hline()

        discentes = Discente_CursoExtensao.objects.filter(
            curso_extensao_id=projeto_extensao.id)
        for discente in discentes:
            linha = [
                escape_latex(discente.nome),
                escape_latex(discente.curso.nome),
                discente.serie,
                discente.turno.nome,
                discente.carga_horaria_semanal,
                # TODO: hifenizar email
                NoEscape(r'\makecell{{ {}; \\ {} }}'.format(
                    escape_latex(discente.telefone),
                    escape_latex(discente.email)))
            ]
            tab.add_row(linha)
            tab.add_hline()

    mdframed_plano_trabalho(doc, discentes)

    doc.append(NoEscape('}'))  # volta com tamanho normal da fonte
예제 #22
0
 def addTable(self, data=None,nrow=None,ncol=None):
     # 初始化参数
     tabsize = '|' + '|'.join(['c']*ncol) + '|'
     mtable = Tabular(tabsize)
     for i in range(nrow):
         mtable.add_hline()
         mtable.add_row(tuple([escape_latex(str(item)) for item in data[i]]))
     mtable.add_hline()
     self.content.append(Command('begin',arguments='center'))
     #self.content.append('这是我们写的歌\par')
     self.content.append(mtable)
     self.content.append(Command('end',arguments='center'))
예제 #23
0
def ent_ri_upsell_report(filename):
	# Get todays date
	today = datetime.today().date()
	last_month = date(today.year, today.month-1, 1)
	# Import Data
	df = rp.read_csv(filename)
	# Start Doc
	doc = lb.start_doc("ENT RI Up-Sell Report (%s)"%last_month.strftime("%b-%y"))
	# Get Data
	tables, images = rp.ent_ri_upsell_opp(df)
	# Get report sections
	sections = []
	for table in tables:
		try:
			sections.append(table['territory'])
		except KeyError:
			pass
	sections = sorted(set(sections))
	# note for tables
	note = "'Total EC2' is a sum of OnDemand, Spot and RI utility costs. It does not include any RI one-off payments. One-off payments are\
	included in the 'Total Revenue' figure."
	# Overview
	with doc.create(Section("Overview")):
		doc.append("This document aggregates EC2 spend information across customer \
			accounts by territor in UKIR ENT and then makes some estimations as to RI \
			up-front cost opportunity. \\textbf{This estimation is not exact, do not \
			share directly with customers.} Current RI opportunity estimates are \
			calculated using an observed relationship between On Demand spend and\
			the results of 'Mark Estes Tool' and are typically conservative (underestimates). True RI up-front and ongoing costs \
			depend on instance type, OS and volume discounts and therefore still \
			need to be generated on an account-by-account basis. I am working on automating this.")
	for table in tables:
		try:			
			if table['section'] == 'Overview':
				lb.include_table(doc, table['file'], table['name'], notes=note)
		except KeyError:
			pass

	lb.add_page(doc)
	# Add Sections
	for section in sections:
		doc.append("\\begin{landscape}")
		with doc.create(Section("%s"%escape_latex(section))):
			doc.append("\\label{sec:%s}"%re.sub(r'[^a-zA-Z0-9]',' ', section))
			for table in tables:
				try:
					if table['territory'] == section:
						lb.include_table(doc, table['file'], table['name'], notes=note)
				except KeyError:
					pass
		doc.append("\\end{landscape}")
		#lb.add_page(doc)
	return doc
예제 #24
0
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl',
                   title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'),
                   temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(
        Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols - 1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith(
                        'Test'):
                    ss_table.add_multicolumn(num_cols, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
예제 #25
0
def tabela_gestao_recursos_financeiros(doc, enum, previsao_orcamentaria):
    item(doc, enum, NoEscape(r'GESTÃO DOS RECURSOS FINANCEIROS: '))

    doc.append(Command('noindent'))
    with doc.create(Enumerate(options={'leftmargin': '7pt'})) as subenum:
        subenum.add_item(
            bold(NoEscape(r'ÓRGÃO GESTOR DOS RECURSOS FINANCEIROS \\')))

    with doc.create(MdFramed(options=MDFRAMED_OPTIONS)):
        doc.append(NoEscape(r'IDENTIFICAÇÃO: \\'))

        for tipo_gestao in TipoGestaoRecursosFinanceiros.objects.all():
            nome_tipo_gestao = tipo_gestao.nome.upper()

            if previsao_orcamentaria.identificacao and previsao_orcamentaria.identificacao.id == tipo_gestao.id:
                marcador = TIMES
            else:
                marcador = PHANTOM

            if nome_tipo_gestao in ('PRAP', 'SECRETARIA FINANCEIRA',
                                    'UNIOESTE'):
                doc.append(
                    NoEscape(r'({}) {} \\'.format(marcador, nome_tipo_gestao)))
            elif nome_tipo_gestao in 'FUNDAÇÃO':
                doc.append(
                    NoEscape(r'({}) {}: '.format(marcador,
                                                 bold(nome_tipo_gestao))))
                if previsao_orcamentaria.fundacao:
                    doc.append(escape_latex(previsao_orcamentaria.fundacao))
                    doc.append(NewLine())
            else:  # outros
                doc.append(
                    NoEscape(r'({}) {}: '.format(marcador,
                                                 bold(nome_tipo_gestao))))
                if previsao_orcamentaria.outro_orgao_gestor:
                    doc.append(
                        escape_latex(previsao_orcamentaria.outro_orgao_gestor))
                    doc.append(NewLine())
예제 #26
0
def mdframed_plano_trabalho(doc, objs):
    doc.append(LineBreak())

    mdframed_options_plano = 'innertopmargin=5pt, innerleftmargin=3pt, innerrightmargin=3pt, topline=false'

    with doc.create(MdFramed(options=mdframed_options_plano)):
        doc.append(bold('PLANO DE TRABALHO: '))

        planos = []
        for obj in objs:
            planos.append(obj.plano_trabalho)

        for plano in planos:
            doc.append(escape_latex(plano))
            doc.append(NewLine())
예제 #27
0
def escape_with_listings(string: str) -> NoEscape:
    """
    Escape LaTeX characters except code listings. All Atlassian code listings and noformat blocks are converted
    to the corresponding LaTeX ones.
    :param string: String containing text without escaping and with Atlassian code listings
    :return: Formatted string
    """
    string = string.replace('\r\n', '\n').replace(' \n', '')
    string, extracted_listing_blocks = escape_listings(string)
    string, extracted_noformat_blocks = escape_noformat(string)

    string = escape_latex(string)
    for block in extracted_listing_blocks + extracted_noformat_blocks:
        key, content = block
        string = string.replace(key, content, 1)
    return NoEscape(string)
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl', title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'), temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols-1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith('Test'):
                    ss_table.add_multicolumn(num_cols, 'l', escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
예제 #29
0
    def add_table(self, data=None,nrow=None,ncol=None):
        '''添加表格

        :param data: 表格数据
        :param nrow: 表格行数
        :param ncol: 表格列数
        :return: 无返回值
        '''
        tabsize = '|' + '|'.join(['c']*ncol) + '|'
        mtable = Tabular(tabsize)
        for i in range(nrow):
            mtable.add_hline()
            mtable.add_row(tuple([escape_latex(str(item)) for item in data[i]]))
        mtable.add_hline()
        self.content.append(Command('begin',arguments='center'))
        self.content.append(mtable)
        self.content.append(Command('end',arguments='center'))
예제 #30
0
 def col_heads_latex(self, x_tiers):
     res = []
     if self.spec.flat_headings:
         res.append(" & " * x_tiers)
         res.append(
             " & ".join((escape_latex(str_of_comb(y_comb)) for y_comb in self.combs))
             + " \\\\\n"
         )
     else:
         headers = self.get_nested_headings()
         sep_slices = None
         for stratum_idx, stratum in enumerate(headers):
             res.append("& " * x_tiers)
             if sep_slices is not None:
                 sep_slices *= len(self.divs[stratum_idx])
             if stratum_idx == self.spec.div_idx:
                 sep_slices = 1
             res.append(stratum_row_latex(stratum, sep_slices))
     return "".join(res)
예제 #31
0
def mmt_ri_upsell_report(filename):
	# Get todays date
	today = datetime.today().date()
	last_month = date(today.year, today.month-1, 1)
	# Import Data
	df = rp.read_csv(filename)
	# Start Doc
	doc = lb.start_doc("MMT EC2 RI Up-Sell Report (%s)"%last_month.strftime("%b-%y"))
	# Get Data
	tables, images = rp.mmt_ri_upsell_opp(df)
	# Get report sections
	sections = []
	for table in tables:
		try:
			sections.append(table['territory'])
		except KeyError:
			pass
	sections = sorted(set(sections))
	# Overview
	with doc.create(Section("Overview")):
		doc.append("This document collates EC2 spend information across customer \
			accounts by territor in UKIR MMT and then makes some estimations as to RI \
			up-front cost opportunity. \\textbf{This estimation is not exact, do not \
			share directly with customers.} Current RI opportunity estimates are \
			calculated using an observed relationship between On Demand spend and\
			the results of 'Mark Estes Tool' and are typically conservative (underestimates). True RI up-front and ongoing costs \
			depend on instance type, OS and volume discounts and therefore still \
			need to be generated on an account-by-account basis. I am working on automating this.")
	# Add Sections
	for section in sections:
		doc.append("\\begin{landscape}")
		with doc.create(Section("%s"%escape_latex(section))):
			for table in tables:
				try:
					if table['territory'] == section:
						lb.include_table(doc, table['file'], table['name'])
				except KeyError: 
					pass
		doc.append("\\end{landscape}")
		lb.add_page(doc)
	lb.write_doc(doc, "MMT EC2 RI Up-Sell Report")
	cleanup()
예제 #32
0
def tabela_certificados(doc, id=None):
    with doc.create(Enumerate()) as enum:
        enum.add_item(
            NoEscape(
                r'Relacionar o nome dos participantes com direito a certificados. \\'
            ))
        table_spec = NoEscape(r'''|>{\centering\arraybackslash}X|
                                  @{  }c@{  }|
                                  @{  }c@{  }|
                                  @{  }c@{  }|
                              ''')
        cabecalho_tabela = ['NOME', 'FUNÇÃO', 'FREQUÊNCIA (%)', 'C/H TOTAL']

        with doc.create(Tabularx(table_spec,
                                 width_argument=WIDTH_ARGUMENT)) as tab:
            tab.add_hline()
            tab.add_row(cabecalho_tabela)
            tab.add_hline()

            certificados = CertificadoRelatorio.objects.filter(relatorio_id=id)
            for certificado in certificados:
                if certificado:
                    linha = [
                        escape_latex(certificado.nome), certificado.funcao,
                        certificado.frequencia, certificado.carga_horaria_total
                    ]
                    tab.add_row(linha)
                    tab.add_hline()

        doc.append(LineBreak())

        # TODO: Item 9.2: Inserir onde o certificado sera gerado: PROEX ou Centro de Coordenação / Órgão Promotor
        enum.add_item(
            NoEscape(r'Informar se os certificados devem ser emitidos: \\'))
        doc.append(
            NoEscape(
                '({}) pela PROEX \hfill ({}) pelo Centro da Coordenação ou Órgão Promotor'
                .format(PHANTOM, PHANTOM)))
예제 #33
0
def tabela_palavras_chave(doc, enum, palavras):
    item(doc, enum, NoEscape(r'PALAVRAS-CHAVE: \\'))

    nro_colunas = 3
    with doc.create(Tabularx('|X|X|X|', width_argument=WIDTH_ARGUMENT)) as tab:
        tab.add_hline()

        row = []
        for i, palavra in enumerate(palavras, 1):
            row.append(
                NoEscape('{} -- {}'.format(str(i),
                                           escape_latex(palavra.nome))))

            if i % nro_colunas == 0:
                tab.add_row(row)
                del row[:]

        # Adiciona o resto dos itens à tabela
        for _ in range(nro_colunas - len(row)):
            row.append('')
        tab.add_row(row)

        tab.add_hline()
예제 #34
0
    def add_table(self, table, *, width=NoEscape(r'0.8\textwidth'),
            placement=NoEscape(r'\centering')):
        """Add a table to the figure.
        Args
        ----
        table: Tabular
            a pylatex tabular object
        width: str
            The width of the image
        placement: str
            Placement of the figure, `None` is also accepted.
        """

        if width is not None:
            if self.escape:
                width = escape_latex(width)

            width = 'width=' + str(width)

        if placement is not None:
            self.append(placement)

        self.append(NoEscape(table.dumps()))
예제 #35
0
def create_latex_table(doc, data_set, caption):
	data_set.sort(key=lambda tup: tup['data'][datetime.today().month-2][1], reverse=True)

	#pprint(data_set)
	if data_set:
		col_num = len(data_set[0]['data'])
		col_string = ""
		for i in range(0, col_num + 1, 1):
			col_string += "|c"
		col_string += "|"

		doc.append(Command('begin', arguments=Arguments('table')))
		doc.append('[h]')
		doc.append(Command('caption', arguments=Arguments(caption)))
		doc.append(Command('centering'))
		with doc.create(Table(col_string)) as table:
			table.add_hline()
			first = 0
			for customer in data_set:
				data_string = ""
				first_time_dates = ""
				for point in customer['data']:
					if first == 0:
						first_time_dates += " & \\textbf{{%s}}"%(point[0])
					data_string += " & %s"%(point[1])
				if first == 0:
					first_line = "\\textbf{{Cust. Name}}" + first_time_dates + "\\\\"
				row_string = escape_latex(customer['name']) + data_string + "\\\\"
				if first == 0:
					doc.append(first_line)
					table.add_hline()
				doc.append(row_string)
				table.add_hline()
				first += 1
		doc.append(Command('end', arguments=Arguments('table')))
	else:
		pass
예제 #36
0
def tabela_membros(doc, projeto_extensao):
    table_spec = NoEscape(r'''|>{\centering\arraybackslash}X|
                              >{\centering\arraybackslash}X|
                              @{  }c@{  }|
                              @{  }c@{  }|
                              >{\centering\arraybackslash}X|
                              >{\centering\arraybackslash}X|
                              @{  }c@{  }|
                          ''')
    cabecalho_tabela = [
        'NOME COMPLETO', 'ENTIDADE', 'CPF', 'DATA NASC.', 'FUNÇÃO',
        'C/H SEMANAL', 'TELEFONE E E-MAIL'
    ]

    doc.append(NoEscape('{\scriptsize'))

    with doc.create(Tabularx(table_spec,
                             width_argument=WIDTH_ARGUMENT)) as tab:
        tab.add_hline()
        tab.add_row(cabecalho_tabela)
        tab.add_hline()

        membros = MembroComunidade_CursoExtensao.objects.filter(
            curso_extensao_id=projeto_extensao.id)
        for membro in membros:
            linha = [
                escape_latex(membro.nome),
                escape_latex(membro.entidade),
                escape_latex(membro.cpf),
                membro.data_nascimento.strftime('%d/%m/%Y'),
                escape_latex(membro.funcao),
                membro.carga_horaria_semanal,
                # TODO: hifenizar email
                NoEscape(r'\makecell{{ {}; \\ {} }}'.format(
                    escape_latex(membro.telefone), escape_latex(membro.email)))
            ]
            tab.add_row(linha)
            tab.add_hline()

    mdframed_plano_trabalho(doc, membros)

    doc.append(NoEscape('}'))  # volta com tamanho da fonte normal
예제 #37
0
 def iter_rows_heads(self):
     for row_idx, (disp, inner_docs) in enumerate(
         self.spec.do_sorted_grouped(self.docs)
     ):
         yield row_idx, InFilter(inner_docs), escape_latex(disp) + " & "
예제 #38
0
파일: args.py 프로젝트: jornpeters/PyLaTeX
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='|')

예제 #39
0
def texify(string):
    """Return a modified version of the argument string where characters that
    are special in LaTeX have been converted into LaTeX escape codes.

    """
    return str(escape_latex(string))
예제 #40
0
def territory_performance(df, ri=None, territory='MMT-UK3'):
	ri = pd.DataFrame()
	"""
	Function to build overview of given territory. Assumes
	only given data for given terrtiory ( therefore no filtering by Territory
	is done)
	Takes:
	df:		DataFrame with territory revenue information.
		expects columns: 	'AR Period', 'Total Billed Revenue'
							'Payer Account Id', 'Customer Company'
	ri:		[Optional] DataFrame with RI information.
		expects columns:
	"""
	# List and Dict objects to store outputs
	tables=[]
	table={}
	images=[]
	image={}
	# Get most recent month
	today = datetime.today().date()
	last_month = date(today.year, today.month-2, 1)
	# Group by Month
	by_ter = df.groupby(['AR Period'])
# Calculate Top Billing Customers
	lm = by_ter.get_group(last_month)
	data = lm.sort(columns=['Total Billed Revenue'], ascending=False)
	top_ten = data[['Customer Company', 'Total Billed Revenue', 'Payer Account Id']].head(20)
	top_ten['Total Billed Revenue'] = top_ten['Total Billed Revenue'].round(0)
	if ri.empty:
		top_ten['Payer Account Id'] = top_ten['Payer Account Id'].apply(sot_links)
		top_ten = top_ten[['Payer Account Id', 'Customer Company','Total Billed Revenue']]
		with pd.option_context("max_colwidth", 1000):
			top_ten.to_latex('%s_top-ten.tex'%territory, na_rep="Unknown", index=False, escape=False)
		table = {'name':"\\textbf{%s: Top Accounts by Billed Revenue (\\$) in %s}"%(escape_latex(territory), last_month.strftime("%b-%y")),\
			 'file':'%s_top-ten'%territory, 'territory':'%s'%territory, 'section':'Overview'}
		tables.append(table)
	
	elif not ri.empty:
		ri = ri_insight(ri, territory)
		top_ten.set_index(top_ten['Payer Account Id'], inplace=True)
		top_ten.drop('Payer Account Id', axis=1, inplace=True)
		top_ten_ri = pd.concat([top_ten, ri['Amazon Elastic Compute Cloud']['% Optimized']], axis=1, join_axes=[top_ten.index])
		top_ten_ri.rename(columns={'% Optimized': 'EC2 RI % Optimized'}, inplace=True)
		top_ten_ri['Total Billed Revenue'] = top_ten_ri['Total Billed Revenue'].round(0)
		top_ten_ri['EC2 RI % Optimized'] = top_ten_ri['EC2 RI % Optimized'].round(0)
		top_ten_ri.to_latex('%s_top-ten.tex'%territory, na_rep="Unknown")
		table = {'name':"\\textbf{%s: Top Accounts by Billed Revenue (\\$) in %s}"%(escape_latex(territory), last_month.strftime("%b-%y")),\
				 'file':'%s_top-ten'%territory, 'territory':'%s'%territory, 'section':'Overview'}
		tables.append(table)
	else:
		pass
# Calculate Number of Accounts in Territory per Month
	size = by_ter.size()
	size = size.reset_index()
	size.rename(columns={0:'# Accounts'}, inplace=True)
	size = pd.pivot_table(size, columns='AR Period')
	size.to_latex('%s-size.tex'%territory, index=False)
	table= {'name':"\\textbf{Number of Accounts}", 'file':"%s-size"%territory, 'section':'Overview',\
			'territory':territory}
	tables.append(table)
# Calculate Total Billed Revenue
	revenue = by_ter['Total Billed Revenue'].sum()
	revenue = np.round(revenue, 0)
	revenue = revenue.reset_index()
	revenue.rename(columns={0:'Total Billed Revenue'}, inplace=True)
	revenue = pd.pivot_table(revenue, columns='AR Period')
	revenue.to_latex('%s-rev.tex'%territory, index=False)
	table = {'name':"\\textbf{Total Billed Revenue (\\$)}", 'file':"%s-rev"%territory, 'section':'Overview',\
			 'territory':territory}
	tables.append(table)
# Calculate Percentage Difference
	perc = revenue.pct_change(axis=1)
	perc = perc.dropna(axis=1, how='all')
	perc = np.multiply(perc, 100)
	perc = np.round(perc, 2)
	perc.to_latex('%s-perc.tex'%territory, index=False)
	table = {'name':"\\textbf{\\% Change from Previous Month}", 'file':"%s-perc"%territory, 'section':'Overview',\
			 'territory':territory}
	tables.append(table)
# Calculate Number of Acounts per Tier
	by_ter = df.groupby(['Account Tier'])
	uns = by_ter.size()
	uns = uns.reset_index()
	uns.rename(columns={0:'Account Count'}, inplace=True)
	uns = pd.pivot_table(uns, columns='Account Tier')
	uns.to_latex('%s-tier-size.tex'%territory, na_rep="0")
	table= {'name':"\\textbf{\\# Accounts by Tier (as of %s)}"%(last_month.strftime("%b-%y")),\
			'file':"%s-tier-size"%territory, 'section':'Overview', 'territory':territory}
	tables.append(table)
# Calculate Total Revenue per Tier
	uns = by_ter['Total Billed Revenue'].sum()
	uns = np.round(uns, 0)
	uns = uns.reset_index()
	uns.rename(columns={0:'Total Billed Revenue'}, inplace=True)
	uns = pd.pivot_table(uns, columns='Account Tier')
	uns.to_latex('%s-tier-rev.tex'%territory, na_rep="0")
	table = {'name':"\\textbf{Total Billed Revenue (\\$) by Tier(as of %s)}"%(last_month.strftime("%b-%y")), 'file':"%s-tier-rev"%territory,\
			 'section':'Overview', 'territory':territory}
	tables.append(table)
# Plot Charts per Teritory
	# Plot Colours
	r,g,b = (105,105,105)
	dark_grey = (r / 255., g / 255., b / 255.)
	# Look for negative numbers - then plot pie or bar
	# ---> Pie chart cant deal with negatives
	contains_neg = False
	for cols in uns.columns.tolist():
		try:
			if not uns.loc[uns[cols] < 0].empty:
				contains_neg = True
		except KeyError:
			pass
	if not contains_neg:
		# Plot Pie Chart
		for index in uns.iterrows():
			#print index[0]
			plot = uns.loc[index[0]].plot(kind='pie', figsize=(6,6), legend=False, colormap='Blues', title=index[0])
			plot.set_ylabel("")
			fig = plot.get_figure()
			fig.savefig("%s-tier-plot.png"%territory)
			fig.clf()
			image = {'name':"\\textbf{Total Billed Revenue (\\$) by Tier (%s)}"%(last_month.strftime("%b-%y")),\
					 'file':"%s-tier-plot.png"%territory, "territory":"%s"%territory, "section":"Overview", 'type':'pie'}
			images.append(image)
	else:
		# Plot Bar Chart
		for index in uns.iterrows():
			ax = plt.subplot(1,1,1, axisbg='white')  
			#ax.spines["top"].set_visible(False)  
			#ax.spines["right"].set_visible(False)
			ax.spines["bottom"].set_visible(True)  
			ax.spines["left"].set_visible(True)
			for child in ax.get_children():
			    if isinstance(child, matplotlib.spines.Spine):
			        child.set_color(dark_grey)
			# Ensure that the axis ticks only show up on the bottom and left of the plot.  
			# Ticks on the right and top of the plot are generally unnecessary chartjunk.
			ax.get_xaxis().tick_bottom()
			ax.get_yaxis().tick_left()
			plot = uns.loc[index[0]].plot(kind='bar', figsize=(12,9), title=index[0])
			plot.set_ylabel("")
			plt.gcf().subplots_adjust(bottom=0.1)
			fig = plot.get_figure()
			fig.savefig("%s-tier-plot.png"%territory)
			fig.clf()
			image = {'name':"\\textbf{Total Billed Revenue (\\$) by Tier (%s)}"%(last_month.strftime("%b-%y")),\
					 'file':"%s-tier-plot.png"%territory, "territory":"%s"%territory, "section":"Overview", 'type':'bar'}
			images.append(image)	
	return tables, images
예제 #41
0
def escape_tex(x):
	return escape_latex(x)
예제 #42
0
def make_experience(data={}):
    """
    make_experience

    This function obtains all the information needed from the
    @data dictionary to construct the experience section.

    @data should have this dictionary structure:
    data = {
        ...,
        "Professional": [
            ...,
            {
                "role": "",             # string
                "company": "",          # string
                "start_year":  0,       # num - YYYY
                "end_year":  0,         # num - YYYY
                "description": ""       # string
            },
            ...
        ],
        ...,
    }

    Returns a string with the LaTex code of this section
    """
    if not data or data == {}:
        return ""
    s = ""
    if data.get("Professional") and len(data.get("Professional")) != 0:
        job_tags = [
            'role',
            'company',
            'start_year',
            'location',
            # 'description'
        ]
        s = s + """\\cvsection{Experience}"""
        for idx, job in enumerate(data.get("Professional")):
            if idx != 0:
                s = s + "\n\\divider"
            description = "\n\\cvevent"
            for tag in job_tags:
                if tag == 'start_year':
                    description = description + "{{{} -- {}}}".format(
                        job.get("start_year"), job.get("end_year"))
                    continue
                if tag in job and job.get(tag):
                    description = description + "{{{}}}".format(job.get(tag))
                else:
                    description = description + "{}"

            s = s + description
            if job.get("description") is not None:
                job['description'] = r'{}'.format(job['description'])
                job['description'] = job['description'].replace('\n\n', '\n')
                job['description'] = escape_latex(job['description'])
                s = s + """\n\\begin{{itemize}}\n \\item {} \n\\end{{itemize}}""".format(
                    job.get("description"))

    return s
예제 #43
0
파일: full.py 프로젝트: amitdash/PyLaTeX
from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, \
    Plot, Figure, Package
from pylatex.numpy import Matrix
from pylatex.utils import italic, escape_latex
import os

if __name__ == '__main__':
    image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg')

    doc = Document()
    doc.packages.append(Package('geometry', options=['tmargin=1cm',
                                                     'lmargin=10cm']))

    with doc.create(Section('The simple stuff')):
        doc.append('Some regular text and some ' + italic('italic text. '))
        doc.append(escape_latex('\nAlso some crazy characters: $&#{}'))
        with doc.create(Subsection('Math that is incorrect')):
            doc.append(Math(data=['2*3', '=', 9]))

        with doc.create(Subsection('Table of something')):
            with doc.create(Tabular('rc|cl')) as table:
                table.add_hline()
                table.add_row((1, 2, 3, 4))
                table.add_hline(1, 2)
                table.add_empty_row()
                table.add_row((4, 5, 6, 7))

    a = np.array([[100, 10, 20]]).T
    M = np.matrix([[2, 3, 4],
                   [0, 0, 1],
                   [0, 0, 2]])
예제 #44
0
def mmt_report(filename, ri_filename=None):
# Import Data
	df = rp.read_csv(filename)
	by_ter = df.groupby(['Territory'])
	if ri_filename != None:
		ri = rp.read_csv(ri_filename)
		ri_by_ter = ri.groupby(['Territory'])
# Get todays date
	today = datetime.today().date()
	threshold = date(today.year, today.month-2, 1)
# Test
	#territory = 'MMT-UK3'
# For each Territory
	for (territory, data) in by_ter:
		data = by_ter.get_group(territory)
		if ri_filename != None:
			ri_data = ri_by_ter.get_group(territory)
		else:
			ri_data = pd.DataFrame()
	# Start Doc
		doc = lb.start_doc("%s Territory Report"%escape_latex(territory))
		# Get Data
		tables, images = rp.territory_report(data, ri_data, territory)
	# Add Overview Section
		lb.add_page(doc)
		with doc.create(Section("Overview")):
			for table in tables:
				try:
					if table['section'] == 'Overview':
						lb.include_table(doc, table['file'], table['name'])
				except KeyError:
					pass
			for image in images:
				try:
					if image['section'] == 'Overview':
						try:
							if image['type'] == 'pie':
								lb.include_images(doc, [image], False, 0.6)
							else:
								lb.include_images(doc, [image], False, 1)
						except KeyError:
							lb.include_images(doc, [image], False, 1)					
				except KeyError:
					pass
	# Add Fast Movers Section
		lb.add_page(doc)
		with doc.create(Section("Fast Movers")):
			doc.append("Fastest movers are calculated by sorting the gradient of a linear regression\
						(line of best fit) of the data points available for each customer in descending order.\
						Customers showing the most growth have steeper 'lines of best fit' through thier monthly\
						spend datapoints.")
			for table in tables:
				try:
					if table['section'] == 'Fast Movers':
						lb.include_table(doc, table['file'], table['name'])
				except KeyError:
					pass
	# Add Churn Section
		lb.add_page(doc)
		with doc.create(Section("Churn")):
			doc.append("Churn is calculated by sorting the gradient of a linear regression\
						(line of best fit) of the data points available for each customer in ascending order.\
						Customers showing the fastest decline have steeper (negative gradient) 'lines of best fit'\
						through thier monthly spend datapoints.")
			for table in tables:
				try:
					if table['section'] == 'Churn':
						lb.include_table(doc, table['file'], table['name'])
				except KeyError:
					pass
	# Add Cheerio Section
		lb.add_page(doc)
		with doc.create(Section("Cheerio")):
			with doc.create(Subsection("Product Upsell")):
				doc.append("Customers who are above the 90th percentile for Total Billed Revenue\
							but are below the 90th percentile for Cheerio Score (number of services used) in their tier.\
							These are some of your \\textbf{highest billing customers!}\
							\\\\\\textbf{Call to pitch managed service offerings}.\
							Good candidates for an \\textbf{Architecture Review}. Position \\textbf{Premium Support}")
				for table in tables:
					try:
						if table['section'] == 'Cheerio':
							if table['subsection'] == 'Product Upsell':
								lb.include_table(doc, table['file'], table['name'])
					except KeyError:
						pass
				lb.add_page(doc)
			with doc.create(Subsection("Utilization Upsell")):
				doc.append("Customers who are above the 90th percentile for Cheerio Score\
							but are below the 90th percentile for Total Billed Revenue (number of services used) in their tier.\
							These are some of your \\textbf{most skilled customers.}\
							\\\\\\textbf{Call to prospect for new projects}. Drive utilization.")
				for table in tables:
					try:
						if table['section'] == 'Cheerio':
							if table['subsection'] == 'Utilization Upsell':
								lb.include_table(doc, table['file'], table['name'])
					except KeyError:
						pass
				lb.add_page(doc)
			with doc.create(Subsection("Cheerio Data Plots")):
				for image in images:
					try:
						if image['section'] == 'Cheerio':
							lb.include_images(doc, [image], False, 1)
					except KeyError:
						pass
				lb.add_page(doc)
	# Add Threshold Section
		lb.add_page(doc)
		with doc.create(Section("Crossing Tier Thresholds")):
			for table in tables:
				try:
					if table['section'] == 'Crossing Thresholds':
						lb.include_table(doc, table['file'], table['name'])
				except KeyError:
					pass
	# Write File
		lb.write_doc(doc, "%s Territory Report"%territory)
		lb.cleanup()
예제 #45
0
def add_table(doc, df, caption, include_index=True):
	# DataFrame.shape returns tuple with (row,col) only. 
	# No index's included.
	print df.shape
	# Generate column string
	if include_index:
		col_num = (df.shape[0] + 1)
	else:
		col_num = (df.shape[0])
	col_string = ""
	for i in range(0, col_num + 1, 1):
		col_string += "|c"
	col_string += "|"

	# Begin Table
	doc.append(Command('begin', arguments=Arguments('table')))
	doc.append('[h]')
	doc.append(Command('caption', arguments=Arguments(caption)))
	doc.append(Command('centering'))

	with doc.create(Table(col_string)) as table:
		# Add titles
		table.add_hline()
		col_names = list(df.columns.values)
		# Add index name as first column if necessary
		if include_index:
			first_line = "\\textbf{{%s}}"%(str(df.index.name))
		else:
			first_line = ""
		# Add other column names
		first_loop = 0
		for title in col_names:
			if (first_loop == 0) and not first_line:
				pass
			else:
				first_line += " & "
			if type(title) is numpy.datetime64:
				ts = pd.to_datetime(str(title))
				first_line += "\\textbf{{%s}}"%(ts.strftime("%b-%y"))
			else:
				first_line += "\\textbf{{%s}}"%(str(title))
			first_loop = 1
		first_line += "\\\\"
		doc.append(first_line)
		table.add_hline()
		# Add Values
		for index, row in df.iterrows():
			data_string = ""
			first_loop = 0
			for point in row:
				print type(point)
				# Only add & after first loop
				if first_loop == 0:
					pass
				else:
					data_string += " & "
				# Catch numerical values
				if (type(point) == numpy.float64) or (type(point) == float) :					
					data_string += "%s"%(format(point, '.2f'))
				# Catch dates
				elif point.__class__ == pd.tslib.Timestamp:
					ts = pd.to_datetime(str(point))
					data_string += "%s"%(ts.strftime("%b-%y"))
				else:
					data_string += "%s"%(point)
				first_loop = 1
			# Check for index type is string
			if include_index:				
				if not type(df.index.values) == str:
					row_string = str(index) + " & " + data_string + "\\\\"
				else:
					row_string = escape_latex(index) + " & " + data_string + "\\\\"
			else:
				row_string = data_string + "\\\\"
			doc.append(row_string)
			table.add_hline()
	doc.append(Command('end', arguments=Arguments('table')))
예제 #46
0
 def append_closing(self, doc):
     doc.append(NoEscape('\\closing{%s}' % (
         escape_latex(_('Kind Regards,'))
     )))
예제 #47
0
    def make_doc(self, message):
        doc = Document(
            documentclass='scrlttr2',
            document_options=[
                'fontsize=11pt',
                'parskip=full',
                'paper=A4',
                'fromalign=right',
                'fromemail=true',
                'fromurl=true',
                'version=last'
            ],
            inputenc='utf8',
            fontenc=None,
            page_numbers=False,
            geometry_options=None,
            lmodern=None,
            textcomp=True,
        )
        doc.packages.append(Package('fontspec,xunicode'))
        doc.packages.append(Package('inputenc', 'utf8'))
        doc.packages.append(Package('eurosym'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('babel', 'ngerman'))
        # doc.packages.append(Package('pdfpages'))
        doc.packages.append(Package('hyperref', 'hidelinks'))

        doc.append(NoEscape("\\lefthyphenmin=5"))
        doc.append(NoEscape('''
            \\newif\\ifquoteopen
                \\catcode`\\"=\\active
                \\DeclareRobustCommand*{"}{%
                \\ifquoteopen
                    \\quoteopenfalse \\grqq%
                \\else
                    \\quoteopentrue \\glqq%
                \\fi
        }'''))

        doc.append(NoEscape(
            '\\setkomavar{fromname}{%s}' % message.real_sender))

        user_address = message.sender_user.address
        if user_address:
            address = '\\\\'.join(
                escape_latex(x) for x in user_address.splitlines()
                if x.strip())
            doc.append(NoEscape(
                '\\setkomavar{fromaddress}{%s}' % address
            ))

        email = message.sender_email

        doc.append(NoEscape(
            '\\setkomavar{fromemail}{\\href{mailto:%(email)s}{%(email)s}}' % {
                'email': email
            }
        ))

        url = message.request.get_absolute_domain_short_url()
        doc.append(NoEscape(
            '\\setkomavar{fromurl}[]{\\href{%(url)s}{%(url)s}}' % {
                'url': url
            }
        ))

        doc.append(NoEscape('\\setkomavar{myref}[\\myrefname]{%s}' % (
            escape_latex('#' + str(message.request.pk))
        )))

        doc.append(NoEscape('\\setkomavar{customer}[%s]{%s}' % (
            escape_latex(_('Delivery')),
            escape_latex(_('Via fax and email')),
        )))

        doc.append(NoEscape('\\setkomavar{date}{\\today}'))
        doc.append(NoEscape(
            '\\setkomavar{subject}{%s}' % escape_latex(message.subject)
        ))

        pb = message.recipient_public_body
        if pb is not None:
            address = pb.address.splitlines()
            recipient_line = [pb.name] + address
            recipient_line = '\\\\'.join(
                escape_latex(x) for x in recipient_line
            )
            doc.append(NoEscape('''\\begin{letter}{%s}''' % recipient_line))

        doc.append(NoEscape('\\opening{%s}' % (
            escape_latex(_('Dear Ladies and Gentlemen,'))
        )))

        text = self.get_letter_text()
        append_text(doc, text)

        self.append_closing(doc)

        doc.append(NoEscape('\\end{letter}'))

        return doc
예제 #48
0
#!/usr/bin/env python

from pylatex import Document, Section
from pylatex.utils import escape_latex

doc = Document(default_filename="utils_escape_latex")
section = Section('Escape LaTeX characters test')

text = escape_latex('''\
& (ampersand)
% (percent)
$ (dollar)
# (number)
_ (underscore)
{ (left curly brace)
} (right curly brace)
~ (tilde)
^ (caret)
\\ (backslash)
--- (three minuses)
a\xA0a (non breaking space)
''')

section.append(text)
doc.append(section)

doc.generate_pdf()
예제 #49
0
 def disp_kv(self, v: str):
     mapped = self.lookup.get(v)
     if mapped:
         return mapped
     else:
         return escape_latex(self.group.get_cat() + "=" + str(v))
예제 #50
0
파일: todos.py 프로젝트: ttm/sonhos
# skate amigo junto conseguia tomada dentro começou
# ensina assim havima lados ovos acordei cara império consegui"""
f=open("../mineracaoDosSonhos/poema_incidencia_curto.txt","w")
f.write(pic)
f.close()
E+="poema_incidencia_curto.txt -> palavras mais significativas por ordem de incidência, versão ditada e menor\n\n"
T+="\n\n"+pic
with doc.create(Section('Incidência')):
    with doc.create(Subsection("Versão completa")):
        with doc.create(Subsubsection('literatura')):
            doc.append(poema_incidencia)
        with doc.create(Subsubsection('explicação')):
            doc.append("palavras mais significativas por ordem de incidência")
    with doc.create(Subsection('Incidência abreviada')):
        with doc.create(Subsubsection('literatura')):
            doc.append(escape_latex(pic))
        with doc.create(Subsubsection('explicação')):
            doc.append("palavras mais significativas por ordem de incidência, versão ditada e mais curta")


#wt__.plot()
W=wt__.tokens
W.sort()
f=open("../mineracaoDosSonhos/palavras_ordenadas_repetidas.txt","w")
f.write(" ".join(W))
f.close()
E+="palavras_ordenadas_repetidas.txt -> palavras mais significativas por ordem alfabética e com repeticoes\n\n"
T+="\n\n"+" ".join(W)

W_=list(set(W))
W_.sort()