Exemplo n.º 1
0
    def test_fixup_arch(self):
        replacement = h.H1("I am the greatest title alive!")

        result = self.registry('ir.ui.view').replace_arch_section(
            self.cr, self.uid, self.view_id, '/div/div[1]/h3', replacement)

        self.eq(
            result,
            h.DIV(
                h.DIV(h.H3("I am the greatest title alive!"),
                      h.UL(h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))),
                h.DIV(
                    h.H3("Column 2"),
                    h.UL(
                        h.LI("Item 1"),
                        h.LI(
                            h.SPAN(
                                "My Company",
                                attrs(model='res.company',
                                      id=1,
                                      field='name',
                                      type='char'))),
                        h.LI(
                            h.SPAN(
                                "+00 00 000 00 0 000",
                                attrs(model='res.company',
                                      id=1,
                                      field='phone',
                                      type='char')))))))
Exemplo n.º 2
0
    def test_field_tail(self):
        replacement = ET.tostring(h.LI(
            h.SPAN(
                "+12 3456789",
                attrs(model='res.company',
                      id=1,
                      type='char',
                      field='phone',
                      expression="edmund")), "whop whop"),
                                  encoding="utf-8")
        self.view_id.save(value=replacement, xpath='/div/div[2]/ul/li[3]')

        self.eq(
            ET.fromstring(self.view_id.arch.encode('utf-8')),
            h.DIV(
                h.DIV(h.H3("Column 1"),
                      h.UL(h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))),
                h.DIV(
                    h.H3("Column 2"),
                    h.UL(
                        h.LI("Item 1"),
                        h.LI(
                            h.SPAN(
                                "My Company",
                                attrs(model='res.company',
                                      id=1,
                                      field='name',
                                      type='char'))),
                        h.LI(h.SPAN({'t-field': "edmund"}), "whop whop"),
                    ))))
Exemplo n.º 3
0
 def setUp(self):
     super(TestViewSaving, self).setUp()
     self.arch = h.DIV(
         h.DIV(h.H3("Column 1"),
               h.UL(h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))),
         h.DIV(
             h.H3("Column 2"),
             h.UL(
                 h.LI("Item 1"),
                 h.LI(
                     h.SPAN(
                         "My Company",
                         attrs(model='res.company',
                               id=1,
                               field='name',
                               type='char'))),
                 h.LI(
                     h.SPAN(
                         "+00 00 000 00 0 000",
                         attrs(model='res.company',
                               id=1,
                               field='phone',
                               type='char'))))))
     self.view_id = self.registry('ir.ui.view').create(
         self.cr, self.uid, {
             'name': "Test View",
             'type': 'qweb',
             'arch': ET.tostring(self.arch,
                                 encoding='utf-8').decode('utf-8')
         })
Exemplo n.º 4
0
    def test_save(self):
        Company = self.env['res.company']
        View = self.env['ir.ui.view']

        # create a view with an xmlid, like the file import would
        with self.env.norecompute():
            self.view_id = View.create({
                'name': "Test View",
                'type': 'qweb',
                'arch': ET.tostring(self.arch, encoding='utf-8').decode('utf-8')
            })
        imd = self.env['ir.model.data'].create({
            'module': 'website',
            'name': 'test_view',
            'model': 'ir.ui.view',
            'res_id': self.view_id,
        })

        # the xml_id of the view should not be flagged as 'noupdate'
        self.assertEqual(self.view_id.model_data_id, imd)
        self.assertFalse(imd.noupdate)

        replacement = ET.tostring(h.DIV(
            h.H3("Column 2"),
            h.UL(
                h.LI("wob wob wob"),
                h.LI(h.SPAN("Acme Corporation", attrs(model='res.company', id=1, field='name', expression="bob", type='char'))),
                h.LI(h.SPAN("+12 3456789", attrs(model='res.company', id=1, field='phone', expression="edmund", type='char'))),
            )
        ), encoding='utf-8')
        self.view_id.save(value=replacement, xpath='/div/div[2]')

        # the xml_id of the view should be flagged as 'noupdate'
        self.assertTrue(imd.noupdate)

        company = Company.browse(1)
        self.assertEqual(company.name, "Acme Corporation")
        self.assertEqual(company.phone, "+12 3456789")
        self.eq(
            ET.fromstring(self.view_id.arch.encode('utf-8')),
            h.DIV(
                h.DIV(
                    h.H3("Column 1"),
                    h.UL(
                        h.LI("Item 1"),
                        h.LI("Item 2"),
                        h.LI("Item 3"))),
                h.DIV(
                    h.H3("Column 2"),
                    h.UL(
                        h.LI("wob wob wob"),
                        h.LI(h.SPAN({'t-field': "bob"})),
                        h.LI(h.SPAN({'t-field': "edmund"}))
                    ))
            )
        )
