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")
Exemplo n.º 2
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()
Exemplo n.º 3
0
def formatWeek(week):
    hr()
    for day in week.days:
        formatDay(day)
        hr()
    # week number
    number = u"Week {}".format(week.number)
    div(number, cls="week-number")
Exemplo n.º 4
0
def generateHtml():
    with open(path.join(current_dir, '../changelog/', 'storage.json'),
              'r') as f:
        data = json.load(f)[::-1]

    doc = document(title='Changelog - lkellar.org')

    articles = []

    with doc.head:
        tags.link(rel='stylesheet', href='style.css')
        tags.meta(charset="UTF-8")
        tags.meta(name="description",
                  content="A log of all changes made on lkellar.org")
        tags.meta(name="viewport",
                  content="width=device-width, initial-scale=1")
        tags.link(rel="alternate",
                  title="Changelog Feed",
                  type="application/json",
                  href="https://lkellar.org/changelog/feed.json")

    with doc:
        with tags.nav().add(tags.ol()):
            with tags.li():
                tags.a("Home", href="../")
            tags.li("Changelog")

        with tags.main():
            tags.h1('Changelog')
            for entry in data:
                tags.hr()
                article_content = tags.article()

                with article_content:
                    tags.h2(
                        f'{entry["title"]} - {entry["date"].split("T")[0]}',
                        id=f'{entry["title"]} - {entry["date"]}'.replace(
                            ' ', ''.lower()))

                    list_content = tags.ul()
                    with list_content:
                        for line in entry['items']:
                            line = urls.sub(r'<a href="\2">\1</a>', line)
                            tags.li(raw(line))

                articles.append((f'{entry["title"]} - {entry["date"]}'.replace(
                    ' ', ''.lower()), list_content.render(), entry["date"],
                                 entry['title']))

    with open(path.join(current_dir, '../changelog/', 'index.html'), 'w') as f:
        f.write(doc.render())

    generateFeed(articles)
Exemplo n.º 5
0
def _render_exchanges(exchanges, trashcan):
    # The ``hr`` elements really help readability in w3m.
    H.hr()
    for exch in exchanges:
        div = H.div(_class=u'exchange')
        with div:
            if exch.request:
                _render_request(exch.request)
                H.hr()
            for resp in exch.responses:
                _render_response(resp)
                H.hr()
            if exch.complaints:
                _render_complaints(exch)
                H.hr()

        # Some exchanges are "complaint boxes", carrying only a complaint.
        # If the user silences that complaint, we end up with an empty box.
        # To avoid adding it to our document, we preemptively add it
        # to a dummy "trash can" element, per Dominate docs:
        #
        #   When the context is closed, any nodes that were not already
        #   added to something get added to the current context.
        #
        if len(div) == 0:
            trashcan.add(div)
Exemplo n.º 6
0
def _header(test_name, expected_hash, actual_hash):
    h1(test_name)
    with div():
        if actual_hash == expected_hash:
            p(
                "This test succeeded on UI comparison.",
                style="color: green; font-weight: bold;",
            )
        else:
            p(
                "This test failed on UI comparison.",
                style="color: red; font-weight: bold;",
            )
        p("Expected: ", expected_hash)
        p("Actual: ", actual_hash)
    hr()
Exemplo n.º 7
0
 def gen_goal(self, goal, toggle=None):
     """Serialize a goal to HTML."""
     with tags.blockquote(cls="alectryon-goal"):
         if goal.hypotheses:
             # Chrome doesn't support the ‘gap’ property in flex containers,
             # so properly spacing hypotheses requires giving them margins
             # and giving negative margins to their container.  This breaks
             # when the container is empty, so just omit the hypotheses if
             # there are none.
             self.gen_hyps(goal.hypotheses)
         toggle = goal.hypotheses and toggle
         cls = "goal-separator" + (" alectryon-extra-goal-label"
                                   if toggle else "")
         with self.gen_label(toggle, cls):
             tags.hr()
             if goal.name:
                 tags.span(goal.name, cls="goal-name")
         tags.div(self.highlight(goal.conclusion), cls="goal-conclusion")
