def add_images(self, ims, txts, links, width=400):
        """add images to the HTML file

        Parameters:
            ims (str list)   -- a list of image paths
            txts (str list)  -- a list of image names shown on the website
            links (str list) --  a list of hyperref links; when you click an image, it will redirect you to a new page
        """
        self.t = table(border=1,
                       style="table-layout: fixed;")  # Insert a table
        self.doc.add(self.t)
        with self.t:
            with tr():
                for im, txt, link in zip(ims, txts, links):
                    with td(style="word-wrap: break-word;",
                            halign="center",
                            valign="top"):
                        with p():
                            with a(href=os.path.join("images", link)):
                                img(
                                    style="width:%dpx" % width,
                                    src=os.path.join("images", im),
                                )
                            br()
                            p(txt)
Ejemplo n.º 2
0
def convert_new_in_html(cmd_args, new, html_file):
    """
    Convert one new to HTML format
    """

    with html_file:
        with tag.div():
            tag.h2(new.get('title'))
            tag.p(new.get('date'))
            tag.br()
            tag.a("Read the full article", href=new.get('link'))
            tag.br()
            tag.br()

            if cmd_args.date:
                for num, link in enumerate(new.get('img_link'), 1):
                    tag.a(f"Image link № {num}", href=link)
                    tag.br()
            else:
                for num, link in enumerate(new.get('img_link')):
                    tag.img(src=link, alt=new.get('img_title')[num])
                    tag.br()

            tag.p(new.get('text'))
            tag.br()

    return html_file
Ejemplo n.º 3
0
def report(supplement, outcome, p=False, show=False):

    supplement_name = supplement.replace('-', ' ')
    outcome_name = outcome.replace('-', ' ')
    title='Report on the effects of {} with respect to {}'.format(supplement_name, outcome_name)
    fname = 'reports/{}.pdf'.format(title)
    doc = dominate.document(title=title)

    # with doc.head:
    #     link(rel='stylesheet', href='style.css')
    #     script(type='text/javascript', src='script.js')

    summary = str(pformat(supplement_metallmind[supplement]['summary'].replace('\n', ' ')))[2:-1]
    outcome = supplement_metallmind[supplement]['outcomes'][outcome]
    grade_info = 'level of evidence: {}'.format(outcome['grade'])
    magnitude_info = 'magnitude of effect: {}'.format(outcome['magnitude'])
    consistency_info = 'consistency of research results: {}'.format(outcome['consistency'])
    notes = outcome['notes']

    doc += h1(title)
    doc += h2('Summary')
    doc += tags.p(summary)
    doc += h2('Effects on {}'.format(outcome_name))
    doc += tags.p(grade_info)
    doc += tags.p(magnitude_info)
    doc += tags.p(consistency_info)
    if notes is not None:
        doc += h3('notes')
        doc += tags.p(notes)

    HTML(string=str(doc)).write_pdf(fname)
    if show:
        os.system('xpdf {}'.format(fname.replace(' ', '\ ')))
    if p:
        os.system('lp {}'.format(fname.replace(' ', '\ ')))
Ejemplo n.º 4
0
 def accordian_collapse(color, title, content, pre, raw_html, **kwargs):
     """
     Creates a collapsible accordian
     """
     title_random = HelperFunctions.id_with_random(5, title)
     with tag.div(_class="jumbotron container reportng-section-collapsible-class") as h:
         # with tag.div(id="accordian"):
         with tag.div(_class="card"):
             with tag.div(_class="card-header %s reportng-collapse-card-header-class" % color,
                          id="headingOne%s" % title_random):
                 tag.h1(title, _class=color, data_toggle="collapse", data_target="#collapse%s" % title_random,
                        aria_expanded="true", aria_controls="collapse%s" % title_random, id=title_random)
             with tag.div(id="collapse%s" % title_random, _class="collapse",
                          aria_labelledby="headingOne%s" % title_random, data_parent="#accordion"):
                 with tag.div(_class="card-body context reportng-collapse-card-body-class"):
                     if raw_html != '':
                         raw(raw_html)
                     elif pre:
                         tag.pre(content)
                     else:
                         tag.p(content)
             if 'alert' in kwargs:
                 HelperFunctions.make_alert(kwargs.get('alert'))
             if 'badge' in kwargs:
                 HelperFunctions.create_badges(kwargs.get('badge'))
     return HelperFunctions.convert_to_string(h)