Exemplo n.º 5
0
    def visit_Component(self, node):
        inst = getattr(self, 'inst', None)
        if inst:
            title = 'Instance {} of {} Register Map'.format(inst, node.name)
        else:
            title = 'Base {} Register Map'.format(node.name)
        self.title = title

        # Create the main content by sweeping the tree.
        bc = E.DIV(id='breadcrumbs')
        try:
            if self.breadcrumbs is not None:
                bc.append(self.breadcrumbs)
        except AttributeError:
            pass

        ww = node.width // 8
        an = ((node.size - 1).bit_length() + 3) // 4
        with self.tempvars(wordwidth=ww, address_nibbles=an, hlev=2):
            nodes = ([E.H1(title, id='title'), bc] +
                     [E.P(d) for d in node.description] +
                     [c
                      for c in self.visitchildren(node)] + [self.footer(node)])
            contentnode = E.DIV(*nodes, id='content')

        # Add a table of contents sidebar.  We'll assume that everything that
        # wants to be in the TOC is already a heading and just work from there.
        h2list = E.UL()
        for elem in contentnode.iter('h2', 'h3'):
            id = escape(elem.text)
            elem.attrib['id'] = id
            if elem.tag == 'h2':
                h2node = E.LI(E.A(elem.text, href='#' + id))
                h2list.append(h2node)
                h3list = None
            else:
                if h3list is None:
                    h3list = E.UL()
                    h2list.append(h3list)
                h3list.append(E.LI(E.A(elem.text, href='#' + id)))

        # Put it all together.
        return E.HTML(
            E.HEAD(
                E.TITLE(title),
                E.LINK(rel='stylesheet',
                       type='text/css',
                       href=htmlpathjoin(self.styledir, 'reg.css'))),
            E.BODY(
                E.DIV(E.DIV(E.P(E.A(title, href='#title')),
                            h2list,
                            id='sidebar'),
                      contentnode,
                      id='wrapper')),
        )
Exemplo n.º 6
0
    def test_save(self):
        Company = self.env['res.company']

        # create an xmlid for the view
        imd = self.env['ir.model.data'].create({
            'module': 'website',
            'name': 'test_view',
            'model': self.view_id._name,
            'res_id': self.view_id.id,
        })
        self.assertEqual(self.view_id.model_data_id, imd)
        self.assertFalse(imd.noupdate)

        replacement = ET.tostring(h.DIV(
            h.H3("Column 2"),
            h.UL(
                h.LI("wob wob wob"),
                h.LI(
                    h.SPAN(
                        "Acme Corporation",
                        attrs(model='res.company',
                              id=1,
                              field='name',
                              expression="bob",
                              type='char'))),
                h.LI(
                    h.SPAN(
                        "+12 3456789",
                        attrs(model='res.company',
                              id=1,
                              field='phone',
                              expression="edmund",
                              type='char'))),
            )),
                                  encoding='unicode')
        self.view_id.save(value=replacement, xpath='/div/div[2]')

        # the xml_id of the view should be flagged as 'noupdate'
        self.assertTrue(imd.noupdate)

        company = Company.browse(1)
        self.assertEqual(company.name, "Acme Corporation")
        self.assertEqual(company.phone, "+12 3456789")
        self.eq(
            ET.fromstring(self.view_id.arch),
            h.DIV(
                h.DIV(h.H3("Column 1"),
                      h.UL(h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))),
                h.DIV(
                    h.H3("Column 2"),
                    h.UL(h.LI("wob wob wob"), h.LI(h.SPAN({'t-field': "bob"})),
                         h.LI(h.SPAN({'t-field': "edmund"}))))))
Exemplo n.º 7
0
    def ToString(self):
        result = E.DIV()
        result.attrib['class'] = 'center'

        ul = E.UL()
        result.append(ul)
        ul.attrib['class'] = 'mktree'
        ul.attrib['id'] = 'diffRoot'

        #  Insert xml declarations

        n = E.LI()
        n.attrib['whereLeft'] = "L0_0"
        n.attrib['whereRight'] = "R0_0"
        leftText = '<?xml version="{0}" encoding="{1}"?>'.format(
            self.xml.docinfo.xml_version, self.xml.docinfo.encoding)
        rightText = '<?xml version="{0}" encoding="{1}"?>'. \
            format(self.matchNode.xml.docinfo.xml_version,
                   self.matchNode.xml.docinfo.encoding)
        self.diffTextToHtml(leftText, rightText, n)
        ul.append(n)

        # Insert DTD declaration if one exists
        n = E.LI()
        if self.xml.docinfo.doctype or self.matchNode.xml.docinfo.doctype:
            self.diffTextToHtml(self.xml.docinfo.doctype,
                                self.matchNode.xml.docinfo.doctype, n)
            ul.append(n)

        # now put all of the children into HTML

        for child in self.children:
            child.ToHtml(ul)

        return self._serialize(result)