def added(screens_path, test_name):
    doc = dominate.document(title=test_name)
    screens = sorted(screens_path.iterdir())

    with doc:
        h1(test_name)
        p(
            "This UI test has been added to fixtures.json.",
            style="color: green; font-weight: bold;",
        )
        hr()

        with table(border=1):
            with tr():
                th("Added files")

            for screen in screens:
                with tr():
                    html.image(screen)

    return html.write(REPORTS_PATH / "added", doc, test_name + ".html")
Exemplo n.º 9
0
    def add_summary(self, dict_):
        """ Add a summary with key value pairs from the dictionary """

        self.doc += br()
        self.doc += hr()
        self.doc += br()
        self.add_header("Test Summary")
        self.doc += br()

        for k, v in dict_.items():
            self.doc += p(b(k), ' = ', str(v))
            self.doc += br()
Exemplo n.º 10
0
def index():
    removed = list((REPORTS_PATH / "removed").iterdir())
    added = list((REPORTS_PATH / "added").iterdir())
    diff = list((REPORTS_PATH / "diff").iterdir())

    title = "UI changes from master"
    doc = dominate.document(title=title)

    with doc:
        h1("UI changes from master")
        hr()

        h2("Removed:", style="color: red;")
        i("UI fixtures that have been removed:")
        html.report_links(removed, REPORTS_PATH)
        br()
        hr()

        h2("Added:", style="color: green;")
        i("UI fixtures that have been added:")
        html.report_links(added, REPORTS_PATH)
        br()
        hr()

        h2("Differs:", style="color: grey;")
        i("UI fixtures that have been modified:")
        html.report_links(diff, REPORTS_PATH)

    return html.write(REPORTS_PATH, doc, "index.html")
Exemplo n.º 11
0
def index() -> Path:
    passed_tests = list((REPORTS_PATH / "passed").iterdir())
    failed_tests = list((REPORTS_PATH / "failed").iterdir())

    title = "UI Test report " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    doc = document(title=title, index=True)

    with doc:
        h1("UI Test report")
        if not failed_tests:
            p("All tests succeeded!", style="color: green; font-weight: bold;")
        else:
            p("Some tests failed!", style="color: red; font-weight: bold;")
        hr()

        h2("Failed", style="color: red;")
        with p(id="file-hint"):
            strong("Tip:")
            text(" use ")
            t.span("./tests/show_results.sh", style="font-family: monospace")
            text(" to enable smart features.")

        with div("Test colors", _class="script-hidden"):
            with t.ul():
                with t.li():
                    t.span("new", style="color: blue")
                    t.button("clear all", onclick="resetState('all')")
                with t.li():
                    t.span("marked OK", style="color: grey")
                    t.button("clear", onclick="resetState('ok')")
                with t.li():
                    t.span("marked BAD", style="color: darkred")
                    t.button("clear", onclick="resetState('bad')")

        html.report_links(failed_tests, REPORTS_PATH, ACTUAL_HASHES)

        h2("Passed", style="color: green;")
        html.report_links(passed_tests, REPORTS_PATH)

    return html.write(REPORTS_PATH, doc, "index.html")
Exemplo n.º 12
0
def _render_exchanges(exchanges):
    H.hr()
    for exch in exchanges:
        with H.div(_class=u'exchange'):
            # The ``hr`` elements really help readability in w3m.
            if exch.request:
                _render_request(exch.request)
                H.hr()
            for resp in exch.responses:
                _render_response(resp)
                H.hr()
            if exch.complaints:
                _render_complaints(exch)
                H.hr()
Exemplo n.º 13
0
def _render_exchanges(exchanges):
    # The ``hr`` elements really help readability in w3m.
    H.hr()
    for exch in exchanges:
        with H.div(_class=u'exchange'):
            if exch.request:
                _render_request(exch.request)
                H.hr()
            for resp in exch.responses:
                _render_response(resp)
                H.hr()
            if exch.complaints:
                _render_complaints(exch)
                H.hr()
