def handle_h(self, tag: QqTag) -> str: """ Uses tags: h1, h2, h3, h4, label, number Example: \h1 This is first header \h2 This is the second header \label{sec:second} :param tag: :return: """ doc, html, text = Doc().tagtext() with html(tag.name): doc.attr(id=self.tag_id(tag)) if tag.find("number"): with html("span", klass="section__number"): with html("a", href="#"+self.tag_id(tag), klass="section__number"): text(tag._number.value) text(self.format(tag, blanks_to_pars=False)) ret = doc.getvalue() if tag.next() and isinstance(tag.next(), str): ret += "<p>" return doc.getvalue()
def as_junit_xml(self): xml, tag, text = XML().tagtext() with tag('testcase', name=self.name, time=(self.stop - self.start)): if self.classname is not None: xml.attr(classname=self.classname) if self.assertions is not None: xml.attr(assertions=self.assertions) with tag('properties'): for key, value in self._properties.iteritems(): xml.stag('property', name=key, value=str(value)) if self.status == 'error': with tag('error', message=self._msg): text(self._msg) elif self.status == 'failure': with tag('failure', message=self._msg): text(self._msg) elif self.status == 'skipped': xml.stag('skipped', message=self._msg) if self.stdout is None: xml.stag('system-out') else: with tag('system-out'): text(str(self.stdout)) if self.stderr is None: xml.stag('system-err') else: with tag('system-err'): text(str(self.stderr)) return xml.getvalue()
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 test_list_jobs(self): project_name = 'test_project' jobs = [ {'name': 'job 1', 'id': '1', 'project': project_name, 'description': 'job 1 description'}] doc, tag, text = Doc().tagtext() with tag('jobs', count=len(jobs)): for job in jobs: with tag('job'): with tag('name'): text(job['name']) with tag('project'): text(job['project']) with tag('description'): text(job['description']) responses.add(responses.GET, 'http://rundeck.host/api/11/jobs?project=test_project', match_querystring=True, body=self.rundeck_success(doc.getvalue()), content_type='text/xml', status=200) project_jobs = self.rundeck_api.list_jobs(project_name) self.assertEquals(len(project_jobs), len(jobs)) self.assertEquals(project_jobs[0]['name'], jobs[0]['name'])
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 process_dump_file(self, p): add_event = 0 main_doc, main_tag, main_text = Doc().tagtext() for line in iter(p.stdout.readline, b''): # Compares first with timestamp regex. Timestamp regex indicates a new packet m = reg_timestamp.match(line.decode()) if m: # add_event indicates if there is a processed event already if add_event == 1: events.append(event) self.add_event_to_html(event, main_doc, main_tag, main_text) add_event = 1 event = Event(m.group('timestamp'), m.group('protocol')) m = reg_ip_1.search(line.decode()) if m: event.id = m.group('id') event.t_protocol = m.group('transport_protocol') event.length = m.group('length') else: m = reg_ip_2.search(line.decode()) if m: event.src = m.group('src') event.src_port = m.group('src_port') event.dst = m.group('dst') event.dst_port = m.group('dst_port') m = reg_length.search(line.decode()) # If TCP data is not 0, the packet gets further processing if m and m.group('length') != 0: length = int(m.group('length')) self.process_host(event, length) # If there is a port unreachable error, event gets discarded m = reg_port_error.search(line.decode()) if m: add_event = 0 return indent(main_doc.getvalue())
def as_xml(self, indentation=False): doc, tag, text = Doc().tagtext() with tag('shell', xmlns="uri:oozie:shell-action:0.2"): #do we actually need these even if we dont use them? with tag('job-tracker'): text(os.environ["JOBTRACKER"]) with tag('name-node'): text(os.environ["NAMENODE"]) with tag('exec'): text(self.command) for argument in self.arguments: with tag('argument'): text(argument) for env in self.environment_vars: with tag('env-var'): text(env) for archive in self.archives: with tag('archive'): text(archive) for f in self.files: with tag('file'): text(f) xml = doc.getvalue() if indentation: return indent(xml) else: return xml
def now_playing(request, data): sk = data['sk'] session = Session.load(sk) if not session: print "Invalid session" return "NOPE" track = data['track'] artist = data['artist'] album = data['album'] albumArtist = data['albumArtist'] print "NOW PLAYING- User: %s, Artist: %s, Track: %s, Album: %s" \ % (session.user.name, artist, track, album) doc, tag, text = Doc().tagtext() with tag('lfm', status="ok"): with tag('nowplaying'): with tag('track', corrected="0"): text(track) with tag('artist', corrected="0"): text(artist) with tag('album', corrected="0"): text(album) with tag('albumArtist', corrected="0"): text(albumArtist) with tag('ignoredMessage', code="0"): text('') return '<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue())
def getSession(request, data): token = Token.load(data['token']) if not token: print "Invalid token" return "NOPE" if not token.user: print "Token not validated" return "NOPE" print "GRANTING SESSION for token %s" % token.token token.consume() session = Session.create(token.user) doc, tag, text = Doc().tagtext() with tag('lfm', status="ok"): with tag('session'): with tag('name'): text(session.user.name) with tag('key'): text(session.id) with tag('subscriber'): text('0') return '<?xml version="1.0" encoding="utf-8"?>\n' + yattag.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 print_subsection(section,subsection,html=False,current=None): """Method for printing subsection data. Parameters ---------- section: list section data subsection: list subsection data html: bool, optional activate html tags current: list, optional list containing current section, subsection and slide number used for highlighting current slide into the TOC Returns ------- str string containing the pretty printed subsection data """ if html: doc, tag, text = Doc().tagtext() with tag('a',href='#slide-'+str(subsection[4])): if current and current[0] == section[0] and current[1] == subsection[0]: with tag('span',klass='toc-subsection emph'): text(' '+str(section[0])+'.'+str(subsection[3])+' '+subsection[1]) else: with tag('span',klass='toc-subsection'): text(' '+str(section[0])+'.'+str(subsection[3])+' '+subsection[1]) string = '\n'+doc.getvalue() else: string = '\n'+' '+str(section[0])+'.'+str(subsection[3])+' '+subsection[1] return string
def serve_pre(content): doc, tag, text = Doc().tagtext() with tag('html'): with tag('head'): with tag('script', src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"): pass with tag('script', src="http://code.jquery.com/jquery-migrate-3.0.0.js"): pass with tag('script', src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"): pass with tag('script'): doc.asis( ''' $('.zone').on('mouseover mouseout', function(e) { $(this).toggleClass('hovering', e.type === 'mouseover'); e.stopPropagation(); }); ''' ) with tag('style'): doc.asis( ''' .zone.hovering {color: orange; font-weight: bold; background-color: gray; cursor: pointer;}; .zone {color: black}; ''' ) with tag('body'): with tag('pre'): doc.asis(content) 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 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 _repr_html_(self): doc, tag, txt = Doc().tagtext() with tag("div", klass="tree-node tree-leaf"): self._label_html(doc) with tag("span", klass="tree-text"): txt(self.text) return doc.getvalue()
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 media_player(request, media_src=''): doc, tag, text = Doc().tagtext() types = {'video':'V', 'audio':'A'} requested_type = media_src.split('/')[0] media_servers = MediaServer.objects.filter(media_type=types[requested_type]) image_src = '' next_path = '' if len(media_src.split('/')) >= 2: requested_server = media_src.split('/')[1] else: requested_server = '' for server in media_servers: if server.name == requested_server: media_src = server.server_url + media_src[len(requested_type + '/' + requested_server):] parent_dir = server.directory_path + os.path.split(media_src)[0][len(server.server_url):] plist = sorted(os.listdir(parent_dir)) media_path = server.directory_path + media_src[len(server.server_url):] media_base = os.path.basename(media_path) for item in os.listdir(parent_dir): if os.path.splitext(item)[1].lower() in ['.jpg','.png']: image_src = os.path.join(os.path.split(media_src)[0],item) if len(plist)-1 > plist.index(media_base): next_path = urlpath(server, os.path.join(parent_dir, plist[plist.index(media_base)+1])) display_directory(server.directory_path, server, doc) ml = media_src.split('/') context = { 'medialisting':doc.getvalue(), 'mediasource':media_src, 'mediatype':requested_type, 'imagesource':image_src, 'heading':os.path.splitext(ml[len(ml)-1])[0], 'nextmedia': next_path, } return render(request, 'media_player/media_player.html', context)
def environment_begin_end(env, label=None, number=None, optional=None): if env == "document": return '<html><meta charset="UTF-8">' + mathjax_snipped, "</html>\n" doc, tag, text = Doc().tagtext() stop_sign = "!!!chahpieXeiDu3zeer3Ki" if env == "itemize" or env == "enumerate": with tag(list_envs[env]): text(stop_sign) else: with tag("div", klass="env_" + mk_safe_css_ident(env)): if label: doc.attr(id="label_" + mk_safe_css_ident(label)) if env in named_envs: with tag("span", klass="env__name"): text(named_envs[env]) text(" ") if number: with tag("span", klass="env__number"): text(number) text(" ") if optional: with tag("span", klass="env__opt_text"): text(optional) text(stop_sign) ret = doc.getvalue() index = ret.index(stop_sign) begin = ret[:index] + "\n" end = ret[index + len(stop_sign) :] + "\n" return (begin, end)
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 timer_to_html(self, match, max_time): """Convert custom metadata to html stream. Parameters ---------- match: re.match object max_time: str Returns ------- str: html stream """ doc = Doc() with doc.tag('span', klass='timercontainer'): style = None if match.group('style'): style = str(match.group('style')) if style: doc.attr(style=style) with doc.tag('div', klass='countDown'): with doc.tag('div'): doc.attr(klass='timer') if style: if 'controls' in style: with doc.tag('div', klass='timercontrols'): with doc.tag('input', type='button'): doc.attr(klass='btn reset', onclick='resetCountdown(' + str(max_time) + ');', value=' ⟳ ', title='reset') with doc.tag('input', type='button'): doc.attr(klass='btn stop', onclick='stopCountdown();', value=' ◼ ', title='pause') with doc.tag('input', type='button'): doc.attr(klass='btn start', onclick='startCountdown();', value=' ▶ ', title='start') return doc.getvalue().replace('amp;', '')
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 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 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 submit(self, bund, files=[]): hdfs = PyWebHdfsClient(host=os.environ["WEBHDFS_HOST"], port='14000', user_name='oozie') for f in files: hdfs.create_file("{}/{}".format(bund.path, f.name), f.read()) doc, tag, text = Doc().tagtext() with tag("configuration"): with tag("property"): with tag("name"): text("user.name") with tag("value"): text("oozie") with tag("property"): with tag("name"): text("oozie.bundle.application.path") with tag("value"): text("/"+bund.path + "/" + bund.name) configuration = doc.getvalue() response = post("{0}/oozie/v1/jobs".format(self.url), data=configuration, headers={'Content-Type': 'application/xml'}) if response.status_code > 399: print response.headers["oozie-error-message"] print response.status_code print response.content
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 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 test_input_no_slash(self): doc = Doc(stag_end = '>') doc.input('passw', type="password") self.assertTrue( doc.getvalue() in ( '<input name="passw" type="password">', '<input type="password" name="passw">' ) )
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 make_html(article, entities, path_to_html): doc, tag, text = Doc().tagtext() with tag('html'): with tag('head'): with tag('meta'): doc.attr(charset='utf-8') with tag('title'): text('Marking of article') with tag('body'): with tag('table'): doc.attr(border='2') with tag('tr'): with tag('th'): doc.attr(style='padding: 10px;font-size:160%') with tag('p'): doc.attr(style='word-spacing:20px;font-style:italic;') with tag('font'): if(color2 != '#000000'): doc.attr(color=color2) text(' Organisation ') with tag('font'): if(color3 != '#000000'): doc.attr(color=color3) text(' PopulatedPlace ') with tag('font'): if(color1 != '#000000'): doc.attr(color=color1) text(' Person ') with tag('pre'): doc.attr(style='white-space: pre-wrap') with tag('p'): doc.attr(style='width:3000px;font-size:160%') k = 0 for d in entities.items(): #print article[d[0]: d[1][0]] if (article[k: d[0]] == ' '): text(' ') else: text(article[k: d[0]]) with tag('font'): if(d[1][1]!='#000000'): doc.attr(color=d[1][1]) with tag('b'): text(article[d[0]: d[1][0]]) k = d[1][0] else: text(article[d[0]: d[1][0]]) k = d[1][0] text(article[k:]) result = ((doc.getvalue())) #print(result) Html_file = open(path_to_html, 'w+') Html_file.write(result) Html_file.close()
def home_page(): doc, tag, text, line = Doc().ttl() with tag('html'): with tag('head'): with tag('title'): text('Oh My Py') with tag('style'): doc.asis('body{background-color: #ffb300; font-family:"Trebuchet MS", Helvetica, sans-serif;} ' 'h1{color: blue; font-variant: small-caps;} ' '#header{width: 80%; horizontal-align: center;} ' 'div{margin: 0 auto; width: 80%; text-align: center;} ' 'button{margin: 10px; width: 70%; height: 50px; text-align: center; box-shadow: 0px 1px 0px 0px #f0f7fa; border-radius:6px; display:inline-block; cursor:pointer; font-size:15px; font-weight:bold; text-decoration:none;} ' 'button:hover {background:linear-gradient(to bottom, #019ad2 5%, #33bdef 100%); background-color:#019ad2;} ' '#button1:active,#button2:active {position:relative; top:1px;} ' '#button1{margin: 10px; width: 70%; height: 50px; text-align: center; box-shadow: 0px 1px 0px 0px #f0f7fa; border-radius:6px; display:inline-block; cursor:pointer; font-size:15px; font-weight:bold; text-decoration:none; color: black; line-height: 40px;} ' '#button1:hover{background:linear-gradient(to bottom, #019ad2 5%, #33bdef 100%); background-color:#019ad2;} ' '#button1:active {position:relative; top:1px;} ' '#button1{background:linear-gradient(to bottom, #89c403 5%, #77a809 100%); background-color:#89c403; border:1px solid #74b807;} ' '#button1:hover {background:linear-gradient(to bottom, #77a809 5%, #89c403 100%); background-color:#77a809;} ' '#button2:active,#button2:active {position:relative; top:1px;} ' '#button2{margin: 10px; width: 70%; height: 50px; text-align: center; box-shadow: 0px 1px 0px 0px #f0f7fa; border-radius:6px; display:inline-block; cursor:pointer; font-size:15px; font-weight:bold; text-decoration:none; color: black; line-height: 40px;} ' '#button2:hover{background:linear-gradient(to bottom, #019ad2 5%, #33bdef 100%); background-color:#019ad2;} ' '#button2:active {position:relative; top:1px;} ' '#button2{background:linear-gradient(to bottom, #89c403 5%, #77a809 100%); background-color:#89c403; border:1px solid #74b807;} ' '#button2:hover {background:linear-gradient(to bottom, #77a809 5%, #89c403 100%); background-color:#77a809;} ' '#button2{background:linear-gradient(to bottom, #3d94f6 5%, #1e62d0 100%); background-color:#3d94f6; border:1px solid #337fed;} ' '#button2:hover {background:linear-gradient(to bottom, #1e62d0 5%, #3d94f6 100%); background-color:#1e62d0;} ' '#button3{background:linear-gradient(to bottom, #ffec64 5%, #ffab23 100%); background-color:#ffec64; border:1px solid #ffaa22;} ' '#button3:hover {background:linear-gradient(to bottom, #ffab23 5%, #ffec64 100%); background-color:#ffab23;} ' '#test{display: none;} ' '#hide{display: none;} ' 'a { text-decoration: none; color: black;} ' '#more_info{display: none;}' '#display_info{font-size:10px; font-weight:normal; text-align: justify;}' '#button3:active + #more_info {display: block;} ' '.alert { padding: 20px; background-color: #f44336; color: white;} .closebtn { margin-left: 15px; color: white; font-weight: bold; float: right; font-size: 22px; line-height: 20px; cursor: pointer; transition: 0.3s;} .closebtn:hover { color: black;}' '') with tag('div', id='container'): with tag('div', id='photo-container'): doc.stag('img', src='https://raw.githubusercontent.com/remeeliz/ohmypy/master/header.JPG', id="header") return doc.getvalue()
def func(self, threat_model): doc, tag, text, line = Doc().ttl() doc.asis("<!DOCTYPE html>") with tag('html', lang='en'): with tag('head'): line('title', 'Threat Model report') doc.asis( '<meta name="viewport" content="width=device-width, initial-scale=1">' ) doc.asis( '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">' ) doc.asis( '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>' ) doc.asis( '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>' ) with tag('body'): with tag('div', klass='container'): line('h2', 'Threat model') line('h2', threat_model.save_file) line('h2', 'Report') #Assets #table: Asset name | Description #Architecture #Architectural Diagram #link to diagram #Technologies #table: Technology name | Description | Attribute key - value | # | | Attribute key - value | #Decomposition #Data flow diagram #Entry points #Threats result = indent(doc.getvalue()) return result
def generate_packets_html(self): doc, tag, text = Doc().tagtext() with tag('h1'): text('Packets transferred from each host') for host in hosts: total_received = 0 with tag('div', klass="col-4"): with tag('h2'): text(host.ip) for src_host in host.hosts: total_from_host = 0 with tag('h4'): text('Packets received from {}'.format(src_host.ip)) for protocol in src_host.protocols: with tag('h4'): text('Protocol: {}'.format(protocol.name)) max_size = 0 min_size = -1 amount = len(protocol.packets) for packet in protocol.packets: if packet.size > max_size: max_size = packet.size if packet.size < min_size or min_size == -1: min_size = packet.size total_received += amount total_from_host += amount with tag('p'): text('Packets: {}'.format(amount)) with tag('p'): text('Minimum size packet: {}'.format( self.sizeof_fmt(min_size))) with tag('p'): text('Maximum size packet: {}'.format( self.sizeof_fmt(max_size))) with tag('p'): with tag('strong'): text('Total from {}: {} packets'.format( src_host.ip, total_from_host)) with tag('p'): text('--------------') with tag('p'): text('Total Received: {}'.format(total_received)) with tag('div', style="clear:both"): text('') return indent(doc.getvalue())
class HtmlCreator: def __init__(self, file, data=None): # Create header, body and write the whole content to html file. self.filestream = file self.data = data self.initDocTagText() def initDocTagText(self): """ Create main yattag variables. This method can be overridden. """ self.doc, self.tag, self.text = Doc().tagtext() def create_html(self): """ Create a html file from header and body content. Next, write html content to the hard drive. This method cannot be overridden. """ # Add html content to the self.doc self.doc.asis('<!DOCTYPE html>') with self.tag('html'): self.design_header() self.design_body() # Write html content from self.doc with codecs.open(self.filestream.name, 'w', 'utf-8') as f: html_content = indent(self.doc.getvalue(), indentation=' ', newline='\r\n') f.write(html_content) def design_header(self): """ Create a header for your html file here. This method should be overridden. """ pass def design_body(self): """ Create a body for your html file here. This method should be overridden. """ pass
def generateTable(html: str, head: [str], rows: [str]) -> str: """Generates a table to insert into the document Parameters ---------- html HTML document that will get the new table head Header row of the new table rows Body rows of the new table Returns ------- str The HTML document with the new table """ doc, tag, text, line = Doc().ttl() # Generate table header with tag('table'): if cfg.VERBOSE: print('[INFO] Generating table header') with tag('tr'): for i in head: with tag('th'): doc.asis(i.strip()) # Generate content in table if cfg.VERBOSE: print('[INFO] Generating table rows') for r in rows: with tag('tr'): r = r.split(';') with tag('td'): doc.asis(r[0][2:]) for s in r[1:]: with tag('td'): doc.asis(s.strip()) # Insert table into doc if cfg.VERBOSE: print('[INFO] Inserting table') upper, lower = html.split('</div></body>', 1)[0], html.split('</div></body>', 1)[1] return upper + doc.getvalue() + '</div></body>' + lower
def result_list(results): doc, tag, text = Doc().tagtext() max_length = 100 current_length = 0 with tag("tb"): for level_id, rank in results: current_length += 1 if current_length >= max_length: break with tag("tr"): level = Level.levels[level_id] url = "../../../levels/{}/".format(level.level_id) with tag("td"): with tag("a",href=url): text(level.display_name, ": ") with tag("td"): text(util.format_place(rank)) return doc.getvalue()
def template(html, root=None): if root: css_url = "\"{}/style.css\"".format(root) else: css_url = "\"./style.css\"" doc, tag, text = Doc().tagtext() doc.asis("<!DOCTYPE html>") with tag("html"): with tag("head"): doc.asis("<link rel=\"stylesheet\" href={}>".format(css_url)) doc.asis("<meta charset=\"utf-8\">") doc.asis("<link href=\"https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono\" rel=\"stylesheet\">") with tag("body"): with tag("div", klass="container"): doc.asis(html) return(doc.getvalue())
def generateXML(self, name: str = 'AlternateMonitoringLocationIdentity') -> 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.__monitoringLocationIdentifierContext is None: raise WQXException( "Attribute 'MonitoringLocationIdentifierContext' is required." ) line('MonitoringLocationIdentifierContext', self.__monitoringLocationIdentifierContext) return doc.getvalue()
def reportCommitText(notes, date, klass=''): 'Generate commit text portion of report.' doc, tag, text = Doc().tagtext() klass_text = 'title' if klass: klass_text = klass_text + ' ' + klass with tag('div', klass=klass): with tag('span', klass='title'): if len(notes) > 2: text(notes[1]) with tag('span', klass='float-right'): text(date.isoformat()) with tag('div', klass='notes ' + klass): with tag('pre'): if len(notes) > 2: for note in notes[2:]: text(note + '\n') return doc.getvalue()
def writeResults(figures): doc, tag, text = Doc().tagtext() # Generate HTML with tag('html'): with tag('head'): with tag('script', src="https://cdn.plot.ly/plotly-latest.min.js"): pass with tag('title'): text('Product Analysis') with tag('body'): for fig in figures: with tag('div'): text(fig) result = doc.getvalue() f = open("results.html", "w") f.write(html.unescape(result)) f.close()
def handle_eq(self, tag: QqTag) -> str: """ eq tag corresponds to \[ \] or $$ $$ display formula without number. Example: \eq x^2 + y^2 = z^2 :param tag: :return: """ doc, html, text = Doc().tagtext() with html("div", klass="latex_eq"): text("\\[\n") text(self.format(tag, blanks_to_pars=False)) text("\\]\n") return doc.getvalue()
def xml_format(title, id_wiki, page_content, links): doc, tag, text = Doc().tagtext() with tag('page'): with tag('id'): text(id_wiki) with tag('title'): text(title) with tag('text'): text(page_content) with tag('links'): for l in links: with tag('link'): text(l.encode('utf-8')) result = indent(doc.getvalue()) return result
def generateXML(self, name: str = 'DataQuality') -> str: doc, tag, text, line = Doc().ttl() with tag(name): if self.__precisionValue is not None: line('PrecisionValue', self.__precisionValue) if self.__biasValue is not None: line('BiasValue', self.__biasValue) if self.__confidenceIntervalValue is not None: line('ConfidenceIntervalValue', self.__confidenceIntervalValue) if self.__upperConfidenceLimitValue is not None: line('UpperConfidenceLimitValue', self.__upperConfidenceLimitValue) if self.__lowerConfidenceLimitValue is not None: line('LowerConfidenceLimitValue', self.__lowerConfidenceLimitValue) return doc.getvalue()
def make_html(md: str) -> str: lines = md.splitlines() content_start_line = lines[1:].index('---') + 2 title = yaml.safe_load('\n'.join(lines[1:content_start_line - 1]))\ .get('title') md_code = markdown.markdown('\n'.join(lines[content_start_line:]), extensions=['extra', 'toc']) doc, tag, text, line = Doc().ttl() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('head'): line('title', title or 'No Title') doc.asis('<meta charset="utf-8">') doc.asis('<base href="../assets/">') line('style', resources.read_text(res, 'content.css')) with tag('body', klass="body"): doc.asis(md_code) return doc.getvalue()
def setup_html(test_links, *, fail=False): """ Sets up test html containing links Args: test_links (list): list of links to be used for tests Return: test HTML value """ doc, tag, _, line = Doc().ttl() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('body'): for data in test_links: if not fail: line('a', 'test_anchor', href=data) return doc.getvalue()
def pGlobalHelp(): global globalHelp doc, tag, text = Doc().tagtext() with tag('h2'): text('Personality Servers: Personalities for NPCs and PCs') with tag('p'): text('Returns a simple personality use in RPG characters.') with tag('blockquote'): text('Get help: ') formatting.link(tag, text, '%s/p/help' % baseUrl) doc.stag('br') text('Try it: ') formatting.link(tag, text, '%s/p/1000words/3?format=json' % baseUrl) doc.stag('br') text('Or try this: ') formatting.link(tag, text, '%s/p/100words/3?format=html' % baseUrl) globalHelp += doc.getvalue()
def write_standing_history_html(self): 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(self.stats["top10perday"][0]) doc.asis("<br />") doc.asis("<br />") text("Page generated at %s" % datetime.now().strftime("%T the %F")) result = doc.getvalue() with open(self.plots_dir + "standinghistory.html", "w") as file: file.write(result)
def write_all_plots_html(self): 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'): for _, plot in self.plots.items(): doc.asis(plot[0]) doc.asis("<br />") text("Page generated at %s" % datetime.now().strftime("%T the %F")) result = doc.getvalue() with open(self.plots_dir + "allplots.html", "w") as file: file.write(result)
def Write(self, room, phone, workers,): global k k += 1 doc, tag, text = Doc().tagtext() with tag('position'+str(k), room=room, phone=phone, workers=workers): text(str(k)) result = indent( doc.getvalue(), indentation=' ' * 4, newline='\r\n') filename = 'data.xml' myfile = open(filename, 'a') myfile.write(result) myfile.write("\n") myfile.close() print(result)
def __str__(self): hold = {} doc, _, text, line = Doc().ttl() with _('html'): with _('header'): if len(self.var) + len(self.local) > 0: with _('script'): for k, v in self.var.items(): doc.asis('var ' + k + ' = ' + json.dumps(v) + ';') for k, v in self.local.items(): v.add(doc) self.header(doc, _, text, line) with _('body'): self.body(doc, _, text, line) result = doc.getvalue() for k, v in hold.items(): globals()[k] = v return result
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 generateXML(self, name: str = 'FrequencyClassInformation') -> str: doc, tag, text, line = Doc().ttl() with tag(name): if self.__frequencyClassDescriptorCode is None: raise WQXException( "Attribute 'frequencyClassDescriptorCode' is required.") line('FrequencyClassDescriptorCode', self.__frequencyClassDescriptorCode) if self.__frequencyClassDescriptorUnitCode is not None: line('FrequencyClassDescriptorUnitCode', self.__frequencyClassDescriptorUnitCode) if self.__lowerClassBoundValue is not None: line('LowerClassBoundValue', self.__lowerClassBoundValue) if self.__upperClassBoundValue is not None: line('UpperClassBoundValue', self.__upperClassBoundValue) return doc.getvalue()
def generateXML(self, name:str = 'LabSamplePreparation') -> str: doc, tag, text, line = Doc().ttl() with tag(name): if self.__labSamplePreparationMethod is not None: doc.asis(self.__labSamplePreparationMethod.generateXML('LabSamplePreparationMethod')) if self.__preparationStartDate is not None: line('PreparationStartDate', self.__preparationStartDate) if self.__preparationStartTime is not None: doc.asis(self.__preparationStartTime.generateXML('PreparationStartTime')) if self.__preparationEndDate is not None: line('PreparationEndDate', self.__preparationEndDate) if self.__preparationEndTime is not None: doc.asis(self.__preparationEndTime.generateXML('PreparationEndTime')) if self.__substanceDilutionFactor is not None: line('SubstanceDilutionFactor', self.__substanceDilutionFactor) return doc.getvalue()
def ac_source(width=64, height=64): doc, tag, text = Doc().tagtext() with tag("g", ("class", "ac-source")): centerX = width / 2 centerY = height / 2 with tag("circle", cx=centerX, cy=centerY, r=min(width, height) / 2): pass wavelength = width * 0.6 amplitude = height * 0.2 d = "M" for i in range(17): f = (i - 8) / 16 # -1 to 1 x = centerX + wavelength * f y = centerY + amplitude * math.sin(f * 2 * math.pi) d += " %.4f %.4f" % (x, y) with tag("path", ("d", d)): pass return indent(doc.getvalue())
def main(): doc, tag, text = Doc().tagtext() with tag('html'): with tag('head'): doc.stag('link', rel="stylesheet", type="text/css", href="/assets/css/project_styles.css") with tag('body'): with open('_projects/configs.txt', 'r') as f: configs = f.readlines() with tag('div', id="projectts"): with tag('table'): for project in configs: config_path = os.path.join('_projects/configs/', project.strip()) add_project(doc, tag, text, config_path) save_file(doc.getvalue())
def constructDoc(masterList): doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('body'): for data in masterList: #with tag('div', klass=data[0]): with tag('h3'): text(data[0]) doc.stag('br') for i in data[1]: with tag('a', href=i): text(i) doc.stag('br') #str = '<a href = "{}"/>'.format(i) #line('li', str) return doc.getvalue()
def buildChapterContent(title, elements): doc, tag, text = Doc().tagtext() doc.asis('<?xml version="1.0" encoding="utf-8"?>') doc.asis('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"\n "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">') with tag('html', xmlns="http://www.w3.org/1999/xhtml", lang="en-US"): with tag('head'): doc.stag('link', href="../Styles/style.css", type="text/css", rel="stylesheet") with tag('body'): with tag('h2'): text(title) for e in elements: with tag(e.name): text(str(e.string)) return indent(doc.getvalue())
def password_field(data): password_doc, password_tag, password_text = Doc(defaults={ data['name']: '' }, errors={ data['name']: 'Compulsury' }).tagtext() with password_tag('div', klass="form-group"): with password_tag('label', ('for', data['id'])): password_text(modeler(data)) password_doc.input(('v-model', data['vmodel']), name=data['name'], type='password', placeholder=data['placeholder'], id=data['id'], klass='form-control') return password_doc.getvalue()
def to_html(self): """Method for inserting box to the html doc.""" doc = Doc() with doc.tag('div',klass='figure'): doc.attr(('id','Figure-'+str(self.number))) if self.style: doc.attr(style=self.style) elif Figure.theme.data.data['style'][0]: doc.attr(style=Figure.theme.data.data['style'][0]) with doc.tag(self.ctn_type): if self.ctn_options: doc.stag('img',src=self.ctn,klass='image',style=self.ctn_options,alt='Figure-'+self.ctn) elif Figure.theme.data.data['content'][0]: doc.stag('img',src=self.ctn,klass='image',style=Figure.theme.data.data['content'][0],alt='Figure-'+self.ctn) else: doc.stag('img',src=self.ctn,klass='image',style='width:100%;',alt='Figure-'+self.ctn) self.put_caption(doc=doc) return doc.getvalue()
def to_html(self): """Convert self data to its html stream.""" doc = Doc() with doc.tag('div', id='Figure-' + str(self.number)): if self.style: doc.attr(style=self.style) else: doc.attr(klass='figure') with doc.tag(self.ctn_type): if self.cap_position is not None and self.cap_position.upper() == 'TOP': self.put_caption(doc=doc, klass='figure-caption') if self.ctn_options: doc.stag('img', src=self.ctn, klass='figure-content', style=self.ctn_options, alt='Figure-' + self.ctn) else: doc.stag('img', src=self.ctn, klass='figure-content', style='width:100%;', alt='Figure-' + self.ctn) if self.cap_position is None or self.cap_position.upper() == 'BOTTOM': self.put_caption(doc=doc, klass='figure-caption') return doc.getvalue()