Exemplo n.º 8
0
    def get_rendered_for_toc(self, path_override=None):
        """Returns an html 'ul' element, that represents the entire table of contents for this category.
        Parameters
        ---------
        path_override : str
          If not None, gets urls for this path. Intended for use by parent categories getting the toc of their children.
        """
        root_elm = E.UL(E.CLASS("toc_category"))
        # Children categories.
        nav = self.navigation
        for child in self.children:
            if path_override != None:
                child_path = get_url(path_override, child.file_path)
            else:
                child_path = get_url(self.file_path, child.file_path)

            child_elm = E.LI(
                E.A(child.name, href=child_path),
                child.get_rendered_for_toc(path_override=self.path)
            )
            root_elm.append(child_elm)
        # Assets.
        for asset in self.assets:
            asset_path = get_new_ext(asset.path, 'html')
            if path_override != None:
                asset_path = get_url(path_override, asset_path)
            else:
                asset_path = get_url(self.file_path, asset_path)
            asset_elm = E.LI(
                E.A(asset.title, href=asset_path)
            )
            root_elm.append(asset_elm)
        return root_elm
Exemplo n.º 9
0
def template(name, contents):

    cpu_class = 'active' if name == 'cpu' else ''
    wc_class = 'active' if name == 'wc' else ''
    help_class = 'active' if name == 'help' else ''

    return E.HTML(
        E.HEAD(
            E.LINK(rel='stylesheet',
                   type='text/css',
                   href='bootstrap/css/bootstrap.css'),
            E.LINK(rel='stylesheet', type='text/css', href='profile.css'),
            E.SCRIPT(src='bootstrap/js/bootstrap.min.js'),
            E.TITLE('RUM Job Profile')),
        E.BODY(
            E.DIV(E.DIV(E.DIV(E.A(E.SPAN(CLASS='icon-bar'),
                                  E.SPAN(CLASS='icon-bar'),
                                  E.SPAN(CLASS='icon-bar'),
                                  CLASS='btn btn-navbar'),
                              E.A('RUM Profile', CLASS='brand', href='#'),
                              E.DIV(E.UL(E.LI(E.A('CPU time', href='cpu.html'),
                                              CLASS=cpu_class),
                                         E.LI(E.A('Wallclock time',
                                                  href='wc.html'),
                                              CLASS=wc_class),
                                         E.LI(E.A('Help', href='help.html'),
                                              CLASS=help_class),
                                         CLASS='nav'),
                                    CLASS='nav-collapse collapse'),
                              CLASS='container'),
                        CLASS='navbar-inner'),
                  CLASS='navbar navbar-inverse navbar-fixed-top'), E.BR(),
            E.BR(), E.BR(), E.DIV(contents, CLASS='container')))
Exemplo n.º 10
0
def change_representation_compressed(change: Dict[str, Any], link: str,
                                     filepath: str, current_depth: int,
                                     max_depth: int) -> Optional[Any]:
    """
    Generator of compressed html markdown.
    """
    change_elements: List[Any] = [
        E.B(change["type"]),
        E.SPAN(" "),
        E.A(change["name"], href=link),
        E.B(" changed lines: "),
        E.SPAN(str(change["changed_lines"])),
    ]

    if change["total_lines"]:
        change_elements.extend(
            [E.SPAN("/"), E.SPAN(str(change["total_lines"]))])

    if change["children"]:
        change_elements.extend([E.BR()])
    child_elements = []
    for child in change["children"]:
        child_element = render_change_as_html(child, filepath,
                                              current_depth + 1, max_depth,
                                              True)
        if child_element is not None:
            child_elements.append(child_element)
    change_elements.append(E.UL(*child_elements))

    return change_elements
Exemplo n.º 11
0
def diff(base, new):
    u"""
    Return an Element that renders the version differences between the amis `base` and `new`.

    Arguments:
        base, new (dicts): Descriptions of a deployed AMI. Any keys that start with
            'version:' should have values that are a repo and a sha, separated by a space.
            They must also have the keys 'environment', 'deployment', 'play', and 'ami_id'.
    """
    diff_items = []
    for delta in sorted(set(version_deltas(base, new))):
        version = delta.new or delta.base
        repo = GITHUB_PREFIX.sub(u'', version.repo)
        diff_items.append(
            E.LI(
                E.A(
                    u"{}: {}...{}".format(repo, delta.base.sha, delta.new.sha),
                    href=u"{}/compare/{}...{}".format(version.repo, delta.base.
                                                      sha, delta.new.sha),
                ) if delta.base.sha != delta.new.sha else E.A(
                    u"{}: {} (no change)".format(repo, delta.base.sha),
                    href=u"{}/commit/{}".format(repo, delta.base.sha),
                )))
    return SECTION(
        E.
        H3(u"Comparing {base.environment}-{base.deployment}-{base.play}: {base.ami_id} to {new.ami_id}"
           .format(
               base=base,
               new=new,
           )), E.UL(*diff_items, style=u"list-style-type: square"))