Ejemplo n.º 5
0
def Page():
    doc = document()
    with doc.head:
        link_("https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css")
        link_("https://extra-uru1z3cxu.now.sh/css/extra.css")
        link_("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css")
        script_("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js")
        script_("http://intercoolerjs.org/release/intercooler-1.2.2.js")

    with doc.body:
        with dom.div(cls=CENTER_FRAME) as CenterFrame:
            with dom.form(FORM_ATTR):
                with dom.div(cls=LABEL_CARD):
                    dom.label('Write down your mark here',
                              cls="text-white text-xl")
                    dom.input(
                        cls=LABEL_INPUT, type='text', placeholder='your watermark text here', name='mk-text')
                with dom.div(cls=IMG_CARD):
                    with dom.div(cls=IMG_FORM):
                        dom.i(cls=UPLOAD_ICON,
                              onclick='''$('#fileupload').click()''')
                        dom.p("Find File", id="file", cls="text-gray-500 mt-4")
                        dom.input(cls="hidden", type="file", name='bg-img', id="fileupload",
                                  onchange='''$('#file').text(this.value.split("\\\\").pop(-1))''')
                        dom.button('Upload', cls=BUTTON, type='submit')

            with dom.div(cls=RESULT_CONTAINER, id="there") as ResultContainer:
                dom.span(id="here")
    return doc.render()
Ejemplo n.º 6
0
def Item(file_name="{{ file_name }}"):
    with dom.div(cls=RESULT_ITEM) as ResultItem:
        dom.p(f"{ file_name }.jpg", cls="text-xl text-gray-400")
        with dom.a(href=f"/download?filename={file_name}"):
            dom.i(cls="fas fa-download text-xl text-gray-400")

    return ResultItem.render() + dom.span(id="here").render()
Ejemplo n.º 7
0
def add_to_output(html_doc, para):
    global new_lines_in_raw
    # we shouldn't accept empty paragraph (?)
    assert len(para) > 0

    with html_doc.body.children[-1]:
        assert html_doc.body.children[-1]['class'] == 'container-fluid';
        for (i, (type, text)) in enumerate(para):
            if 'heading' in type and text.strip():
                # tags.p()
                # tags.p()
                heading = sizes.get_heading_type(size_kind)
                print type, text
                heading(text)
            elif type == "new_line":
                new_lines_in_raw += 1
                if new_lines_in_raw == 1:
                    tags.br()
                elif new_lines_in_raw == 2:
                    tags.p()
                else:
                    pass
            elif is_subject(para, i):
                if not is_prev_subject(para, i):
                    # tags.p()
                    #tags.br()
                    pass
                subject(html_doc, type, text)
            else:
                regular(type, text)

            if type != "new_line":
                new_lines_in_raw = 0
def test1_basic(record):
    d = _doc('Test 1')
    with d:
        with t.div(cls='test1_cls', id='test1_id'):
            t.p('This is a test paragraph; test record id: %s, "test" value: "%s"'
                % (record['id'], record['name']))
    return d.render()
Ejemplo n.º 9
0
 def add_image(self,
               im,
               title,
               txt='',
               width=None,
               height=None,
               font_pct=100):
     if width is None:
         width = self.default_image_width
     if height is None:
         height = self.default_image_height
     if self.t is None or self.row_image_count >= self.images_per_row:
         self._add_table()
     with self.t:
         # with tr():
         # with td(style="word-wrap: break-word;", halign="center", valign="top"):
         with tags.td(halign="center", valign="top"):
             with tags.p():
                 if height is not None:
                     img_style = "width:{}px; height:{}px".format(
                         width, height)
                 else:
                     img_style = "width:{}px;".format(width)
                 tags.img(style=img_style,
                          src=r'data:image/png;base64,' +
                          self._encode_image(im))
                 tags.br()
                 tags.p(
                     "{}\n{}".format(title, txt),
                     style=
                     'width:{}px; word-wrap: break-word; white-space: pre-wrap; font-size: {}%;'
                     .format(width, font_pct))
     self.row_image_count += 1
Ejemplo n.º 10
0
def makeHtml(path, fileName, sitename, authorname, usecss, usejs):
    doc = dominate.document(title=sitename)

    with doc.head:
        if (usecss.lower() == "y"):
            link(rel='stylesheet', href='style.css')
        if (usejs.lower() == "y"):
            script(type='text/javascript', src='script.js')
        with meta():
            attr(author=authorname)

    with doc:
        with div(id='header').add(ol()):
            for i in ['home', 'about', 'contact']:
                li(a(i.title(), href='/%s.html' % i))

        with div():
            attr(cls='body')
            p('Lorem ipsum..')

    if not os.path.exists("./" + path):
        os.makedirs("./" + path)

    f = open("./" + path + "/" + fileName, 'w+')
    f.write(str(doc))
    f.close()

    if (usejs.lower() == "y"):
        if not os.path.exists("./" + sitename + "/js"):
            os.makedirs("./" + sitename + "/js")
    if (usecss.lower() == "y"):
        if not os.path.exists("./" + sitename + "/css"):
            os.makedirs("./" + sitename + "/css")