Exemplo n.º 14
0
def index():
    passed_tests = list((REPORTS_PATH / "passed").iterdir())
    failed_tests = list((REPORTS_PATH / "failed").iterdir())

    title = "UI Test report " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    doc = dominate.document(title=title)

    with doc:
        h1("UI Test report")
        if not failed_tests:
            p("All tests succeeded!", style="color: green; font-weight: bold;")
        else:
            p("Some tests failed!", style="color: red; font-weight: bold;")
        hr()

        h2("Failed", style="color: red;")
        html.report_links(failed_tests, REPORTS_PATH)

        h2("Passed", style="color: green;")
        html.report_links(passed_tests, REPORTS_PATH)

    return html.write(REPORTS_PATH, doc, "index.html")
Exemplo n.º 15
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    # We don't want to hold the entire report in memory before printing it,
    # because that would mean unbounded memory growth with more input.
    # But Dominate obviously doesn't have a streaming mode, so we do this
    # manually. We create our document, but instead of the actual exchanges,
    # we insert a separator string that allows us to split it into a prologue
    # and an epilogue.
    separator = u'---- CUT HERE ----'

    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        H.hr()
        text_node(separator)

    (prologue, epilogue) = document.render().split(separator)

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
Exemplo n.º 16
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    # We don't want to hold the entire report in memory before printing it,
    # because that would mean unbounded memory growth with more input.
    # But Dominate obviously doesn't have a streaming mode, so we do this
    # manually. We create our document, but instead of the actual exchanges,
    # we insert a separator string that allows us to split it into a prologue
    # and an epilogue.
    separator = u'---- CUT HERE ----'

    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        H.hr()
        text_node(separator)

    (prologue, epilogue) = document.render().split(separator)

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
Exemplo n.º 17
0
    def get_html(self):
        """overrides the base class function"""

        html_string = super(GenericFileMetaDataMixin, self).get_html()
        if not self.has_metadata:
            no_metadata_message = div(id="#fb-metadata-default", cls="text-center text-muted",
                                      role="alert")
            with no_metadata_message:
                div("No file level metadata exists for the selected file.")
                hr()
                i_tag = i(cls="fa fa-eye-slash fa-2x")
                i_tag['aria-hidden'] = 'true'
            html_string = no_metadata_message.render()
        else:
            if self.temporal_coverage:
                html_string += self.temporal_coverage.get_html()

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

        template = Template(html_string)
        context = Context({})
        return template.render(context)
Exemplo n.º 18
0
    def get_html(self):
        """overrides the base class function"""

        html_string = super(GenericFileMetaDataMixin, self).get_html()
        if not self.has_metadata:
            no_metadata_message = div(id="#fb-metadata-default",
                                      cls="text-center text-muted",
                                      role="alert")
            with no_metadata_message:
                div("No file level metadata exists for the selected file.")
                hr()
                i_tag = i(cls="fa fa-eye-slash fa-2x")
                i_tag['aria-hidden'] = 'true'
            html_string = no_metadata_message.render()
        else:
            if self.temporal_coverage:
                html_string += self.temporal_coverage.get_html()

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

        template = Template(html_string)
        context = Context({})
        return template.render(context)
Exemplo n.º 19
0
def _generate_exchange_divs(exchanges):
    for exch in exchanges:
        div = H.div(_class=u'exchange')
        with div:
            if exch.request:
                _render_request(exch.request)
                # The ``hr`` elements really help readability in w3m.
                H.hr()
            for resp in exch.responses:
                _render_response(resp)
                H.hr()
            if exch.complaints:
                _render_complaints(exch)
                H.hr()

        # Some exchanges are "complaint boxes", carrying only a complaint.
        # If the user silences that complaint, we end up with an empty box.
        if len(div) != 0:   # pylint: disable=len-as-condition
            yield div