Exemplo n.º 12
0
def compare_tables(body, old, new):
    body.append(builder.H2("Table Comparisons"))
    for name in sorted(old.tables):
        body.append(builder.H3(name))
        if name in new.tables:
            compare_table(body, name, old, new)
        else:
            body.append(builder.UL(builder.LI(builder.B("TABLE LOST"))))
Exemplo n.º 13
0
    def test_save(self):
        Company = self.registry('res.company')
        View = self.registry('ir.ui.view')

        replacement = ET.tostring(h.DIV(
            h.H3("Column 2"),
            h.UL(
                h.LI("wob wob wob"),
                h.LI(
                    h.SPAN(
                        "Acme Corporation",
                        attrs(model='res.company',
                              id=1,
                              field='name',
                              expression="bob",
                              type='char'))),
                h.LI(
                    h.SPAN(
                        "+12 3456789",
                        attrs(model='res.company',
                              id=1,
                              field='phone',
                              expression="edmund",
                              type='char'))),
            )),
                                  encoding='utf-8')
        View.save(self.cr,
                  self.uid,
                  res_id=self.view_id,
                  value=replacement,
                  xpath='/div/div[2]')

        company = Company.browse(self.cr, self.uid, 1)
        self.assertEqual(company.name, "Acme Corporation")
        self.assertEqual(company.phone, "+12 3456789")
        self.eq(
            ET.fromstring(
                View.browse(self.cr, self.uid,
                            self.view_id).arch.encode('utf-8')),
            h.DIV(
                h.DIV(h.H3("Column 1"),
                      h.UL(h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))),
                h.DIV(
                    h.H3("Column 2"),
                    h.UL(h.LI("wob wob wob"), h.LI(h.SPAN({'t-field': "bob"})),
                         h.LI(h.SPAN({'t-field': "edmund"}))))))
Exemplo n.º 14
0
def transform_demo(div):
    div.append(E.BUTTON('Run demo'))

    demo_dir = op.join(FILEBASE, div.get('demo'))
    div.set('demo', demo_dir)

    files = (f for f in os.listdir(demo_dir) if not f.startswith('.'))
    ul = E.UL(*(E.LI(E.A(f, href=op.join(demo_dir, f))) for f in files))
    div.append(ul)
Exemplo n.º 15
0
def build_locale_content():
    main = template_keys['mirror.locale.main']
    content = E.DIV(E.P("Browse in ", _locale_link(main), ", or:"))
    ul = E.UL()
    for locale in locales:
        ul.append(E.LI(_locale_link(locale)))
    content.append(ul)
    template_keys['mirror.locale.content'] = html.tostring(content).decode(
        'utf-8')
Exemplo n.º 16
0
def html_file_section_handler_vanilla(item: Dict[str, Any]) -> Any:
    filepath = item["file"]
    file_url = item.get("file_url", filepath)
    change_elements = [
        render_change_as_html(change, filepath, 0, 2)
        for change in item["changes"]
    ]
    file_elements = [
        E.H4(E.A(filepath, href=file_url)),
        E.B("Changes:"),
        E.UL(*change_elements),
    ]
    return E.DIV(*file_elements)
Exemplo n.º 17
0
 def _format_amis(self):
     u"""
     Return an Element that contains formatted description of the deployed AMIs.
     """
     return SECTION(
         E.H2(u"Final AMIs"),
         E.UL(*[
             E.
             LI(u"{ami.environment}-{ami.deployment}-{ami.play}: {ami.ami_id}"
                .format(ami=ami)) for _, ami in self.ami_pairs
             if ami is not None
         ],
              style=u"list-style-type: square"),
     )
Exemplo n.º 18
0
    def visit_Register(self, node):
        """Generate a Register DIV with heading, bitfield table, field listing,
        etc."""

        ap = self.addressparagraph(node)
        ap.text += ' ' + register_format(node)

        root = E.DIV(ap,
                     self.heading(node.name),
                     CLASS('register'),
                     *[E.P(d, CLASS('description')) for d in node.description],
                     id="REG_" + node.name)

        if node.space:
            # We need bitfield tables.
            table = E.TABLE(CLASS('bitfield'))
            rows = []
            for startbit in range(0, node.space.size, 16):
                endbit = startbit + 16
                row = E.TR(CLASS('fields'))
                cells = []
                for obj, start, size in node.space[startbit:endbit]:
                    if obj:
                        cell = E.TD(obj.name, CLASS('std_field'))
                    else:
                        cell = E.TD('.', CLASS('reserved_field'))
                    cell.attrib['colspan'] = str(size)
                    cells.append(cell)
                row.extend(reversed(cells))
                rows.append(row)

                rows.append(
                    E.TR(
                        CLASS('bit_numbers'), *[
                            E.TD(str(n - 1))
                            for n in range(endbit, startbit, -1)
                        ]))
            table.extend(reversed(rows))
            root.append(table)

            fieldlist = E.UL(CLASS('fieldlist'),
                             *self.visitchildren(node, reverse=True))
            root.append(fieldlist)

        elif node.width != node.parent.width:
            # We have a truncated field, i.e. not all the bits that the
            # component allows.
            root.append(E.P('Bits {}:0 only.'.format(node.width - 1)))

        return root