Ejemplo n.º 11
0
def diff(master_screens_path, current_screens_path, test_name, master_hash,
         current_hash):
    doc = dominate.document(title=test_name)
    master_screens = sorted(master_screens_path.iterdir())
    current_screens = sorted(current_screens_path.iterdir())

    with doc:
        h1(test_name)
        p("This UI test differs from master.",
          style="color: grey; font-weight: bold;")
        with table():
            with tr():
                td("Master:")
                td(master_hash, style="color: red;")
            with tr():
                td("Current:")
                td(current_hash, style="color: green;")
        hr()

        with table(border=1, width=600):
            with tr():
                th("Master")
                th("Current branch")

            html.diff_table(master_screens, current_screens)

    return html.write(REPORTS_PATH / "diff", doc, test_name + ".html")
Ejemplo n.º 12
0
def generateStatsHTML(graph,statsFilePath = "stats.html",postStatsFilePath = "postStats.html"): #Generates the Stats HTML section

	firstLevel = checkFirstLevel(graph)
	softwareLabelNum = queryVersionNum(graph)
	softwareLabelNumList = addQueryToList(softwareLabelNum)
	
	stats = document(title="FSL Viewer") #Creates initial html page (stats)
	stats += h1("Sample FSL Viewer")
	stats += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html")))
	stats += h2("Stats")
	stats += hr()
	stats += h3("Analysis Methods")
	
	if askSpm(graph) == True: #Checks if SPM was used
		
		stats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/)." % softwareLabelNumList[1])
		
	elif askFsl(graph) == True: #Checks if FSL was used
		
		fslFeatVersion = queryFslFeatVersion(graph)
		stats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)." % (fslFeatVersion[0], softwareLabelNumList[1]))
		
	stats += hr()
	stats += h3("Design Matrix")
	
	designMatrixLocation = queryDesignMatrixLocation(graph)
	stats += a(img(src = designMatrixLocation[1], style = "border:5px solid black", border = 0), href = designMatrixLocation[0]) #Adds design matrix image (as a link) to html page
	
	statsFile = open(statsFilePath, "x")
	print(stats, file = statsFile) #Prints html page to a file
	statsFile.close()
Ejemplo n.º 13
0
    def get_ncdump_html(self):
        """
        Generates html code to display the contents of the ncdump text file. The generated html
        is used for netcdf file type metadata view and edit modes.
        :return:
        """

        nc_dump_div = div()
        nc_dump_res_file = None
        for f in self.logical_file.files.all():
            if f.extension == ".txt":
                nc_dump_res_file = f
                break
        if nc_dump_res_file is not None:
            nc_dump_div = div(style="clear: both", cls="col-xs-12")
            with nc_dump_div:
                legend("NetCDF Header Information")
                p(nc_dump_res_file.full_path[33:])
                header_info = nc_dump_res_file.resource_file.read()
                header_info = header_info.decode('utf-8')
                textarea(header_info,
                         readonly="",
                         rows="15",
                         cls="input-xlarge",
                         style="min-width: 100%")

        return nc_dump_div
Ejemplo n.º 14
0
    def get_html_forms(self, datatset_name_form=True):
        """generates html forms for all the metadata elements associated with this logical file
        type
        :param datatset_name_form If True then a form for editing dataset_name (title) attribute is
        included
        """
        root_div = div()

        with root_div:
            if datatset_name_form:
                self._get_dataset_name_form()

            keywords_div = div(cls="col-sm-12 content-block",
                               id="filetype-keywords")
            action = "/hsapi/_internal/{0}/{1}/add-file-keyword-metadata/"
            action = action.format(self.logical_file.__class__.__name__,
                                   self.logical_file.id)
            delete_action = "/hsapi/_internal/{0}/{1}/delete-file-keyword-metadata/"
            delete_action = delete_action.format(
                self.logical_file.__class__.__name__, self.logical_file.id)
            with keywords_div:
                legend("Keywords")
                with form(id="id-keywords-filetype",
                          action=action,
                          method="post",
                          enctype="multipart/form-data"):

                    input(id="id-delete-keyword-filetype-action",
                          type="hidden",
                          value=delete_action)
                    with div(cls="tags"):
                        with div(id="add-keyword-wrapper", cls="input-group"):
                            input(id="txt-keyword-filetype",
                                  cls="form-control",
                                  placeholder="keyword",
                                  type="text",
                                  name="keywords")
                            with span(cls="input-group-btn"):
                                a("Add",
                                  id="btn-add-keyword-filetype",
                                  cls="btn btn-success",
                                  type="button")
                    with ul(id="lst-tags-filetype",
                            cls="custom-well tag-list"):
                        for kw in self.keywords:
                            with li(cls="tag"):
                                span(kw)
                                with a():
                                    span(
                                        cls=
                                        "glyphicon glyphicon-remove-circle icon-remove"
                                    )
                p("Duplicate. Keywords not added.",
                  id="id-keywords-filetype-msg",
                  cls="text-danger small",
                  style="display: none;")

            self.get_extra_metadata_html_form()
            self.get_temporal_coverage_html_form()
        return root_div
