def to_html(self, match, toc_depth=None, max_time=None, current=None): """Convert logo metadata to html stream. Parameters ---------- match: re.match object max_time: str max time for presentation Returns ------- str: html stream """ if 'toc' in self.name: return self.toc_to_html(match=match, current=current, depth=int(toc_depth)) if 'logo' in self.name: return self.logo_to_html(match) elif 'timer' in self.name: return self.timer_to_html(match=match, max_time=max_time) elif 'custom' in self.name: return self.custom_to_html(match) else: doc = Doc() with doc.tag('span', klass='metadata'): style = None if match.group('style'): style = str(match.group('style')) if style: doc.attr(style=style) if isinstance(self.value, list): doc.asis(', '.join(self.value)) else: doc.asis(str(self.value)) return doc.getvalue()
def show_xml(): pages = [ f for f in os.listdir(CACHEDIR) if os.path.isdir(os.path.join(CACHEDIR,f)) ] doc, tag, text = Doc().tagtext() doc.asis('<?xml version="1.0" encoding="utf-8" ?>') # xml tags with tag('sac_uo'): for p in pages: item = get_data_from_page('%s/latest' % p) if item: with tag('item'): with tag('id'): text(item['id']) with tag('nom'): text(item['nom']) with tag('resp'): text(item['resp']) # mini hack with tag('iddep'): text(item['iddep']) with tag('dep'): text(item['dep']) with tag('centers'): text(item['centers']) return indent( doc.getvalue(), indentation = ' ' * 4, newline = '\r\n' )
def as_junit_xml(self): """ Return Junit-format XML fragment. """ xml, tag, text = XML().tagtext() with tag('testsuite', name=self.name, hostname=self.hostname, time=(self.stop - self.start), tests=len(self._testcases), timestamp=datetime.fromtimestamp(self.start).isoformat(), errors=self.errored, failures=self.failed, skipped=self.skipped, ): if self._id is not None: xml.attr(id=self._id) with tag('properties'): for key, value in self._properties.iteritems(): xml.stag('property', name=key, value=str(value)) for testcase in self._testcases: if testcase.status is None: with tag('error'): text('Unknown outcome of this step.') else: xml.asis(testcase.as_junit_xml()) return xml.getvalue()
def as_xml(self): doc, tag, text = Doc().tagtext() doc.asis("<?xml version='1.0' encoding='UTF-8'?>") with tag('workflow-app', ('xmlns:sla', 'uri:oozie:sla:0.2'), name=self.name, xmlns="uri:oozie:workflow:0.5"): doc.stag('start', to=self.actions[0].name) for index, action in enumerate(self.actions): with tag("action", name=action.name): doc.asis(action.as_xml(indent)) if index + 1 < len(self.actions): next_action = self.actions[index+1] doc.stag("ok", to=next_action.name) else: doc.stag("ok", to="end") doc.stag("error", to="notify") with tag("action", name="notify"): with tag("email", xmlns="uri:oozie:email-action:0.1"): with tag("to"): text(self.email) with tag("subject"): text("WF ${wf:name()} failed at ${wf:lastErrorNode()}") with tag("body"): text("http://hue.data.shopify.com/oozie/list_oozie_workflow/${wf:id()}") doc.stag("ok", to="kill") doc.stag("error", to="kill") with tag("kill", name="kill"): with tag("message"): text("${wf:lastErrorNode()} - ${wf:id()}") doc.stag('end', name="end") return indent(doc.getvalue())
def handle_enumerateable(self, tag): """ Uses tags: label, number, name Add tags used manually from enumerateable_envs :param tag: :return: """ doc, html, text = Doc().tagtext() name = tag.name env_localname = self.localize(self.enumerateable_envs[name]) with html("div", klass="env env__" + name): if tag.find("label"): doc.attr(id=self.label2id(tag._label.value)) number = tag.get("number", "") with html("span", klass="env-title env-title__" + name): if tag.find("label"): with html("a", klass="env-title env-title__" + name, href="#" + self.label2id(tag._label.value)): text(join_nonempty(env_localname, number) + ".") else: text(join_nonempty(env_localname, number) + ".") doc.asis(" " + self.format(tag, blanks_to_pars= True)) return "<p>"+doc.getvalue()+"</p>\n<p>"
def handle_list(self, tag: QqTag, type): doc, html, text = Doc().tagtext() with html(type): for item in tag("item"): with html("li"): doc.asis(self.format(item)) return doc.getvalue()
def to_html(self, metadata, style=None): """Method for producing and html string of selected metadata. Parameters ---------- metadata : str metadata key style : str, optional css style of metadata tag Returns ------- str html string containing the metadata >>> source = '---metadata authors = ["S. Zaghi","J. Doe"] ---endmetadata' >>> meta = Metadata(source) >>> meta.to_html(metadata='authors') '<span class="metadata">S. Zaghi and J. Doe</span>' """ doc = Doc() if metadata == 'logo': self.put_logo(doc=doc,style=style) else: with doc.tag('span',klass='metadata'): if style: doc.attr(style=style) doc.asis(self.get_value(metadata)) return doc.getvalue()
def html_from_tree(tree): """Generate indented HTML from VOTL Object tree. Params: tree (Object): A VOTL Object containing the tree, from which HTML will be generated. Returns: String containing a pretty-formatted HTML document. """ doc, tag, text = Doc().tagtext() doc.asis("<!DOCTYPE html>") first = tree.children[0] if first.object_type == "header": title = first.first_line else: title = "Untitled" with tag("html"): with tag("head"): with tag("title"): text(title) doc.stag("meta", charset="utf-8") with tag("body"): _recurse_tags(tree, doc, tag, text) return indent(doc.getvalue())
def saveRelease(self, release): """ Create an XML file of release metadata that Dalet will be happy with :param release: Processed release metadata from MusicBrainz """ output_dir = self.release_meta_dir doc, tag, text = Doc().tagtext() doc.asis('<?xml version="1.0" encoding="UTF-8"?>') with tag('Titles'): with tag('GlossaryValue'): with tag('GlossaryType'): text('Release') with tag('Key1'): text(release.mbID) with tag('ItemCode'): text(release.mbID) with tag('KEXPReviewRich'): text(release.review) formatted_data = indent(doc.getvalue()) output_file = path.join(output_dir, 'r' + release.mbID + ".xml") with open(output_file, "wb") as f: f.write(formatted_data.encode("UTF-8"))
def __to_html(self, pmid, title, abstract, output_dir): """Generate HTML file for Anndoc Write a HTML file required for Anndoc, formatted according to TagTog's standards that can be viewed at the link below. https://github.com/jmcejuela/tagtog-doc/wiki By default, the MEDLINE identifier will be used as the title, unless something else is specified. Args: title (str): Title of the paper abstract (str): Abstract contents of the paper output_file (Optional[str]): Path to the output file. Defaults to none. """ from yattag import Doc from yattag import indent from os.path import join doc, tag, text = Doc().tagtext() # Compute hashId (TODO find out what hashing is used, currently random) hashId = self.__random_hashId(pmid) # Use Yattag to generate HTML syntax doc.asis('<!DOCTYPE html>') with tag('html', ('data-origid', pmid), ('data-anndoc-version', "2.0"), ('lang', ""), ('xml:lang', ""), ('xmlns', "http://www.w3.org/1999/xhtml"), klass='anndoc', id=hashId): with tag('head'): doc.stag('meta', charset='UTF-8') doc.stag('meta', name='generator', content='org.rostlab.relna') with tag('title'): text(hashId) with tag('body'): with tag('article'): with tag('section', ('data-type', 'title')): with tag('h2', id='s1h1'): text(title) with tag('section', ('data-type', 'abstract')): with tag('h3', id='s2h1'): text("Abstract") with tag('div', klass='content'): with tag('p', id='s2p1'): text(abstract) # Write to file result = indent(doc.getvalue()) try: with open(join(output_dir, pmid+'.html'), 'w') as fw: fw.write(result) except IOError as e: print('I/O Error({0}): {1}'.format(e.errno, e.strerror)) raise
def to_html(self, config): """Generate a html stream of the whole presentation. Parameters ---------- config : MatisseConfig MaTiSSe configuration """ doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): # doc.attr(title=self.metadata['title'].value) self.__put_html_tag_head(doc=doc, tag=tag, text=text, config=config) with tag('body', onload="resetCountdown(" + str(self.metadata['max_time'].value) + ");"): doc.attr(klass='impress-not-supported') with tag('div', id='impress'): # numbering: [local_chap, local_sec, local_subsec, local_slide] current = [0, 0, 0, 0] for chapter in self.chapters: current[0] += 1 current[1] = 0 current[2] = 0 current[3] = 0 self.metadata['chaptertitle'].update_value(value=chapter.title) self.metadata['chapternumber'].update_value(value=chapter.number) for section in chapter.sections: current[1] += 1 current[2] = 0 current[3] = 0 self.metadata['sectiontitle'].update_value(value=section.title) self.metadata['sectionnumber'].update_value(value=section.number) for subsection in section.subsections: current[2] += 1 current[3] = 0 self.metadata['subsectiontitle'].update_value(value=subsection.title) self.metadata['subsectionnumber'].update_value(value=subsection.number) for slide in subsection.slides: current[3] += 1 self.metadata['slidetitle'].update_value(value=slide.title) self.metadata['slidenumber'].update_value(value=slide.number) with doc.tag('div'): chapter.put_html_attributes(doc=doc) section.put_html_attributes(doc=doc) subsection.put_html_attributes(doc=doc) slide.put_html_attributes(doc=doc) self.__put_html_slide_decorators(tag=tag, doc=doc, decorator='header', current=current, overtheme=slide.overtheme) # with doc.tag('div'): # doc.attr(style='clear: both;') self.__put_html_slide_decorators(tag=tag, doc=doc, decorator='sidebar', position='L', current=current, overtheme=slide.overtheme) slide.to_html(doc=doc, parser=self.parser, metadata=self.metadata, theme=self.theme, current=current) self.__put_html_slide_decorators(tag=tag, doc=doc, decorator='sidebar', position='R', current=current, overtheme=slide.overtheme) # with doc.tag('div'): # doc.attr(style='clear: both;') self.__put_html_slide_decorators(tag=tag, doc=doc, decorator='footer', current=current, overtheme=slide.overtheme) self.__put_html_tags_scripts(doc=doc, tag=tag, config=config) # source = re.sub(r"<li>(?P<item>.*)</li>", r"<li><span>\g<item></span></li>", source) html = indent(doc.getvalue()) return html
def handle_paragraph(self, tag: QqTag): """ :param tag: :return: """ doc, html, text = Doc().tagtext() with html("span", klass="paragraph"): doc.asis(self.format(tag, blanks_to_pars=False).strip() + ".") return "<p>" + doc.getvalue()+" "
def as_xml(self): doc, tag, text = Doc().tagtext() doc.asis("<?xml version='1.0' encoding='UTF-8'?>") with tag('bundle-app', name=self.name, xmlns="uri:oozie:bundle:0.1"): for coordinator in self.coordinators: with tag("coordinator", name=coordinator.name): with tag("app-path"): text("/"+coordinator.path + "/" + coordinator.name) return indent(doc.getvalue())
def record_listens(request, data): """ Submit the listen in the lastfm format to be inserted in db. Accepts listens for both track.updateNowPlaying and track.scrobble methods. """ output_format = data.get('format', 'xml') try: sk, api_key = data['sk'], data['api_key'] except KeyError: raise InvalidAPIUsage(CompatError.INVALID_PARAMETERS, output_format=output_format) # Invalid parameters session = Session.load(sk) if not session: if not Token.is_valid_api_key(api_key): raise InvalidAPIUsage(CompatError.INVALID_API_KEY, output_format=output_format) # Invalid API_KEY raise InvalidAPIUsage(CompatError.INVALID_SESSION_KEY, output_format=output_format) # Invalid Session KEY lookup = defaultdict(dict) for key, value in data.items(): if key in ["sk", "token", "api_key", "method", "api_sig"]: continue matches = re.match('(.*)\[(\d+)\]', key) if matches: key = matches.group(1) number = matches.group(2) else: number = 0 lookup[number][key] = value if request.form['method'].lower() == 'track.updatenowplaying': for i, listen in lookup.items(): if 'timestamp' not in listen: listen['timestamp'] = calendar.timegm(datetime.now().utctimetuple()) # Convert to native payload then submit 'em after validation. listen_type, native_payload = _to_native_api(lookup, data['method'], output_format) for listen in native_payload: validate_listen(listen, listen_type) user = db_user.get(session.user_id) augmented_listens = insert_payload(native_payload, user, listen_type=listen_type) # With corrections than the original submitted listen. doc, tag, text = Doc().tagtext() with tag('lfm', status='ok'): if listen_type == 'playing_now': doc.asis(create_response_for_single_listen(list(lookup.values())[0], augmented_listens[0], listen_type)) else: accepted_listens = len(lookup.values()) # Currently LB accepts all the listens and ignores none with tag('scrobbles', accepted=accepted_listens, ignored='0'): for original_listen, augmented_listen in zip(list(lookup.values()), augmented_listens): doc.asis(create_response_for_single_listen(original_listen, augmented_listen, listen_type)) return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()), output_format)
def MakeHTMLHivePlot(): doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): with open ('C:/Users/s/Documents/GitHub/d3BMCR/HiveTemplate1.html','r') as scpt: doc.asis(scpt.read()) a=doc.getvalue() with open (pathPlusName,'w') as f: f.write(a) webbrowser.open(pathPlusName)
def write_raw_text_in_html(self, content, path): doc, tag, text = Doc().tagtext() with tag('html'): with tag('head'): doc.asis('<meta http-equiv="content-type" content="text/html; charset=utf-8" />') with tag('body'): doc.asis(content) result = doc.getvalue() with open("plots/" + path, "w") as file: file.write(result)
def to_html(self): """Method for inserting box to the html doc.""" doc = Doc() with doc.tag('div',klass='box'): if self.style: doc.attr(style=self.style) with doc.tag('div',klass='box content'): if self.ctn_options: doc.attr(style=self.ctn_options) doc.asis(self.ctn) self.put_caption(doc=doc) return doc.getvalue()
def as_junit_xml(self,): xml, tag, text = XML().tagtext() xml.asis('<?xml version="1.0" encoding="UTF-8"?>') with tag('testsuites', name=self.title, tests=sum(len(suite._testcases) for suite in self._suites), errors=self.errored, failures=self.failed, ): for testsuite in self._suites: xml.asis(testsuite.as_junit_xml()) return xml.getvalue()
def to_html(self): """Method for inserting box to the html doc.""" doc = Doc() with doc.tag("div", klass="box"): if self.style: doc.attr(style=self.style) if self.cap_position == "TOP": self.put_caption(doc=doc) with doc.tag("div", klass="box content"): if self.ctn_options: doc.attr(style=self.ctn_options) doc.asis(self.ctn) if self.cap_position is None or self.cap_position == "BOTTOM": self.put_caption(doc=doc) return doc.getvalue()
def set_qti_metadata(max_attempts): meta, tag, text = Doc().tagtext() meta.asis("<!-- Metadata -->") metadata = DEFAULT_QTI_META metadata['cc_maxattempts'] = max_attempts with tag('qtimetadata'): for key, value in metadata.iteritems(): with tag('qtimetadatafield'): with tag('fieldlabel'): text(key) with tag('fieldentry'): text(value) return indent(meta.getvalue())
def generateModuleHtml(data, module, outModuleDir): """ parse data from config file 'moduleX.config.json' and generate a moduleX html file """ # create magic yattag triple doc, tag, text = Doc().tagtext() doc.asis('<!-- NAVIGATION MENU -->') with tag('nav', klass="menu accordion"): with tag('h3'): text(data["title"]) with tag('ul'): generateMenuSections(data,doc,tag,text) generateMainContent(data,doc,tag,text,module, outModuleDir) writeHtml(module, outModuleDir,doc)
def to_html(self): """Method for inserting box to the html doc.""" doc = Doc() with doc.tag('div',klass='note'): if self.style: doc.attr(style=self.style) elif Note.theme.data.data['style'][0]: doc.attr(style=Note.theme.data.data['style'][0]) self.put_caption(doc=doc) with doc.tag('div',klass='note content'): if self.ctn_options: doc.attr(style=self.ctn_options) elif Note.theme.data.data['content'][0]: doc.attr(style=Note.theme.data.data['content'][0]) doc.asis(seditor.md_convert(self.ctn)) return doc.getvalue()
def to_html(self): """Convert self data to its html stream.""" doc = Doc() with doc.tag('div', id='table-' + str(self.number)): if self.style: doc.attr(style=self.style) else: doc.attr(klass='table') if self.cap_position is None or self.cap_position.upper() == 'TOP': self.put_caption(doc=doc, klass='table-caption') with doc.tag('div', klass='table-content'): if self.ctn_options: doc.attr(style=self.ctn_options) doc.asis(markdown2html(self.ctn, no_p=True)) if self.cap_position is not None and self.cap_position.upper() == 'BOTTOM': self.put_caption(doc=doc, klass='table-caption') return doc.getvalue()
def to_html(self): """Convert self data to its html stream.""" doc = Doc() with doc.tag("div", id="note-" + str(self.number)): if self.style: doc.attr(style=self.style) else: doc.attr(klass="note") if self.cap_position is None or self.cap_position.upper() == "TOP": self.put_caption(doc=doc, klass="note-caption") with doc.tag("div", klass="note-content"): if self.ctn_options: doc.attr(style=self.ctn_options) doc.asis(markdown2html(self.ctn, no_p=True)) if self.cap_position is not None and self.cap_position.upper() == "BOTTOM": self.put_caption(doc=doc, klass="note-caption") return doc.getvalue()
def to_html(self): """Convert self data to its html stream.""" if self.number > 0: doc = Doc() with doc.tag('div', klass='columns'): for col, column in enumerate(self.columns): with doc.tag('div', klass='column'): doc.attr(('column-number', str(col + 1))) style = 'display:block;float:left;' if column[1]: style += column[1] else: style += 'width:' + str(int(100.0 / self.number)) + '%;' doc.attr(style=style) doc.asis(markdown2html(source=column[0])) return doc.getvalue() return ''
def mk_toc(self, maxlevel=2, chapter = None) -> str: """ Makes TOC (Table Of Contents) :param maxlevel: maximum heading level to include to TOC (default: 2) :param chapter: if None, we assume to have whole document on the same page and TOC contains only local links. If present, it is equal to index of current chapter :return: str with HTML content of TOC """ doc, html, text = Doc().tagtext() curlevel = 1 curchapter = 0 # chapter before first h1 has index 0 with html("ul", klass="nav"): for child in self.root: chunk = [] if isinstance(child, QqTag): m = re.match(r'h(\d)', child.name) if m: hlevel = int(m.group(1)) # h1 header marks new chapter, so increase curchapter counter if hlevel == 1: curchapter += 1 if hlevel > maxlevel: continue while hlevel > curlevel: chunk.append("<li><ul class='nav'>\n") curlevel += 1 while hlevel < curlevel: chunk.append("</ul></li>\n") curlevel -= 1 targetpage = self.url_for_chapter(index=curchapter, fromindex=chapter) item_doc, item_html, item_text = Doc().tagtext() with item_html("li", klass = "toc_item toc_item_level_%i" % curlevel): with item_html("a", href=targetpage+"#"+self.tag_id(child)): item_text(self.format(child, blanks_to_pars=False)) chunk.append(item_doc.getvalue()) doc.asis("".join(chunk)) return doc.getvalue()
def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') with tag('head'): doc.stag('meta', name = 'viewport', content = 'width=device-width, initial-scale=1') with tag('title'): text('Chameleon Docker Demo') doc.stag('link', rel = 'stylesheet', href = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css') with tag('body'): with tag('div', klass = 'container-fluid'): with tag('div', klass = 'row'): with tag('div', klass = 'col-xs-12 col-md-6 col-md-offset-3'): with tag('h1', klass = 'text-center'): text('Chameleon Cloud Docker Demo') input_file = codecs.open("description.md", mode="r") doc.asis(str(markdown.markdown(input_file.read()))) input_file.close() try: with tag('div', klass = 'row'): with tag('div', klass = 'col-xs-12 col-md-2 col-md-offset-5'): with tag('div', klass = 'list-group'): conn = psycopg2.connect(host = socket.gethostbyname('postgres'), user = '******', password = '******', database = 'docker') cur = conn.cursor() cur.execute('select name from demosite') for row in cur.fetchall(): with tag('div', klass = 'list-group-item'): text(row[0]) cur.close() conn.close() except: print "Postgres error:", sys.exc_info() with tag('div', klass = 'row'): with tag('div', klass = 'col-xs-12 col-md-6 col-md-offset-3'): with tag('div', klass = 'alert alert-warning text-center', role = 'alert'): with tag('b'): text('Error!') text(' ') text('Unable to retrieve database items.') return doc.getvalue()
def parseresults(results): doc, tag, text = Doc().tagtext() listed_details = ['_id', 'bio', "distance_mi", "teaser", "common_interests", "schools"] doc.asis('<!DOCTYPE html>') with tag('html'): with tag('title'): text('Tinder Viewer') with tag('body'): for person in results: with tag('div'): with tag('h2'): text(person['name']) with tag('div'): print('{0} is {1}'.format(person['name'].encode('utf-8'), person['_id'])) for item in listed_details: text(item + ': ') try: text(bytes(json.dumps(person[item]), 'utf-8').decode('unicode-escape')) except UnicodeEncodeError: good_text = ''.join( c for c in bytes( json.dumps(person[item]), 'utf-8' ).decode('unicode-escape') if c in string.printable ) text(good_text) doc.stag('br') text('age is: ') text(calc_age(person['birth_date'])) doc.stag('br') for i in range(len(person['photos'])): address = person['photos'][i]['processedFiles'][0]['url'] doc.stag('img', src=address) doc.stag('br') if 'instagram' in person.keys() and person['instagram'] is not None: with tag('h3'): text('Instagram:') for photo in person['instagram']['photos']: with tag('a', href= photo['image'], target='_blank'): doc.stag('img', src=photo['thumbnail']) doc.stag('br') open_html(doc.getvalue())
def generate(self): """generates the report given the elements added until now""" doc, tag, text = Doc().tagtext() self.convert_plots() with tag('html'): with tag('body'): with tag('h1', id = 'report_title'): text(self.title) with tag('ul', id = 'values'): for k,v in self.variables.items(): with tag('li', id = 'values'): text(k + ": " + str(v)) for k,v in self.plots_mpld3.items(): with tag('h2'): text(k) doc.asis(v) self.report = doc.getvalue() return self.report
def as_xml(self): doc, tag, text = Doc().tagtext() doc.asis("<?xml version='1.0' encoding='UTF-8'?>") with tag("coordinator-app", xmlns="uri:oozie:coordinator:0.2", timezone="America/New_York", name=self.name, start=self.start, end=self.end, frequency=str(self.frequency)): with tag("controls"): with tag("timeout"): text("600") with tag("concurrency"): text("1") with tag("execution"): text("LAST_ONLY") with tag("throttle"): text("1") with tag("action"): with tag("workflow"): with tag("app-path"): text("/" + self.workflow.path + "/" + self.workflow.name) return indent(doc.getvalue())
def __doHtml(self, url, album_title, album_description, tmpHtml): #from yattag import Doc #from yattag import indent doc, tag, text, line = Doc().ttl() if url == '': album_title = 'Фотографии с пользователем' doc.asis( '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' ) with tag('html'): with tag('head'): with tag('title'): text(album_title) doc.asis( '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>' ) with tag('body'): with tag('h1'): text(album_title) with tag('a', target="_blank", href=url): text(url) if (album_description != ''): with tag('p'): album_description doc.asis(tmpHtml) result = indent(doc.getvalue(), indentation=' ', newline='\r\n', indent_text=True) return result
def generate_page(datatypes, lastdata, devices): doc, tag, text = Doc().tagtext() with tag('html'): with tag('head'): doc.asis( '<link rel="stylesheet" type="text/css" href="static/style.css">' ) doc.asis( '<link rel="stylesheet" type="text/css" href="static/noty.css">' ) doc.asis( '<link rel="stylesheet" type="text/css" href="static/mint.css">' ) #doc.asis('<script src="static/jquery.js"></script>') #doc.asis('<script src="static/smoothie.js"></script>') doc.asis('<script src="static/visualization.js"></script>') with tag('title'): text("EcoStatus visualization") with tag('body'): with tag('div', id='body'): with tag('div', id='devices_block'): for d in devices: with tag('h4', id='device_name_' + d): text(d) for dt in datatypes: with tag('p'): with tag('h2'): text(dt) with tag('canvas', id=dt, width="720", height="150"): pass with tag('p'): with tag('h2'): text("Current") for d in devices: with tag('h4'): text(d) with tag('b'): text(str(lastdata["current"][d])) with tag('br'): pass with tag('h2'): text("Database") for d in devices: with tag('h4'): text(d) with tag('b'): text(str(lastdata["db"][d])) with tag('br'): pass return doc.getvalue()
def featureRoleExplanation(self, id, dataname, datastructure): doc, tag, text, line = Doc().ttl() self.hideButtonId += 1 doc.asis(self.explanationTitle('Feature role', id, self.hideButtonId)) with tag('div', id=id, style="display:block"): with tag('div', klass="w3-container w3-margin-top w3-margin-bottom"): with tag('div', klass="w3-border"): with tag('div', klass="w3-white w3-padding", style="height:700px;"): line('svg', '', id="graph_%s" % id, width="700", style="height:100%;width:100%;") line( 'script', 'featureRoleGenerateGraph("graph_%s", %s)' % (id, dataname)) with tag('div', klass="w3-center w3-sand w3-padding"): doc.asis( 'Relationship diagram showing entites related to feature role' ) for key in datastructure: doc.asis( self.explanationSection( key, key.upper(), self.sectionRowFactory(datastructure[key]))) return doc.getvalue()
def handle_proof(self, tag: QqTag) -> str: """ Uses tags: proof, label, outline, of Examples: \proof Here is the proof \proof \of theorem \ref{thm:1} Now we pass to proof of theorem \ref{thm:1} :param tag: :return: HTML of proof """ doc, html, text = Doc().tagtext() with html("div", klass="env env__proof"): if tag.find("label"): doc.attr(id=self.label2id(tag._label.value)) with html("span", klass="env-title env-title__proof"): if tag.exists("outline"): proofline = 'Proof outline' else: proofline = 'Proof' doc.asis( join_nonempty( self.localize(proofline), self.format(tag.find("of"), blanks_to_pars=False)).rstrip() + ".") doc.asis(rstrip_p(" " + self.format(tag, blanks_to_pars=True))) doc.asis("<span class='end-of-proof'>∎</span>") return doc.getvalue() + "\n<p>"
def generateXML(self, name:str = 'BiologicalResultDescription') -> str: doc, tag, text, line = Doc().ttl() with tag(name): if self.__biologicalIntentName is None: raise WQXException("Attribute 'biologicalIntentName' is required.") line('BiologicalIntentName',self.__biologicalIntentName) if self.__biologicalIndividualIdentifier is not None: line('BiologicalIndividualIdentifier', self.__biologicalIndividualIdentifier) if self.__subjectTaxonomicName is None: raise WQXException("Attribute 'subjectTaxonomicName' is required.") line('SubjectTaxonomicName',self.__subjectTaxonomicName) if self.__subjectTaxonomicNameUserSupplied is not None: line('SubjectTaxonomicNameUserSupplied', self.__subjectTaxonomicNameUserSupplied) if self.__subjectTaxonomicNameUserSuppliedReferenceText is not None: line('SubjectTaxonomicNameUserSuppliedReferenceText', self.__subjectTaxonomicNameUserSuppliedReferenceText) if self.__unidentifiedSpeciesIdentifier is not None: line('UnidentifiedSpeciesIdentifier', self.__unidentifiedSpeciesIdentifier) if self.__sampleTissueAnatomyName is not None: line('SampleTissueAnatomyName', self.__sampleTissueAnatomyName) if self.__groupSummaryCount is not None: line('GroupSummaryCount', self.__groupSummaryCount) if self.__groupSummaryWeightMeasure is not None: doc.asis(self.__groupSummaryWeightMeasure.generateXML('GroupSummaryWeightMeasure')) if self.__taxonomicDetails is not None: doc.asis(self.__taxonomicDetails.generateXML('TaxonomicDetails')) if len(self.__frequencyClassInformation) > 3: raise WQXException("Attribute frequencyClassInformation must be a list of 0 to 3 FrequencyClassInformation objects.") for x in self.__frequencyClassInformation: doc.asis(x.generateXML('FrequencyClassInformation')) return doc.getvalue()
def generateHtmlHeader() -> str: """Generates the skeleton HTML file Returns ------- str A string containing the contents of the HTML file generated """ doc, tag, text, line = Doc().ttl() doc.asis('<!DOCTYPE html>') with tag('html'): if cfg.VERBOSE: print('[INFO] Generating HTML header') with tag('head'): doc.stag('meta', charset='utf-8') with tag('title'): text('') doc.stag('meta', name='description', content='An HTML file generated by the RNote compiler.') doc.stag('meta', name='author', content='RNote Compiler') if cfg.VERBOSE: print('[INFO] Generating HTML body') with tag('body'): with tag('style'): style = sty.Styler() # Temp obj. doc.asis( '@page {{size: {} {}; @frame {{top: {}cm; left: {}cm; height: {}cm; width: {}cm; -pdf-frame-border:1;}}' .format(style.pagesize, style.orientation, style.top, style.left, style.height, style.width)) doc.asis('/*EndOf@pageManualStyling*/}') del style with tag('div', id='content'): pass return doc.getvalue()
def _raw_file(self, name=None): """Build up a page for the Raw File view.""" name = name if name else '' name = name.replace('|', '/') display_name = self._get_display_name(name) if 'path' not in self.page_options: body_txt = 'No directory to serve in the config file.' else: path = os.path.join(self.path, name) body = Doc() with body.tag('h1'): body.text('File: %s' % display_name) with body.tag('div'): body.attr(klass='navigation') body.asis(self._get_navigation_links(path)) with body.tag('div'): body.attr(klass='files') if os.path.exists(path): if os.path.isdir(path): body.asis(self._get_dir_listing(path)) else: body.asis(self._get_file(path)) body_txt = body.getvalue() flash_messages = self.page_options.get('flash_messages', True) return HtmlPage(head=None, body=body_txt, flash_messages=flash_messages).render_template()
def generateXML(self, name: str = 'WellInformation') -> str: doc, tag, text, line = Doc().ttl() with tag(name): if self.__wellTypeText is None: raise WQXException("Attribute 'wellTypeText' is required.") line('WellTypeText', self.__wellTypeText) if self.__aquiferTypeName is not None: line('AquiferTypeName', self.__aquiferTypeName) if self.__nationalAquiferCode is not None: line('NationalAquiferCode', self.__nationalAquiferCode) if self.__aquiferInformation is not None: doc.asis( self.__aquiferInformation.generateXML( 'AquiferInformation')) if self.__formationTypeText is not None: line('FormationTypeText', self.__formationTypeText) if self.__wellHoleDepthMeasure is not None: doc.asis( self.__wellHoleDepthMeasure.generateXML( 'WellHoleDepthMeasure')) if self.__constructionDate is not None: line('ConstructionDate', self.__constructionDate) if self.__wellDepthMeasure is not None: doc.asis( self.__wellDepthMeasure.generateXML('WellDepthMeasure')) return doc.getvalue()
def test_get_links(): test_data = [ 'https://aff.ironsocket.com/SH7L', 'https://aff.ironsocket.com/SH7L', 'https://wsrs.net/', 'https://cmsgear.com/' ] doc, tag, _, line = Doc().ttl() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('body'): for data in test_data: line('a', 'test_anchor', href=data) mock_html = doc.getvalue() mock_soup = BeautifulSoup(mock_html, 'html.parser') with requests_mock.Mocker() as mock_connection: for data in test_data: mock_connection.register_uri('GET', data, text='Received') result = getweblinks.get_links(mock_soup, ext=['.com', '.net']) assert result == test_data
def parse(self,source,current=None): """Method for substituting $toc with its pretty printed version. Parameters ---------- source : str string (as single stream) containing the source current: list, optional list containing current section, and subsection number used for highlighting current slide into the TOC """ parsed_source = source for match in re.finditer(__retoc__,parsed_source): deep = match.group('deep') if deep: deep = int(deep) doc = Doc() with doc.tag('div',klass='toc'): doc.asis(self.pstr(html=True,current=current,deep=deep)) parsed_source = re.sub(__retoc__,doc.getvalue(),parsed_source,1) doc = None return parsed_source
def build_tmx(langpair_dict, xml_source_lang, xml_target_lang): # convert to tmx doc, tag, text = Doc().tagtext() langpair_set = langpair_dict.items() doc.asis('<?xml version="1.0" encoding="UTF-8"?>') with tag('tmx', version="1.4"): with tag('header', creationtool="cApps", creationtoolversion="2021.02", segtype="paragraph", adminlang="en", datatype="HTML", srclang=xml_source_lang): doc.attr(('o-tmf', "omt") # o_tmf="omt", ) text('') with tag('body'): for tu in langpair_set: src_txt = str(tu[0]).strip() tgt_txt = str(tu[1]).strip() if src_txt != 'nan' and \ tgt_txt != 'nan' and \ src_txt != tgt_txt: with tag('tu'): with tag('tuv'): doc.attr(('xml:lang', xml_source_lang)) with tag('seg'): text(src_txt) with tag('tuv'): doc.attr(('xml:lang', xml_target_lang)) with tag('seg'): text(tgt_txt) tmx_output = indent(doc.getvalue(), indentation=' ' * 2, newline='\r\n') return tmx_output # .replace("o_tmf=", "o-tmf=")
async def autofill_cksum(req): endpoint = 'https://www2.monroecounty.gov/elections-absentee-form' contact = await Contact.find_by_id(req.match_info['hash']) if contact is None: raise web.HTTPFound(location=endpoint) asyncio.create_task(tag_contact_with(contact, 'vote4robin_absentee')) doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') with tag('head'): with tag('title'): text(f"{contact.forename}'s Mail-in Ballot Application") with tag('script', type='text/javascript'): text(''' window.onload = function() { document.getElementById('abs-ballot-app').submit() } ''') with tag('form', method='post', action=endpoint, id='abs-ballot-app'): for key, val in contact.form_data(): doc.input(type='hidden', value=val, name=key) return web.Response(text=doc.getvalue(), content_type='text/html')
def calibration(directory, scenename): doc, tag, text = Doc().tagtext() doc.asis("<!DOCTYPE html>") PATH = "./src/pngs/" + scenename + "/orig/calibration/stereo/" positions = glob.glob(PATH + "pos*") positions.sort() with tag("html"): with tag("head"): doc.asis('<link rel="stylesheet" href="styles.css">') with tag("h1"): text(scenename) with tag("body"): with tag("h2"): text("Stereo calibration photos") with tag("div", name="table-container"): with tag("table"): with tag("tr"): for pos in positions: with tag("th"): with tag("div", name="view-container"): source = pos + "/IMG0.JPG" doc.stag("img", src=source, name="views", id=pos[-4:-1] + pos[-1]) position = 0 num_views = len(positions) with tag("table"): for pos in positions: imgs = glob.glob(pos + "/IMG*.JPG") imgs.sort() no = 0 with tag("tr"): for img in imgs: with tag("th"): with tag("div", name="thumbnail-container"): doc.stag("img", src=img, name="thumbnail", id="thumb" + str(position) + str(no), onmouseover="changeView(" + str(num_views) + "," + str(no) + ")") no = no + 1 position = position + 1 doc.asis( '<script type="text/javascript" src="master.js"></script>') HTML = doc.getvalue() filename = scenename + "-calib.html" file = open(filename, "w") file.write(HTML) file.close() return filename
def main(): questions, answers = [], [] load_cards('a.csv', answers) load_cards('q.csv', questions) tasks = { "answers-back": partial(generate_back, isQuestions=False), "answers-front": partial(generate_front_answers, answers=answers), "questions-back": partial(generate_back, isQuestions=True), "questions-front": partial(generate_front_questions, questions=questions) } for key in tasks: doc = Doc() doc.asis('<!DOCTYPE html>') with doc.tag('html'): with doc.tag('head'): doc.asis('<link rel="stylesheet" href="style.css"/>') with doc.tag('body'): tasks[key](doc=doc) with open('design/index.html', 'w+', encoding='utf-8') as f: f.write(doc.getvalue()) pdfkit.from_file('design\\index.html', f'{key}.pdf', options={ '--zoom': 1.24, '--margin-bottom': '0', '--margin-top': '0', '--margin-left': '0', '--margin-right': '0', '--enable-local-file-access': None, '--page-width': '60mm', '--page-height': '90mm', '--encoding': 'utf-8' })
def create_help_sheet(self, numbers, range_text): """Create helper sheet for resource. Args: numbers: Numbers used for activity (list). range_text: String describing range of numbers (str). Returns: Pillow image object (Image). """ doc, tag, text, line = Doc().ttl() with tag("div"): with tag("h1"): text("Teacher guide sheet for binary search activity") with tag("p"): text( "Use this sheet to circle the number you are asking your class ", "to look for when you are demonstrating how the binary search ", "works. This allows you to demonstrate the maximum number of ", "searches it would take. When students are playing the treasure ", "hunt game, they can choose any number. Avoid those numbers that are ", "underlined as they are key binary search positions (avoiding them is a ", "good thing to do for demonstrations, but in practice students, ", "or computers, won’t intentionally avoid these).") with tag("h2"): text("Sorted numbers") with tag("p"): # doc.attr(style="columns:2;") numbers.sort() red_number_jump = (len(numbers) + 1) // 4 text = "" for (index, number) in enumerate(numbers): if (index + 1) % red_number_jump == 0: text += "<u>{}</u> - ".format(number) else: text += "{} - ".format(number) text = text[:-3] doc.asis(text) return doc.getvalue()
def save(self, path, inner=False): os.makedirs(path, exist_ok=True) doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('head'): with tag('title'): text(self.title or 'Text') with tag('body'): with tag('h1'): text(self.title or 'Text') with tag('div'): for t in self.texts: with tag('div', style='width: {}px; float: left'.format(self.width)): with tag('pre'): text(t) file = open('{}/page.htm'.format(path), 'w', encoding='utf-8') file.write(indent(doc.getvalue())) file.close()
def to_html(self): """Method for inserting columns to the html doc.""" if self.number > 0: doc = Doc() with doc.tag('div', klass='columns'): for col, column in enumerate(self.columns): with doc.tag('div', klass='column'): doc.attr(('column-number', str(col + 1))) style = 'display:block;float:left;' if column[1]: style += column[1] else: style += 'width:' + str(int( 100.0 / self.number)) + '%;' doc.attr(style=style) content = box_parse(column[0]) content = figure_parse(content) content = table_parse(content) content = note_parse(content) doc.asis(seditor.md_convert(content)) return doc.getvalue() return ''
def get_multiple_systems_html_report(orig_sents, sys_sents_list, refs_sents, system_names, test_set, lowercase, tokenizer, metrics): doc = Doc() doc.asis('<!doctype html>') with doc.tag('html', lang='en'): doc.asis(get_head_html()) with doc.tag('body', klass='container-fluid m-2 mb-5'): doc.line('h1', 'EASSE report', klass='mt-4') with doc.tag('a', klass='btn btn-link', href='https://forms.gle/J8KVkJsqYe8GvYW46'): doc.text('Any feedback welcome!') doc.stag('hr') doc.line('h2', 'Test set') doc.stag('hr') with doc.tag('div', klass='container-fluid'): doc.asis( get_test_set_description_html( test_set=test_set, orig_sents=orig_sents, refs_sents=refs_sents, )) doc.line('h2', 'Scores') doc.stag('hr') with doc.tag('div', klass='container-fluid'): doc.line('h3', 'System vs. Reference') doc.stag('hr') doc.asis( get_score_table_html_multiple_systems( orig_sents, sys_sents_list, refs_sents, system_names, lowercase, tokenizer, metrics)) doc.line('h2', 'Qualitative evaluation') doc.stag('hr') with doc.tag('div', klass='container-fluid'): doc.asis( get_multiple_systems_qualitative_examples_html( orig_sents, sys_sents_list, refs_sents, system_names)) return indent(doc.getvalue())
def get_test_set_description_html(test_set, orig_sents, refs_sents): doc = Doc() test_set = test_set.capitalize() doc.line('h4', test_set) orig_sents = np.array(orig_sents) refs_sents = np.array(refs_sents) df = pd.DataFrame() df.loc[test_set, '# of samples'] = str(len(orig_sents)) df.loc[test_set, '# of references'] = str(len(refs_sents)) df.loc[test_set, 'Words / source'] = np.average( np.vectorize(count_words)(orig_sents)) df.loc[test_set, 'Words / reference'] = np.average( np.vectorize(count_words)(refs_sents.flatten())) def modified_count_sentences(sent): return max(count_sentences(sent), 1) orig_sent_counts = np.vectorize(modified_count_sentences)(orig_sents) expanded_orig_sent_counts = np.expand_dims(orig_sent_counts, 0).repeat(len(refs_sents), axis=0) refs_sent_counts = np.vectorize(modified_count_sentences)(refs_sents) ratio = np.average((expanded_orig_sent_counts == 1) & (refs_sent_counts == 1)) df.loc[test_set, '1-to-1 alignments*'] = f'{ratio*100:.1f}%' ratio = np.average((expanded_orig_sent_counts == 1) & (refs_sent_counts > 1)) df.loc[test_set, '1-to-N alignments*'] = f'{ratio*100:.1f}%' ratio = np.average((expanded_orig_sent_counts > 1) & (refs_sent_counts > 1)) df.loc[test_set, 'N-to-N alignments*'] = f'{ratio*100:.1f}%' ratio = np.average((expanded_orig_sent_counts > 1) & (refs_sent_counts == 1)) df.loc[test_set, 'N-to-1 alignments*'] = f'{ratio*100:.1f}%' doc.asis(get_table_html_from_dataframe(df.round(2))) doc.line('p', klass='text-muted', text_content='* Alignment detection is not 100% accurate') return doc.getvalue()
def get_xml(self, threshold=0): """ Return NSRR XML of all predictions :param threshold: Threshold of yolo's confidence. Discards confidence lower than threshold if thresholds is set. :return: string of XML """ doc, tag, text = Doc().tagtext() doc.asis('<?xml version="1.0" encoding="UTF-8" standalone="no"?>') with tag('PSGAnnotation'): with tag('SoftwareVersion'): text("Compumedics") with tag('EpochLength'): text("30") with tag("ScoredEvents"): start = 0 for i, confidence in enumerate(self.predictions): if start != 0: if confidence == 0: end = i with tag("ScoredEvent"): with tag("EventType"): text("Respiratory|Respiratory") with tag("EventConcept"): text("Obstructive apnea|ObstructiveApnea") with tag("Start"): text(start) with tag("Duration"): text(end - start) with tag("SignalLocation"): text("ABDO RES") start = 0 elif confidence > threshold: start = i result = indent(doc.getvalue(), indentation=' ' * 4, newline='\r\n') return result
def generate_index(json_data): info("Generating Index.html file") doc, tag, text, line = Doc().ttl() doc.asis('<!DOCTYPE html>') with tag('html'): doc.asis(generators.generate_header('FAQ')) with tag('body'): with tag('div', klass='wrapper'): doc.asis(generate_index_menu(json_data)) doc.asis(generators.generate_js_imports()) with open(os.path.dirname(__file__) + '/../index.html', "w") as index_file: index_file.write(indent(doc.getvalue()))
def generateXML(self, name: str = 'ProjectMonitoringLocationWeighting') -> str: doc, tag, text, line = Doc().ttl() with tag(name): if self.__monitoringLocationIdentifier is None: raise WQXException( "Attribute 'monitoringLocationIdentifier' is required.") line('MonitoringLocationIdentifier', self.__monitoringLocationIdentifier) if self.__locationWeightingFactorMeasure is None: raise WQXException("Attribute 'measureCompact' is required.") doc.asis( self.__locationWeightingFactorMeasure.generateXML( 'LocationWeightingFactorMeasure')) if self.__statisticalStratumText is not None: line('StatisticalStratumText', self.__statisticalStratumText) if self.__locationCategoryName is not None: line('LocationCategoryName', self.__locationCategoryName) if self.__locationStatusName is not None: line('LocationStatusName', self.__locationStatusName) if self.__referenceLocationTypeCode is not None: line('ReferenceLocationTypeCode', self.__referenceLocationTypeCode) if self.__referenceLocationStartDate is not None: line('ReferenceLocationStartDate', self.__referenceLocationStartDate) if self.__referenceLocationEndDate is not None: line('ReferenceLocationEndDate', self.__referenceLocationEndDate) if self.__referenceLocationCitation is not None: doc.asis( self.__referenceLocationCitation.generateXML( 'ReferenceLocationCitation')) if self.__commentText is not None: line('CommentText', self.__commentText) return doc.getvalue()
def get_catalog_html_text(catalog_node): global message_config_local catalog_html_resource_root_path = environment_config_local[ 'output_catalog_html_resource']['root_path'] catalog_style_path = catalog_html_resource_root_path + environment_config_local[ 'data_catalog_html_resource']['css_file_name'] catalog_script_path = catalog_html_resource_root_path + environment_config_local[ 'output_catalog_html_resource']['js_file_name'] doc, tag, text = Doc().tagtext() doc.asis("<!DOCTYPE html>") with tag("html", lang=_get_html_language()): # Head & Meta with tag("head"): doc.stag("meta", charset="utf-8") # Title with tag("title"): text(catalog_node.catalog_name + message_config_local['html_catalog']['title']) # CSS doc.stag("link", rel="stylesheet", href=catalog_style_path) # JavaScript with tag("script", src=catalog_script_path): text("") # Body & onLoad method with tag("body", onLoad="catalogOnLoad()"): # Catalog scope with tag("div", klass="catalog"): # Root unordered list with tag("ul", klass="catalog_root_ul"): _process_catalog_node(catalog_node, doc, tag, text) return doc.getvalue()
def generate_contact(self): f = self.generate(i18n.t('menu.contact')) i18n.load_path.append('./translations') i18n.set('locale', self.meta.lang) i18n.set('fallback', 'en') doc, tag, text = Doc().tagtext() with tag('div', klass='contact'): with tag('h2', klass='contact__title'): text(i18n.t('menu.contact')) with tag('span', klass='contact__message'): text(i18n.t('contact.intro') + '!') with tag('span', klass='contact__phone'): text( i18n.t('contact.phone', opening_hour=self.meta.author.available_from, closing_hour=self.meta.author.available_until) + ':') with tag('a', href=f'tel:{self.meta.author.phone}', klass='contact__phone__link'): doc.asis('<i class="fas fa-phone"></i>') with tag('span', klass='contact__mail'): text(i18n.t('contact.mail') + ':') with tag( 'a', href=f'mailto:{self.meta.author.mail}?subject=contact', klass='contact__mail__link'): doc.asis('<i class="far fa-paper-plane"></i>') return self.close_html(f + indent(doc.getvalue()))
def test_multiple_errors_multuple_locations(self): doc, tag, text = Doc().tagtext() doc.asis('<?xml version="1.0" encoding="UTF-8"?>') with tag("results", version="2"): with tag("cppcheck", version="testVersion"): pass with tag("errors"): for i in range(10): with tag( "error", id="testId" + str(i), verbose="testMessage" + str(i)): for j in range(10): with tag( "location", file="/test/file" + str(j), line=j, info="info" + str(j)): pass parser = CppcheckXmlV2Parser() results = parser.load(BytesIO(b(doc.getvalue()))) assert len(results) == 10 for i in range(10): diag = results[i] assert diag.tool_info.name == "cppcheck" assert diag.tool_info.version == "testVersion" assert diag.kind == "testId" + str(i) assert diag.message.location.path == "/test/file0" assert diag.message.location.line_start == 0 assert diag.message.text == "testMessage" + str(i) assert len(diag.additional_messages) == 10 for j in range(10): message = diag.additional_messages[j] assert message.location.path == "/test/file" + str(j) assert message.location.line_start == j assert message.text == "info" + str(j)
def generate_tile(md_file_link: {}): doc, tag, text = Doc().tagtext() excerpt = md_file_link['excerpt'] parser = MastaParse() parser.feed(excerpt) missing_tag = parser.get_missing_closing_tag() if missing_tag: excerpt = f'{excerpt[:-len(missing_tag)]} {missing_tag}' if '<' in excerpt[-4:]: excerpt = excerpt[:-4] with tag('div', klass='excerpts__item'): with tag('a', href=f"{md_file_link['link']}", klass='excerpts__item__link'): doc.asis(md_file_link['title']) doc.asis(excerpt) return indent(doc.getvalue())
def generateXML(self, name: str = 'IndexType') -> str: doc, tag, text, line = Doc().ttl() with tag(name): if self.__indexTypeIdentifier is None: raise WQXException( "Attribute 'indexTypeIdentifier' is required.") line('IndexTypeIdentifier', self.__indexTypeIdentifier) if self.__indexTypeIdentifierContext is None: raise WQXException( "Attribute 'indexTypeIdentifierContext' is required.") line('IndexTypeIdentifierContext', self.__indexTypeIdentifierContext) if self.__indexTypeName is None: raise WQXException("Attribute 'indexTypeName' is required.") line('IndexTypeName', self.__indexTypeName) if self.__indexTypeCitation is not None: doc.asis( self.__indexTypeCitation.generateXML('IndexTypeCitation')) if self.__indexTypeScaleText is not None: line('IndexTypeScaleText', self.__indexTypeScaleText) return doc.getvalue()
def to_html_doc(title, items, image_base_path, image_width, image_height): doc, tag, text = Doc().tagtext() with tag('html'): with tag('head'): with tag('style'): doc.asis( f'img {{max-width:{image_width}px;max-height:{image_height}px;width:auto;height:auto;}}' ) with tag('body'): with tag('h1'): text(title) for year, year_items in ordered_dict_sorted_by_key( groupby(lambda item: item['year'], items)).items(): with tag('h3'): text(f'{year}') for item in year_items: with tag('img', src=image_base_path + '/' + item['image_id'] + '.jpg?authuser=1', height=f'{image_height}', width=f'{image_width}'): text('') return doc
def generate_html(self,title): doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('title'): text(title) with tag('body'): with tag('h3'): text(title) with tag('ol', id='sermon list'): for index,post in enumerate(self.posts): with tag('li', number=index, id='sermon post'): with tag('p'): with tag('a', href=post['blog_url']): text('[Blog]') # doc.asis(' | ') # with tag('a', href=post['audio_url']+'?dl=1'): # text('[Download Audio]') text(' Title: {}'.format(post['title'])) doc.asis('<audio controls src={} type="audio/mpeg"/>'.format(post['audio_url'])) doc.stag('hr') return doc.getvalue()
def custom_to_html(self, match): """Convert custom metadata to html stream. Parameters ---------- match: re.match object Returns ------- str: html stream """ doc = Doc() with doc.tag('span', klass='metadata'): style = None if match.group('style'): style = str(match.group('style')) if style: doc.attr(style=style) doc.asis( re.search(r'value\:(?P<value>.*?)\;', style).group('value')) return doc.getvalue()