Exemplo n.º 19
0
def compare_docs(body, old, new, verbose):
    body.append(builder.H2("Document Comparisons"))
    for name in sorted(old.docs):
        body.append(builder.H3(f"{name} Docs"))
        new_docs = new.docs[name]
        if not new_docs.docs:
            body.append(builder.UL(builder.LI(builder.B(LOST))))
        else:
            old_docs = old.docs[name]
            items = []
            for key in old_docs.docs:
                old_id, old_title, old_xml = old_docs.docs[key]
                if key not in new_docs.docs:
                    items.append(builder.I(builder.LI(old_title)))
                else:
                    diffs = diff_xml(old_xml, new_docs.docs[key][2], verbose)
                    if diffs is not None:
                        title = builder.B(old_title)
                        items.append(builder.LI(title, diffs))
            if not items:
                body.append(builder.P(CHECK, OK))
            else:
                body.append(builder.UL(*items))
Exemplo n.º 20
0
def main_page_gen(default_style):
    html = E.HTML(
        E.HEAD(
            E.META(**{'http-equiv':"Default-Style", 'content':default_style, 'id':'stylemetatag'}),
            E.TITLE("U2ch - Main Page"),
            E.SCRIPT(type = 'text/javascript', src = '/mainscript.js'), #js
	    *initiate.style_cache
            ),
        E.BODY(
            E.UL(initiate.stats_cache,
                 style = "display: none;",
                 id = "mblstatscache"),
	    E.TABLE(
                E.CLASS("maintable"),
                E.THEAD(E.TR(E.TD(E.DIV(E.CLASS("mainslogandiv"),
                                        E.SPAN("U2CH"),
                                        E.SPAN("",
                                               style="display: inline-block; width: 5em;"),
                                        E.SPAN("Viewing above imageboards"),
                                        ),
                                  E.DIV(E.CLASS("mainimagediv"),
                                        E.IMG(src="u-2.jpg", style="width:496px;height:334px;"),
                                        ),
                                  )), id = 'header'),
                E.TBODY(E.TR(E.TD(
                    E.HR(E.CLASS("delimeter")),
                    E.DIV(E.CLASS("mblcontainer"),
                          E.DIV(E.CLASS("mblcentering"),
                                initiate.board_cache_main_page,
                                ),
                          ),
                    E.HR(E.CLASS("delimeter")),
                    )), id = 'mainpart'),
                E.TFOOT(E.TR(E.TD(
                    E.DIV('powered by ',
                        E.A('Farlight Imageboard Engine',
                            href='https://github.com/Alpherie/farlight_board_engine',
                            target='_blank',
                            ),
                        id='credentials'),
                    )), id = 'footer'),
                ),
            onload = 'mainpagefunc()'
            )
        )
    return lxml.html.tostring(html)
Exemplo n.º 21
0
def html_file_section_handler_github(item: Dict[str, Any]) -> Any:
    filepath = item["file"]
    file_url = item.get("file_url", filepath)
    change_elements = [
        render_change_as_html(change, filepath, 0, 2)
        for change in item["changes"]
    ]
    file_summary_element = E.A(filepath, href=file_url)
    file_elements = [
        E.B("Changes:"),
        E.UL(*change_elements),
    ]
    file_elements_div = E.DIV(*file_elements)
    file_details_element = E.DIV(
        lxml.html.fromstring(
            f"<details><summary>{lxml.html.tostring(file_summary_element).decode()}</summary>"
            f"{lxml.html.tostring(file_elements_div).decode()}</details>"))
    return file_details_element