Ejemplo n.º 15
0
    def output_mismatch(self, ref_name, prof_name):
        """Output mismatch section"""

        tags.h4("List of algorithms with different results:",
                style="color:var(--red-color);display:inline-block")

        header = ["Algorithm",
                  ref_name + " (reference)",
                  prof_name + " (profiled)"]

        data = []
        for key in self.mismatch:
            ref = self.mismatch[key][0]
            prof = self.mismatch[key][1]

            reftext = "{:.2f}".format(ref.operation_avg()) + " ms"
            proftext = "{:.2f}".format(prof.operation_avg()) + " ms"

            data.append([key, reftext, proftext])

        sm_div = show_hide_div("performance_mismatch_div", hide=False)

        with sm_div:
            tags.p(
                "These are the algorithms in which the cards performed "
                "with different results."
            )
            table(data, header,
                  red_value="ms")
def report_headline(version):
    with div(cls='jumbotron'):
        h1('Audit Engine: {version} - Discrepancy Report for Automated Independent Audit'
           .format(version=version))
        build_time = datetime.datetime.now(datetime.timezone.utc)
        p(f'Summary built at: {build_time.strftime("%Y-%m-%d %H:%M:%S")}',
          cls='lead')
Ejemplo n.º 17
0
    def output_support_mismatch(self, ref_name: str, prof_name: str):
        """Output algorithm support differences section"""

        tags.h4("Differences in algorithm support:",
                style="color:var(--red-color);display:inline-block")

        header = ["Algorithm",
                  ref_name + " (reference)",
                  prof_name + " (profiled)"]

        data = []
        for key in self.support_mismatch:
            ref = self.support_mismatch[key][0]
            prof = self.support_mismatch[key][1]

            reftext = "Supported" if ref.support else "Unsupported"
            if ref.error:
                reftext = ref.error

            proftext = "Supported" if prof.support else "Unsupported"
            if prof.error:
                proftext = prof.error

            data.append([key, reftext, proftext])

        sm_div = show_hide_div("support_mismatch_div")

        with sm_div:
            tags.p(
                "If an algorithm is supported by the reference card, but not "
                "the profiled card and vice versa, the cards almost certainly "
                "do not match.")
            table(data, header,
                  green_value="Supported",
                  red_value="Unsupported")
Ejemplo n.º 18
0
 def get_dataset_name_html(self):
     """generates html for viewing dataset name (title)"""
     if self.logical_file.dataset_name:
         dataset_name_div = div(cls="col-xs-12 content-block")
         with dataset_name_div:
             legend("Title")
             p(self.logical_file.dataset_name)
         return dataset_name_div
Ejemplo n.º 19
0
def create_doc(my_date=""):
    doc = document(title="My favorite page")
    with doc:
        with div():
            attr(cls="body")
            p("lorem ipsum")
            p(f"{my_date}")
    return doc
Ejemplo n.º 20
0
 def html(self):
     # If the user just calls ``html()``, we fill out a basic page.
     with self._edit_html():
         H.h1('Hello world!')
         H.p(lorem_ipsum())
         H.p(lorem_ipsum())
     # But then we also return the context manager that can be used
     # to rebuild the page as the user wishes. It does nothing unless
     # it is entered (``with``).
     return self._edit_html()
Ejemplo n.º 21
0
 def add_text(self, txts, width=400):
     self.add_table()
     with self.t:
         with tr():
             for txt in txts:
                 with td(style="word-wrap: break-word;",
                         halign="center",
                         valign="top"):
                     with p(style="width:%dpx" % width):
                         p(h3(txt))
Ejemplo n.º 22
0
 def add_images(self, ims, txts, links, width=400, height=300):
     self.add_table()
     with self.t:
         with tr():
             for im, txt, link in zip(ims, txts, links):
                 with td(style="word-wrap: break-word; height:{}px; width:{}px".format(height + 10,width + 10), halign="center", valign="top"):
                     with p():
                         with a(href=os.path.join('/',link)):
                             img(style="width:{}px;height:{}".format(width, height), src=os.path.join('/',im))
                         br()
                         p(txt)
Ejemplo n.º 23
0
 def add_images(self, ims, txts, links, width=400):
     self.add_table()
     with self.t:
         with tr():
             for im, txt, link in zip(ims, txts, links):
                 with td(style="word-wrap: break-word;", halign="center", valign="top"):
                     with p():
                         with a(href=os.path.join('images', link)):
                             img(style="width:%dpx" % width, src=os.path.join('images', im))
                         br()
                         p(txt)