Exemplo n.º 20
0
def _generate_exchange_divs(exchanges):
    for exch in exchanges:
        div = H.div(_class=u'exchange')
        with div:
            if exch.request:
                _render_request(exch.request)
                # The ``hr`` elements really help readability in w3m.
                H.hr()
            for resp in exch.responses:
                _render_response(resp)
                H.hr()
            if exch.complaints:
                _render_complaints(exch)
                H.hr()

        # Some exchanges are "complaint boxes", carrying only a complaint.
        # If the user silences that complaint, we end up with an empty box.
        if len(div) != 0:  # pylint: disable=len-as-condition
            yield div
Exemplo n.º 21
0
    def add_image_with_text(self, visuals, aspect_ratio=1.0, width=256):
        """ Add images along with textual metadata """

        image_dir = self.get_image_dir()

        visuals['image'] = visuals['image'][0]
        self.add_header(visuals['image'])

        pred = util.tensor2im(visuals['Predicted'])
        image_name = visuals['image']

        save_path = os.path.join(image_dir, 'pred_' + image_name)
        util.save_image(pred, save_path, aspect_ratio=aspect_ratio)

        t = table(
            border=1,
            style="table-layout: fixed; width: 1200px;")  # Insert a table
        self.doc.add(t)
        with t:
            with tr():
                with td(style="word-wrap: break-word;",
                        halign="center",
                        valign="top"):
                    with p():
                        hr()
                        p(b('ImageID: '), visuals['image'])
                        br()
                        #### Add image and feature maps ####
                        with figure(style="display: inline-block;"):
                            img(style=
                                "border:0px;margin:0px;float:left;width:%dpx;"
                                % width,
                                src=os.path.relpath(
                                    os.path.join(visuals['low_path'],
                                                 visuals['image']),
                                    self.web_dir))
                            figcaption('Low-Light',
                                       style="text-align: center;")
                        with figure(style="display: inline-block;"):
                            img(style=
                                "border:0px;margin:0px;float:left;width:%dpx;"
                                % width,
                                src=os.path.join('images',
                                                 'pred_' + visuals['image']))
                            figcaption('Prediction',
                                       style="text-align: center;")
                        with figure(style="display: inline-block;"):
                            img(style=
                                "border:0px;margin:0px;float:left;width:%dpx;"
                                % width,
                                src=os.path.relpath(
                                    os.path.join(visuals['target_path'],
                                                 visuals['image']),
                                    self.web_dir))
                            figcaption('Ground Truth',
                                       style="text-align: center;")
                        #### Add image and feature maps ####
                        br()
                        # Add a table for class probabilities
                        for k, v in visuals['metrics'].items():
                            p("{} = {}".format(k, float(v)))
                            br()