Exemplo n.º 22
0
    def visit_MemoryMap(self, node):
        """Create an HTML file for a MemoryMap."""
        self.title = title = node.name + ' Peripheral Map'
        an = ((node.size - 1).bit_length() + 3) // 4

        # Sweep the document tree to build up the main content
        with self.tempvars(wordwidth=1,
                           address_nibbles=an,
                           base=node.base,
                           subdir=node.name + '_instances',
                           hlev=2):
            children = list(self.visitchildren(node))
            table = E.TABLE(
                E.TR(E.TH('Peripheral'), E.TH('Base Address'), E.TH('Size'),
                     E.TH('Description'), *children), CLASS('component_list'))
            nodes = ([E.H1(title, id='title')] +
                     [E.P(d) for d in node.description] +
                     [E.HR(), table, self.footer(node)])
            contentnode = E.DIV(*nodes, id='content')

        # Add a table of contents sidebar for each table row.
        instlist = E.UL()
        for elem in contentnode.xpath("//td[contains(@class, 'peripheral')]"):
            text = tostring(elem, method="text", encoding="unicode")
            id = escape(text)
            elem.attrib['id'] = id
            node = E.LI(E.A(text, href='#' + id))
            instlist.append(node)

        # And put it all together.
        return E.HTML(
            E.HEAD(
                E.TITLE(title),
                E.LINK(rel='stylesheet',
                       type='text/css',
                       href=htmlpathjoin(self.styledir, 'reg.css'))),
            E.BODY(
                E.DIV(E.DIV(E.P(E.A(title, href='#title')),
                            instlist,
                            id='sidebar'),
                      contentnode,
                      id='wrapper')),
        )
Exemplo n.º 23
0
    def __bullets_points(self, iter_elem):
        ul = builder.UL()

        i = 0
        for elem in iter_elem:
            elem = " ".join(elem)
            if self.capitalize_bullets:
                elem = "".join([elem[0].upper(), elem[1:]])

            if i == len(iter_elem) - 1:
                elem += str(self.end_of_last_bullet)
            else:
                elem += str(self.end_of_bullet)

            elem = html.fromstring('<li>' + elem + '</li>')

            ul.append(elem)
            i += 1

        return html.tostring(ul, encoding="utf-8").decode("utf-8")
Exemplo n.º 24
0
def diff(base, new):
    u"""
    Return an Element that renders the version differences between the amis `base` and `new`.

    Arguments:
        base, new (dicts): Descriptions of a deployed AMI. Any keys that start with
            'version:' should have values that are a repo and a sha, separated by a space.
            They must also have the keys 'environment', 'deployment', 'play', and 'ami_id'.
    """
    diff_items = []
    unique_version_changes = set(version_deltas(base, new))
    sorted_version_changes = sorted(unique_version_changes, key=lambda delta: delta.base or delta.new)
    for delta in sorted_version_changes:
        diff_items.append(E.LI(*diff_link(delta)))
    return SECTION(
        E.H3(u"Comparing {base.environment}-{base.deployment}-{base.play}: {base.ami_id} to {new.ami_id}".format(
            base=base,
            new=new,
        )),
        E.UL(*diff_items, style=u"list-style-type: square")
    )
Exemplo n.º 25
0
def format_msg(msg, status):
    if msg.text is not None:
        if "password" in msg.text:
            """Strip out the test password, just in case the report gets sent
            around."""
            return E.P("Entering password")
        if status == "FAIL":
            msg_html = html.fromstring(msg.text)
            if msg_html.xpath(".//a") != []:
                href = msg_html.xpath(".//a")[0].get("href")
                return E.UL(
                    E.CLASS("thumbnails"),
                    E.LI(
                        E.CLASS("span4"),
                        E.A(E.CLASS("thumbnail"), E.IMG(src=href), href=href),
                    ),
                )
            else:
                return E.P(msg.text)
        else:
            return E.P(msg.text)
Exemplo n.º 26
0
    def __bullets_points(self, iter_elem):
        ul = builder.UL()

        i = 0
        for elem in iter_elem:
            elem = " ".join(elem)
            if self.capitalize_bullets:
                elem = "".join([elem[0].upper(), elem[1:]])

            if i == len(iter_elem) - 1:
                elem += str(self.end_of_last_bullet)
            else:
                elem += str(self.end_of_bullet)

            if "<" in elem and ">" in elem:
                elem = handle_string_to_html(builder.SPAN, elem,
                                             builder.CLASS("to_delete"))

            ul.append(builder.LI(elem))
            i += 1

        return html.tostring(ul, encoding="utf-8").decode("utf-8")
Exemplo n.º 27
0
def render_change_as_html(change: Dict[str, Any], filepath: str,
                          current_depth: int, max_depth: int) -> Optional[Any]:
    if current_depth >= max_depth:
        return None

    link = change.get("link")
    if link is None:
        link = filepath

    change_elements: List[Any] = [
        E.B("Name: "),
        E.A(change["name"], href=link),
        E.BR(),
        E.B("Type: "),
        E.SPAN(change["type"]),
        E.BR(),
        E.B("Changed lines: "),
        E.SPAN(str(change["changed_lines"])),
    ]

    if change["total_lines"]:
        change_elements.extend(
            [E.BR(),
             E.B("Total lines: "),
             E.SPAN(str(change["total_lines"]))])

    if change["children"]:
        change_elements.extend([E.BR(), E.B("Changes:")])
    child_elements = []
    for child in change["children"]:
        child_element = render_change_as_html(child, filepath,
                                              current_depth + 1, max_depth)
        if child_element is not None:
            child_elements.append(child_element)
    change_elements.append(E.UL(*child_elements))

    return E.LI(*change_elements)