Ejemplo n.º 24
0
def create_mainpage_html(local, url_list, path, web_title):
    _html = dmtags.html(style="background-color:#fcfbeb;")
    _head, _body = _html.add(dmtags.head(dmtags.title(web_title)),
                             dmtags.body(cls="main_page"))
    with _head:
        dmtags.comment("The page is genarated on {} by Ein".format(
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
        dmtags.meta(charset="utf-8",
                    name="viewport",
                    content="width=device-width, initial-scale=1")
        dmtags.link(
            href="https://fonts.googleapis.com/css?family=Noto+Sans+JP:500",
            rel="stylesheet")
        dmtags.link(
            href=
            "https://cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.min.css",
            rel="stylesheet")
        dmtags.link(href="https://rawcdn.githack.com/c892836a/python_for_fun/"
                    "b2fa53022b0ae5a26d6f140c38b860a210c21040/css/custom.css",
                    rel="stylesheet")
        dmtags.link(
            href="https://lh3.googleusercontent.com/S__tM5EYqZDFLuv1uPG" +
            "mlZTTLLyNAbUvljzDH8-S0Pxq2nA9fnFF3SwU0w0wF8PlMu_hv3WhLMdlFodKbQ=s0",
            rel="shortcut icon",
            type="image/vnd.microsoft.icon")
    main_div = _body.add(
        dmtags.div(
            style=
            "text-align:center; font-family: 'Noto Sans JP', sans-serif; font-size:36px;"
        ))

    with main_div:
        _p1 = dmtags.p(style="color:#470000;")
        for url in url_list:
            _p2 = dmtags.p(style="font-size:20px;")
            with _p2:
                dmtags.a(url[0], href="{}".format(url[1]))
        with _p1:
            text("{}".format(web_title))

    # create html file
    if local:
        os.chdir(path)
        os.chdir(os.pardir)
        with open("{}.html".format(web_title), "w", encoding='utf8') as f:
            f.write("<!DOCTYPE html>\n")
            f.write(_html.render())

    else:
        with open("{}\\{}.html".format(path, web_title), "w",
                  encoding='utf8') as f:
            f.write("<!DOCTYPE html>\n")
            f.write(_html.render())
Ejemplo n.º 25
0
 def add_images(self, ims, txts, links, width=400):
     self.t = table(border=1, style="table-layout: fixed;")  # Insert a table
     self.doc.add(self.t)
     with self.t:
         with tr():
             for im, txt, link in zip(ims, txts, links):
                 with td(style="word-wrap: break-word;", halign="center", valign="top"):
                     with p():
                         with a(href=os.path.join('images', link)):
                             img(style="width:%dpx" % width, src=os.path.join('images', im))
                         br()
                         p(txt)
Ejemplo n.º 26
0
    def __init__(self, series, **kwargs):
        super().__init__(f"Remove the {series.name} series")
        self.series = series
        with self.content:
            tags.p("""Remove the series from the Manna app.

                        Note this does NOT remove the series from the backing
                        storage. So if vimeo is your backing store for example,
                        you will still need to remove the series from vimeo
                        separately but the series will no longer be represented
                        in the Manna app unless it is reimported.""",
                   style="text-align: left;")
        self.on_ready_scriptage = f"""
Ejemplo n.º 27
0
 def __init__(self, series, **kwargs):
     super().__init__(f"Normalize the video names in {series.name}")
     with self.content:
         if series.normalizable_vids:
             tags.label("The following video titles can be normalized:")
             self.addTable(VideoTable(series.normalizable_vids))
             example = series.normalizable_vids[0].name
             tags.pre(f'For example, "{example}" would become ' +
                      f'"{series.normalized_name(example)}"',
                      style="text-align: left;")
         else:
             tags.p("Nothing to normalize in this series...")
             self.submit_tag['disabled'] = True
Ejemplo n.º 28
0
def _block(profession, toml):
    with div(id=profession):
        with div(class_name='content'):
            with div(id=f'{profession}-logo'):
                for style, token in toml['logo']['tokens']:
                    span(raw(token), class_name=style)
            with div(class_name='text'):
                with div(class_name='biography'):
                    for paragraph in toml['biography']['paragraphs']:
                        p(paragraph)
                with div(class_name='links'):
                    for link in toml['links']:
                        a(link['label'], href=link['url'], target='_blank')
                        p(link['summary'])
Ejemplo n.º 29
0
def Item(file_name):
    with open(f'{file_name}.jpg', 'rb') as img_file:
        b64_str = base64.b64encode(img_file.read())
    with dom.div(cls=RESULT_ITEM) as ResultItem:
        dom.p(f"{ file_name }.jpg", {
            "ic-action": "slideToggle",
            "ic-target": f"#{file_name}"
        },
              cls="w-full text-xl text-gray-400")
        dom.img(src=f"data:image/jpeg;base64,{b64_str.decode('utf-8')}",
                id=f"{file_name}",
                cls="w-full",
                style="display:none")

    return ResultItem.render() + dom.span(id="here").render()
Ejemplo n.º 30
0
def motionvote_preselecthtml():
    motionvotekey = request.args.get(MOTIONVOTE_KEY_URLARG)
    motionvote = MotionVote.query.filter_by(motionvotekey=motionvotekey).one()
    meeting = motionvote.meeting
    motion = motionvote.motion
    user = motionvote.user
    html = div()
    with html:
        h1('{} {}: {}\'s Vote'.format(meeting.date, meeting.purpose, user.name))
        p(b('Motion'))
        with div(style='margin-left: 1em;'):
            raw(motion.motion)
            if motion.comments:
                raw(motion.comments)
    return html.render()
Ejemplo n.º 31
0
def _render_response(resp):
    with H.section():
        with H.div(_class=u'message-display'):
            if resp.remark:
                H.p(printable(resp.remark), _class=u'message-remark')
            with H.h2(), H.code():  # Status line
                # See above regarding spaces.
                if resp.version:
                    H.span(printable(resp.version),
                           **_for_object(resp.version))
                with H.span(**_for_object(resp.status)):
                    _render_known(resp.status)
                    H.span(printable(find_reason_phrase(resp)))
            _render_message(resp)  # Headers, body and all that
        _render_complaints(resp)
Ejemplo n.º 32
0
 def add_text_sep(self, txts, width=400):
     self.add_table()
     with self.t:
         with tr():
             for txt in txts:
                 with td(style="word-wrap: break-word;",
                         halign="center",
                         valign="top"):
                     with p(style="width:%dpx" % width):
                         splitted = txt.split(',')
                         if len(splitted) > 1:
                             for h in splitted:
                                 p(h3(h))
                         else:
                             p(h3(txt))
Ejemplo n.º 33
0
 def add_images(self, ims, txts, links, width=400):
     """Add images to table."""
     table = self.add_table()
     tr = table.add(htags.tr())
     with tr:
         for im, txt, link in zip(ims, txts, links):
             with htags.td(style="word-wrap: break-word;",
                           halign="center",
                           valign="top"):
                 with htags.p():
                     with htags.a(href=os.path.join('images', link)):
                         htags.img(style="width:%dpx" % width,
                                   src=os.path.join('images', im))
                     htags.br()
                     htags.p(txt)
Ejemplo n.º 34
0
def _render_request(req):
    with H.section():
        with H.div(_class=u'message-display'):
            if req.remark:
                H.p(printable(req.remark), _class=u'message-remark')
            with H.h2(), H.code():      # Request line
                # We don't insert spaces here because,
                # without ``__pretty=False``,
                # Dominate renders each element on its own line,
                # thus implicitly creating whitespace.
                with H.span(__pretty=False, **_for_object(req.method)):
                    _render_known(req.method)
                H.span(printable(req.target), **_for_object(req.target))
                if req.version:
                    H.span(printable(req.version), **_for_object(req.version))
            _render_message(req)        # Headers, body and all that
        _render_complaints(req)
Ejemplo n.º 35
0
def _render_response(resp):
    with H.section():
        with H.div(_class=u'message-display'):
            if resp.remark:
                H.p(printable(resp.remark), _class=u'message-remark')
            with H.h2(), H.code():      # Status line
                # See above regarding spaces.
                if resp.version:
                    H.span(printable(resp.version),
                           **_for_object(resp.version))
                # httpolice-devtool (the Chrome extension) relies
                # on the ``StatusCode`` class. Avoid breaking it, at least
                # as long as it doesn't inconvenience HTTPolice itself.
                with H.span(**_for_object(resp.status, u'StatusCode')):
                    _render_known(resp.status)
                    text_node(u' ' + printable(find_reason_phrase(resp)))
            _render_message(resp)       # Headers, body and all that
        _render_complaints(resp)
Ejemplo n.º 36
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        H.p(u'This is the list of all notices produced by ',
            H.a(u'HTTPolice', href=homepage, target='_self'),
            u' version ', version, u'.')
        H.p(u'See also the ',
            H.a(u'HTTPolice manual', href=u'index.html', target='_self'), u'.')
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_], placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
Ejemplo n.º 37
0
    def get_json_file_data_html(self):
        """
        Generates html code to display the contents of the json file. The generated html
        is used for ref timeseries file type metadata in the view and edit modes.
        :return:
        """

        json_res_file = self.logical_file.files.first()
        json_file_content_div = div(cls="content-block")
        with json_file_content_div:
            legend("Reference Time Series JSON File Content")
            p(json_res_file.full_path[33:])
            header_info = self.json_file_content
            if isinstance(header_info, str):
                header_info = unicode(header_info, 'utf-8')

            textarea(header_info, readonly="", rows="15",
                     cls="input-xlarge", style="min-width: 100%; resize: vertical;")

        return json_file_content_div
Ejemplo n.º 38
0
    def get_ts_series_html(self):
        """Generates html for all time series """

        root_div = div()
        with root_div:
            legend("Reference Time Series")
            panel_group_div = div(cls="panel-group", id="accordion")
            panel_group_div.add(p("Note: Time series are listed below by site name. "
                                  "Click on a site name to see details."))
            for index, series in enumerate(self.time_series_list):
                panel_group_div.add(series.get_html(index + 1))

        return root_div
Ejemplo n.º 39
0
    def visit_Field(self, node):
        # FIXME: add error class

        wrap = self._get_wrap(node)

        # add the label
        wrap.add(tags.label(node.label.text, _for=node.id))
        wrap.add(raw(node()))

        if node.description:
            wrap.add(tags.p(node.description, _class='form-text text-muted'))

        return wrap
Ejemplo n.º 40
0
    def get_ncdump_html(self):
        """
        Generates html code to display the contents of the ncdump text file. The generated html
        is used for netcdf file type metadata view and edit modes.
        :return:
        """

        nc_dump_div = div()
        nc_dump_res_file = None
        for f in self.logical_file.files.all():
            if f.extension == ".txt":
                nc_dump_res_file = f
                break
        if nc_dump_res_file is not None:
            nc_dump_div = div(style="clear: both", cls="content-block")
            with nc_dump_div:
                legend("NetCDF Header Information")
                p(nc_dump_res_file.full_path[33:])
                header_info = nc_dump_res_file.resource_file.read()
                header_info = header_info.decode('utf-8')
                textarea(header_info, readonly="", rows="15",
                         cls="input-xlarge", style="min-width: 100%; resize: vertical;")

        return nc_dump_div
Ejemplo n.º 41
0
    def __init__(self, *args, field=None, **kwargs):
        self.kclass_dep = KClassDep('form-group')
        if field is not None:
            if field.errors:
                self.kclass_dep.append('has-error')
            if field.flags.required:
                self.kclass_dep.append('required')

        super().__init__(**self.update_kwargs(kwargs))

        if field is not None:
            self.add(
                raw(str(field.label)),
                br(),
                raw(field(class_='form-control')),
            )

            if field.errors:
                for error in field.errors:
                    self.add(p(error, _class='help-block'))
Ejemplo n.º 42
0
    def get_html(self):
        """overrides the base class function"""

        html_string = super(RefTimeseriesFileMetaData, self).get_html()
        if self.abstract:
            abstract_div = div(cls="content-block")
            with abstract_div:
                legend("Abstract")
                p(self.abstract)

            html_string += abstract_div.render()
        if self.file_version:
            file_ver_div = div(cls="content-block")
            with file_ver_div:
                legend("File Version")
                p(self.file_version)
            html_string += file_ver_div.render()
        if self.symbol:
            symbol_div = div(cls="content-block")
            with symbol_div:
                legend("Symbol")
                if self.symbol.startswith('http'):
                    with p():
                        a(self.symbol, href=self.symbol, target="_blank")
                else:
                    p(self.symbol)
            html_string += symbol_div.render()
        if self.temporal_coverage:
            html_string += self.temporal_coverage.get_html()

        if self.spatial_coverage:
            html_string += self.spatial_coverage.get_html()

        html_string += self.get_ts_series_html().render()
        html_string += self.get_json_file_data_html().render()
        template = Template(html_string)
        context = Context({})
        return template.render(context)
Ejemplo n.º 43
0
def generatePostStatsHTML(graph,statsFilePath = "stats.html",postStatsFilePath = "postStats.html"): #Generates Post-Stats page
	voxelWise = checkHeightThreshold(graph)
	clusterWise = checkExtentThreshold(graph)
	softwareLabelNum = queryVersionNum(graph)
	softwareLabelNumList = addQueryToList(softwareLabelNum)
	statisticType = queryStatisticType(graph)
	statisticType = statisticImage(statisticType[0])
	statisticTypeString = statisticImageString(statisticType)
	contrastName = queryContrastName(graph)
	statisticMapImage = queryExcursionSetMap(graph)
	
	postStats = document(title="FSL Viewer") #Creates initial HTML page (Post Stats)
	postStats += h1("Sample FSL Viewer")
	postStats += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html")))
	postStats += h2("Post-stats")
	postStats += hr()
	postStats += h3("Analysis Methods")
	
	if voxelWise == True: #If main threshold is Height Threshold
		mainThreshValue = queryHeightThresholdValue(graph)
		if askSpm(graph) == True:
			
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at P = %s (corrected)" % (softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
	
		elif askFsl(graph) == True:
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)."
			"%s statistic images were thresholded at P = %s (corrected)" 
			%(fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
	
	elif clusterWise == True: #If main threshold is extent threshold
		
		mainThreshValue = queryClusterThresholdValue(graph)
		heightThreshValue = queryUHeightThresholdValue(graph)
		clusterThreshType = clusterFormingThreshType(graph, statisticType)
		
		if askSpm(graph) == True:
			
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded using clusters determined by %s > %s and a (corrected) "
			"cluster significance of P = %s " 
			% (softwareLabelNumList[1], statisticTypeString, clusterThreshType, heightThreshValue[0], mainThreshValue[0]))
	
		elif askFsl(graph) == True:
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl). %s statistic images were thresholded "
			"using clusters determined by %s > %s and a (corrected) cluster significance of P = %s" 
			%(fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, clusterThreshType, heightThreshValue[0], mainThreshValue[0]))
		
	
	else: #If there is no corrected threshold - assume voxel wise
		mainThreshValue = queryUHeightThresholdValue(graph)
		if askSpm(graph) == True and askIfPValueUncorrected(graph) == True: #SPM used and threshold type is nidm_PValueUncorrected
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at P = %s (uncorrected)" % (softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
			
		
		elif askSpm(graph) == True and askIfOboStatistic(graph) == True: #SPM used and threshold type is obo_statistic
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at %s = %s (uncorrected)" % (softwareLabelNumList[1], statisticTypeString, statisticType, mainThreshValue[0]))
			
		
		elif askFsl(graph) == True and askIfPValueUncorrected(graph) == True:
			
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)."
			"%s statistic images were thresholded at P = %s (uncorrected)." % (fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
			
			
		elif askFsl(graph) == True and askIfOboStatistic(graph) == True:
			
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)."
			"%s statistic images were thresholded at %s = %s (uncorrected)." % (fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, statisticType, mainThreshValue[0]))
			
		
	
	postStats += hr()
	postStats += h3("Thresholded Activation Images")
	postStats += hr()
	i = 0
	
	if askFsl(graph) == True:
	
		while i < len(contrastName):
		
			postStats += p("%s" % contrastName[i])
			postStats += img(src = statisticMapImage[i])
			i = i + 1
	
	postStatsFile = open(postStatsFilePath, "x")
	print(postStats, file = postStatsFile)
	postStatsFile.close()
Ejemplo n.º 44
0
def htmlize_p(notation):
    """Like `htmlize`, wrapped in a ‘p’.
    Does not return: instead, must be run in a dominate context.
    """
    with tags.p():
        htmlize(notation)
Ejemplo n.º 45
0
def _exc_to_html(_, ctx):
    for para in expand_error(ctx['error']):
        with H.p():
            _piece_to_html(para, ctx)
Ejemplo n.º 46
0
def _paragraph_to_html(para, ctx):
    with H.p():
        _piece_to_html(para.content, ctx)
Ejemplo n.º 47
0
 def visit_Text(self, node):
     if not self._in_dropdown:
         return tags.p(node.text, _class='navbar-text')
     return tags.li(node.text, _class='dropdown-header')
Ejemplo n.º 48
0
def _paragraph_to_html(para, ctx):
    with H.p(__pretty=False):
        _piece_to_html(para.content, ctx)
Ejemplo n.º 49
0
    def get_html_forms(self, dataset_name_form=True, temporal_coverage=True):
        """overrides the base class function"""

        root_div = div()
        with root_div:
            div("{% load crispy_forms_tags %}")
            if self.has_title_in_json:
                # title is in json file - we don't allow the user to edit title (dataset name)
                self.get_dataset_name_html()
            else:
                # title is not in json file - we allow the user to edit title (dataset name)
                self.get_dataset_name_form()
            if self.has_keywords_in_json:
                self.get_keywords_html()
            else:
                self.get_keywords_html_form()

            self.get_extra_metadata_html_form()
            abstract_div = div(cls="content-block")
            with abstract_div:
                if self.has_abstract_in_json:
                    # abstract is in json file - we don't allow the user to edit abstract
                    legend("Abstract")
                    p(self.abstract)
                else:
                    # abstract is not in json file - we allow the user to edit abstract
                    self.get_abstract_form()
            if self.file_version:
                file_ver_div = div(cls="content-block")
                with file_ver_div:
                    legend("File Version")
                    p(self.file_version)

            if self.symbol:
                symbol_div = div(cls="content-block")
                with symbol_div:
                    legend("Symbol")
                    if self.symbol.startswith('http'):
                        with p():
                            a(self.symbol, href=self.symbol, target="_blank")
                    else:
                        p(self.symbol)

            self.get_temporal_coverage_html_form()
            with div(cls="content-block"):
                with form(id="id-coverage-spatial-filetype", action="{{ spatial_form.action }}",
                          method="post", enctype="multipart/form-data"):
                    div("{% crispy spatial_form %}")
                    with div(cls="row", style="margin-top:10px;"):
                        with div(cls="col-md-offset-10 col-xs-offset-6 "
                                     "col-md-2 col-xs-6"):
                            button("Save changes", type="button",
                                   cls="btn btn-primary pull-right",
                                   style="display: none;",
                                   onclick="metadata_update_ajax_submit("
                                           "'id-coverage-spatial-filetype');")

            self.get_ts_series_html()
            self.get_json_file_data_html()

        template = Template(root_div.render())
        context_dict = dict()
        temp_cov_form = self.get_temporal_coverage_form(allow_edit=False)
        spatial_cov_form = self.get_spatial_coverage_form()

        context_dict["temp_form"] = temp_cov_form
        context_dict["spatial_form"] = spatial_cov_form
        context = Context(context_dict)
        rendered_html = template.render(context)
        return rendered_html