Exemplo n.º 22
0
def render_attn_to_html(data_imgs, captions, ixtoword,
                        attn_maps, att_sze, lr_imgs=None,
                        batch_size=cfg.TRAIN.BATCH_SIZE,
                        max_word_num=cfg.TEXT.WORDS_NUM, info = ['Real Images'], nvis = 8, v_sigma = 20):
    html_doc = dominate.document(title='Attention Visualization')
    with html_doc:
        T.hr()
        T.h1('Attention Sample')

    if type(data_imgs) is not list:
        # to maintain API.
        data_imgs = [data_imgs]
    
    ndataimgs = len(data_imgs) 

    processed_data_imgs = []
    for data_img in data_imgs:
        data_img = data_img[:nvis]
        if att_sze == 17:
            vis_size = att_sze * 16
        else:
            vis_size = data_img.size(2)
        
        data_img = nn.Upsample(size=(vis_size, vis_size), mode='bilinear')(data_img)
        # [-1, 1] --> [0, 1]
        data_img.add_(1).div_(2).mul_(255)
        data_img = data_img.data.numpy()
        # b x c x h x w --> b x h x w x c
        data_img = np.transpose(data_img, (0, 2, 3, 1))
        pad_sze = data_img.shape
        processed_data_imgs.append(data_img)

    seq_len = max_word_num
    img_set = []
    
    for i in range(nvis):
        attn = attn_maps[i].cpu().view(1, -1, att_sze, att_sze)
        # --> 1 x 1 x 17 x 17
        attn_max = attn.max(dim=1, keepdim=True)
        attn = torch.cat([attn_max[0], attn], 1)
        #
        attn = attn.view(-1, 1, att_sze, att_sze)
        attn = attn.repeat(1, 3, 1, 1).data.numpy()
        # n x c x h x w --> n x h x w x c
        attn = np.transpose(attn, (0, 2, 3, 1))
        num_attn = attn.shape[0]
        #
        imgs = [ imgs[i] for imgs in processed_data_imgs ]
        row_beforeNorm = []; minVglobal, maxVglobal = 1, 0
        row_merged = [ Image.fromarray(np.uint8(img)) for img in imgs ]
        row_pure_attn = [ Image.fromarray(np.zeros(img.shape, dtype = np.uint8))\
                          for img in imgs]
        for j in range(num_attn):
            one_map = attn[j]
            if (vis_size // att_sze) > 1:
                one_map = skimage.transform.pyramid_expand(one_map, sigma=v_sigma, upscale=vis_size // att_sze)
            row_beforeNorm.append(one_map)
            minV = one_map.min()
            maxV = one_map.max()
            if minVglobal > minV:
                minVglobal = minV
            if maxVglobal < maxV:
                maxVglobal = maxV
        for j in range(num_attn):
            one_map = row_beforeNorm[j]
            one_map = (one_map - minVglobal) / (maxVglobal - minVglobal)
            one_map *= 255
            #
            PIL_im = Image.fromarray(np.uint8(img))
            PIL_att = Image.fromarray(np.uint8(one_map))
            merged = Image.new('RGBA', (vis_size, vis_size), (0, 0, 0, 0))
            mask = Image.new('L', (vis_size, vis_size), (210))
            merged.paste(PIL_im, (0, 0))
            merged.paste(PIL_att, (0, 0), mask)
            row_pure_attn.append(PIL_att)
            row_merged.append(merged)

        with html_doc:
            T.hr()
            T.h2('%d-th Image:' % i)
            for nthimg, (pil_att, pil_img) in enumerate(zip(row_pure_attn, row_merged)):
                if nthimg < ndataimgs:
                    if len(info) == ndataimgs:
                        T.p(info[nthimg])
                    else:
                        T.p('Data Images')
                elif nthimg == ndataimgs:
                    T.p("Attention map maximized across time:")
                else:
                    cap = captions[i][nthimg - (ndataimgs + 1)].cpu().data.numpy()
                    cap = ' '.join([ixtoword[w] for w in cap])
                    cap = cap.replace('<end>','')
                    T.p(cap)

                attn_b64 = render_PIL_image_b64(pil_att)
                T.img(src="data:;base64,{0}".format(attn_b64))
                image_b64 = render_PIL_image_b64(pil_img)
                T.img(src="data:;base64,{0}".format(image_b64))
    return html_doc
Exemplo n.º 23
0
 def add_hr(self):
     with self.doc:
         hr()
Exemplo n.º 24
0
    def __init__(self, config):
        self.config = config

        env = jinja2.Environment(
                  loader=jinja2.FileSystemLoader(self.config['templates_dir']),
                  trim_blocks=True)
        self.script = env.get_template(self.config['js_file']).render(**self.config)

        self.document = dominate.document(title=self.config['project_name'])
        self.document['lang'] = 'en'

        self.images = []
        for image_file in os.listdir(self.config['images_dir']):
            dir_image_file = os.path.join(self.config['images_dir'], image_file)
            if os.path.isfile(dir_image_file):
                src = '{}/{}'.format(self.config['images_route'], image_file)
                alt = os.path.splitext(
                          image_file.capitalize()
                              .replace('-', ' ')
                              .replace('_', ' '))[0]
                self.images.append((src, alt))
        self.images.sort(key=lambda x: x[1])

        with self.document.head:
            tags.meta(charset='utf-8')
            tags.meta(
                name='viewport',
                content='width=device-width, initial-scale=1, shrink-to-fit=no')
            # Bootstrap CSS.
            tags.link(
                rel='stylesheet',
                href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
                integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T',
                crossorigin='anonymous')
            # Fonts.
            tags.link(
                rel='stylesheet',
                href='https://fonts.googleapis.com/css?family=Dancing+Script&display=swap')

        with self.document:
            self.noscript()

            with tags.script():
                util.text(self.script, escape=False)

            with tags.div(id='root'):
                with tags.div(cls='container'):
                    with tags.div(cls='row mb-3 mt-3'):
                        with tags.div(cls='col'):

                            with tags.div(cls='card'):
                                with tags.div(cls='card-body'):
                                    with tags.h1(cls='display-5', style="font-family: 'Dancing Script', cursive;"):
                                        with tags.span(cls='text-capitalize'):
                                            util.text(self.config['project_name'])

                                    with tags.p(cls='lead'):
                                        util.text('Use machine learning to classify flowers! The ')
                                        tags.a('fast.ai library', href='https://docs.fast.ai')
                                        util.text(' was used to ')
                                        tags.a('train', href='https://github.com/nkaretnikov/resnet-flowers')
                                        util.text(' a ')
                                        tags.a('residual', href='https://arxiv.org/pdf/1512.03385.pdf')
                                        util.text(' ')
                                        tags.a('neural network', href='http://cs231n.github.io/convolutional-networks')
                                        util.text(' on the ')
                                        tags.a('Flower Color Images', href='https://www.kaggle.com/olgabelitskaya/flower-color-images')
                                        util.text(' dataset to recognize the classes below.')

                                    tags.hr(cls='my-4')

                                    with tags.div(cls='container'):
                                        with tags.div(cls='row mb-1'):
                                            for src, alt in self.images:
                                                with tags.div(cls='col-6 col-sm-4 col-md-3 col-lg-2'):
                                                    self.image(src=src, alt=alt)

                    with tags.div(cls='row mb-1'):
                        with tags.div(cls='col-md-9 col-lg-7 col-xl-6'):
                            self.upload_form()

                    with tags.div(cls='row mb-3'):
                        with tags.div(cls='col-md-9 col-lg-7 col-xl-6'):
                            self.url_form()

            # Optional JavaScript for Bootstrap.
            tags.script(
                src='https://code.jquery.com/jquery-3.3.1.slim.min.js',
                integrity='sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo',
                crossorigin='anonymous')
            tags.script(
                src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',
                integrity='sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1',
                crossorigin='anonymous')
            tags.script(
                src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js',
                integrity='sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM',
                crossorigin='anonymous')

            # Show the filename when using 'custom-file'.
            tags.script(
                src='https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.min.js',
                integrity='sha384-wbycNUwFmhRaoqw8zOxtEdIA5kWW1MUAV4bXEfNNOk0e5HmG3AaNRvOHFjWNAAQb',
                crossorigin='anonymous')
            with tags.script():
                util.text('$(document).ready(function () { bsCustomFileInput.init() })')
Exemplo n.º 25
0
 def visit_Separator(self, node):
     return tags.hr(_class='separator')
Exemplo n.º 26
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()
Exemplo n.º 27
0
 def visit_Separator(self, node):
     return tags.hr(_class='separator')
Exemplo n.º 28
0
def formatDays(days):
	with div(cls="days"):
		hr()
		for day in days:
			formatDay(day)
			hr()
Exemplo n.º 29
0
def hr():
    """horizontal rule"""
    return HTML(str(dt.hr()))
Exemplo n.º 30
0
def _generate_html_email_body(title: str, new_songs: Iterable[Track],
                              playlist: PlayList) -> str:
    link_style = 'color: #373737;'

    # Generate links to the artists
    artists_spans = []
    for track in new_songs:
        artists = []
        for artist in track['track']['artists']:
            name = artist['name']
            url = '#'
            if ('external_urls' in artist
                    and 'spotify' in artist['external_urls']):
                url = artist['external_urls']['spotify']
                artists.append(a(name, href=url, style=link_style))
            else:
                artists.append(name)
        first = True
        artists_span = span()
        for artist_entry in artists:
            if not first:
                artists_span += ', '
            artists_span += artist_entry
            first = False
        artists_spans.append(artists_span)

    # Generate document
    doc = dominate.document(title=title)
    with doc:
        with div(style=('font-family: arial, serif;border: 1px solid #99ff99; '
                        'padding: 3px; width: 600px; margin: auto; '
                        'background-color: #99ff99;')):
            with table():
                with tr():
                    with td():
                        with a(href=playlist['external_urls']['spotify']):
                            img(src=playlist['images'][0]['url'],
                                width='200px',
                                height='200px')
                    with td(style=('vertical-align: text-top; '
                                   'padding-left: 10px;')):
                        div('New music was added to',
                            style='text-align: center;')
                        with h2():
                            a(playlist['name'],
                              href=playlist['external_urls']['spotify'],
                              style=link_style)
                        h3(playlist['description'],
                           style='text-align: center;')
            hr(size='1', color='black', width='90%')
            div('The following tracks where added:',
                style='margin-top: 10px; margin-bottom: 10px;')

            for track, artists_span in zip(new_songs, artists_spans):
                with table(style=('border: 1px solid black; width:100%; '
                                  'margin-bottom: 10px; font-size: 14px;')):
                    with td(width='100px;', style='width: 100px;'):
                        a(img(src=track['track']['album']['images'][2]['url']),
                          href=track['track']['external_urls']['spotify'])
                    with td():
                        with table():
                            with tr():
                                td('Artist(s):',
                                   style=('text-align: right; '
                                          'padding-right: 5px;'))
                                td(artists_span)
                            with tr():
                                td('Title:',
                                   style='text-align: right; '
                                   'padding-right: 5px;')
                                td(
                                    a(track['track']['name'],
                                      href=track['track']['external_urls']
                                      ['spotify'],
                                      style=link_style))
                            with tr():
                                td('Album:',
                                   style='text-align: right; '
                                   'padding-right: 5px;')
                                td(
                                    a(track['track']['album']['name'],
                                      href=track['track']['album']
                                      ['external_urls']['spotify'],
                                      style=link_style))

    return doc.render(pretty=False)
Exemplo n.º 31
0
def process():
    #   doc = dominate.document(DOCNAME)

    h = html(name=DOCNAME)

    with h:

        #           _head = head()

        _head = head()
        with _head:
            s = style()
            s.add("\nh3, h4 {text-align:center;}")
            s.add("\nth {background-color:yellow;}")
            s.add("\ntr, td, th {text-align:center;}")
            s.add("\ntd.left {text-align:left;}")
            s.add("\n")

        b = body()

        b.add(h3(DOCNAME))
        b.add(h4(asctime()))
        b.add(hr())

        t = table(border="1", cellpadding="3", cellspacing="3")
        b.add(t)

        r = tr()
        t.add(r)

        r.add(th("Code"))
        r.add(th("Waypoint"))
        r.add(th("Image"))
        r.add(th("Note"))

        f = open(FILENAME, "r")

        for index, line in enumerate(f.readlines()):
            if index == 0:
                continue

            code, waypoint_name, url = line.split('\t')

            r = tr()
            t.add(r)

            r.add(td(code))
            r.add(td(a(waypoint_name, href=url)))

            if code in IMAGES:
                link = IMAGES[code]
                if isinstance(link, type([])):
                    images = table()
                    for link in link:
                        r2 = tr()
                        r2.add(td(a(link, href=link)))
                        images.add(r2)
                else:
                    images = a(link, href=link)
            else:
                images = ""
            r.add(td(images))

            if code in NOTES:
                note = NOTES[code]
            else:
                note = "TBD"
            r.add(td(note, cls="left"))

    outfile = open(OUTFILE, "wb")
    print >> outfile, h
    outfile.close()
    print "Output is in %s" % OUTFILE