Exemplo n.º 28
0
def make_menu(index=False):

    if index:
        contact = builder.A(builder.B("Contact"),
                            builder.CLASS("hashtag"),
                            href="#contact")
    else:
        contact = builder.A(builder.B("Contact"), href=base_url + "#contact")

    menu = builder.UL(
        builder.LI(
            builder.A(builder.I("", builder.CLASS("fas fa-bars")), href=""),
            builder.CLASS("menu-button")),
        builder.LI(builder.A(builder.B("Dmitry Kovalev"), href=base_url),
                   builder.CLASS("menu-title")),
        builder.LI(builder.A(builder.B("Posts"), href=base_url + "posts.html"),
                   builder.CLASS("menu-item")),
        builder.LI(
            builder.A(builder.B("Papers"), href=base_url + "papers.html"),
            builder.CLASS("menu-item")),
        builder.LI(contact, builder.CLASS("menu-item")),
        builder.LI(builder.A(builder.B("CV"), href=base_url + "CV/cv.pdf"),
                   builder.CLASS("menu-item")), builder.CLASS("menu"))
    return builder.DIV(menu, builder.CLASS("menu-container"))
def create_table():
    """HTML generation by lxml.html tree."""

    divisions = ['All', 'E', 'CMS', 'T', 'A', 'AE', 'PPD', 'AD/APC',
                 'TD', 'CD', 'ND', 'LBN', 'Other']
    pubtypes = ['All', 'PUB', 'THESIS', 'CONF', 'TM', 'FN', 'SLIDES', 'POSTER']
    dates = [YEAR_2, YEAR_1, YEAR, MONTH_2, MONTH_1, MONTH]
    years = [YEAR_2, YEAR_1, YEAR]
    months = [MONTH_2, MONTH_1, MONTH]

    # This is a doctype work around for a lxml.etree bug
    doctype_wa = etree.parse(StringIO('''<!DOCTYPE html>\n<html>\n</html>'''))
    head_tag = E.HEAD(
        E.META({'charset': 'utf-8'}),
        E.TITLE("FERMILAB RESEARCH AT A GLANCE"),
        E.STYLE(
            {'type': 'text/css'},
            "td {text-align: right;}",
            " td.l {text-align: left;padding: 7px;}",
            " a.t {display: block;}"
        )
    )
    body = E.BODY(E.P(
        E.A("Fermilab Technical Publications",
            href="http://ccd.fnal.gov/techpubs/fermilab_spires.html")
    ))
    tag_h3 = E.H3("FERMILAB RESEARCH AT A GLANCE")
    tag_p = E.P("Glossary at end.")
    tag_p_and_i = E.P(E.I("Updated: " + DATE_TIME_STAMP))

    body.append(tag_h3)
    body.append(tag_p)
    body.append(tag_p_and_i)
    table = E.TABLE()

    tag_tr_td = E.TR(E.TD, E.TD("Date"))
    for division in divisions:
        if division == 'A':
            division = 'AT'
        tag_tr_td.append(E.TD(division))
    table.append(tag_tr_td)

    pub_table_row = E.TR()
    for pubtype in pubtypes:
        pub_table_row.append(E.TD(pubtype))
        pub_type_datelist = E.TD()
        year_list = E.UL()
        month_list = E.UL()
        for year in years:
            year_list.append(E.LI(year))
        for month in months:
            month_list.append(E.LI(month))
        pub_type_datelist.append(year_list)
        pub_type_datelist.append(month_list)
        pub_type_datelist.append(E.UL())
        pub_table_row.append(pub_type_datelist)
        pub_type_datelist = E.TD()

        for division in divisions:
            tdg = E.TD()
            list_of_searches = E.UL()
            for date in dates:
                if division == 'All':
                    division = ''
                if pubtype == 'All':
                    pubtype = ''
                search = 'find r fermilab ' + pubtype
                if division == 'Other':
                    for good_division in divisions[1:len(divisions)-1]:
                        if good_division == 'AD/APC':
                            search += ' not  (r AD or APC)'
                        else:
                            search += ' not r ' + good_division
                elif division == 'AD/APC':
                    search = 'find r fermilab ' + pubtype + \
                             ' and (r AD or APC)'
                else:
                    search += ' ' + division
                search += ' and de ' + date
                search = re.sub(r'\s+', ' ', search)
                result = perform_request_search(p=search, cc="Fermilab")
                result = len(result)
                if result == 0:
                    hit_number = E.LI()
                else:
                    link = search.replace(' ', '+')
                    link = 'https://inspirehep.net/search?cc=Fermilab&p=' + link
                    link += '&rg=100&sf=earliestdate'
                    hit_number = E.LI(E.A({'class': 't'}, str(result),
                                          href=link))
                list_of_searches.append(hit_number)
                if date == YEAR or date == MONTH:
                    tdg.append(list_of_searches)
                    list_of_searches = E.UL()

            pub_table_row.append(tdg)

        table.append(pub_table_row)
        pub_table_row = E.TR()
    glos = E.H4('Glossary')
    table2 = E.TABLE()
    glos_tr_td = E.TR(
        E.TD({'class': 'l'}, "E: Experimental papers"),
        E.TD({'class': 'l'}, "PPD: Particle Physics Division papers")
    )
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "T: Particle Physics Division \
Theoretical Physics Department papers"),
                      E.TD({'class': 'l'}, "AD/APC: Accelerator Division \
and Accelerator Physics Center papers"))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "AT: Fermilab Center for Particle \
Astrophysics theoretical papers"),
                      E.TD({'class': 'l'}, "TD: Technical Division papers"))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "AE: Fermilab Center for Particle \
Astrophysics experimental papers"),
                      E.TD({'class': 'l'}, "CD: Computing Sector papers"))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "ND: Neutrino Division papers"),
                      E.TD({'class': 'l'}, "LBN: Long Baseline Neutrino \
Sector papers"))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, " "), E.TD({'class': 'l'}, " "))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, " "), E.TD({'class': 'l'}, " "))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, " "), E.TD({'class': 'l'}, " "))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "PUB: Paper intended for \
publication in a journal"),
                      E.TD({'class': 'l'}, "FN: Physics note - short paper not \
fitting the other categories"))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "CONF: Paper written as part of a \
conference"),
                      E.TD({'class': 'l'}, "SLIDES: Slides presented at a \
conference or lecture"))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "THESIS: Ph.D. thesis based on \
work done at Fermilab"),
                      E.TD({'class': 'l'}, "POSTER: Poster presented at a \
conference"))
    table2.append(glos_tr_td)
    glos_tr_td = E.TR(E.TD({'class': 'l'}, "TM: Technical memo"),
                      E.TD({'class': 'l'}, ""))
    table2.append(glos_tr_td)

    body.append(table)
    body.append(glos)
    body.append(table2)
    doctype_wa.getroot().append(head_tag)
    doctype_wa.getroot().append(body)
    out = lxml.html.tostring(doctype_wa, encoding='UTF-8', pretty_print=True,
                             method='html').rstrip('\n')
    return out
Exemplo n.º 30
0
    def test_save(self):
        Company = self.env['res.company']

        # create an xmlid for the view
        imd = self.env['ir.model.data'].create({
            'module': 'website',
            'name': 'test_view',
            'model': self.view_id._name,
            'res_id': self.view_id.id,
        })
        self.assertEqual(self.view_id.model_data_id, imd)
        self.assertFalse(imd.noupdate)

        replacement = ET.tostring(h.DIV(
            h.H3("Column 2"),
            h.UL(
                h.LI("wob wob wob"),
                h.LI(
                    h.SPAN(
                        "Acme Corporation",
                        attrs(model='res.company',
                              id=1,
                              field='name',
                              expression="bob",
                              type='char'))),
                h.LI(
                    h.SPAN(
                        "+12 3456789",
                        attrs(model='res.company',
                              id=1,
                              field='phone',
                              expression="edmund",
                              type='char'))),
            )),
                                  encoding='unicode')

        self.view_id.with_context(website_id=1).save(value=replacement,
                                                     xpath='/div/div[2]')
        self.assertFalse(
            imd.noupdate,
            "view's xml_id shouldn't be set to 'noupdate' in a website context as `save` method will COW"
        )
        # remove newly created COW view so next `save()`` wont be redirected to COW view
        self.env['website'].with_context(website_id=1).viewref(
            self.view_id.key).unlink()

        self.view_id.save(value=replacement, xpath='/div/div[2]')

        # the xml_id of the view should be flagged as 'noupdate'
        self.assertTrue(imd.noupdate)

        company = Company.browse(1)
        self.assertEqual(company.name, "Acme Corporation")
        self.assertEqual(company.phone, "+12 3456789")
        self.eq(
            ET.fromstring(self.view_id.arch),
            h.DIV(
                h.DIV(h.H3("Column 1"),
                      h.UL(h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))),
                h.DIV(
                    h.H3("Column 2"),
                    h.UL(h.LI("wob wob wob"), h.LI(h.SPAN({'t-field': "bob"})),
                         h.LI(h.SPAN({'t-field': "edmund"}))))))