def html(self): from lxml.html import builder as E return E.TABLE( E.CLASS("register"), E.TR(E.TH("Register Table", colspan="3")), *[ E.TR(E.TD(k), E.TD(E.CLASS("fixed"), "%x" % id(v)), E.TD(str(v))) for k, v in self.__p.iteritems() ])
def format_stats(self): """ Create a formatted report summarizing deltas from last week's job. Values for the report are drawn from the colon-delimited records in the YYYYMM.changes file written to the job's vendor output directory. """ table = B.TABLE(style="width: 400px;") values = self.week, self.year caption = "Changed Documents for Week %s, %s" % values table.append(B.CAPTION(caption, style="border-bottom: solid 1px;")) header_row = B.TR() for header in ("Document Type", "Added", "Modified", "Removed"): header_row.append(B.TH(header, style="text-align: right;")) table.append(header_row) path = "%s/%s%02d.changes" % (self.directory, self.year, self.week) for line in sorted(open(path)): doctype, action, count = line.strip().split(":") if action == "added": name = doctype.split(".")[0] row = B.TR(B.TD(name, style="text-align: right;")) table.append(row) row.append(B.TD(count, style="text-align: right;")) return html.tostring(table, encoding="unicode")
def login_page_gen(): html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Administration and moderation") ), E.BODY( E.H1(E.CLASS("heading"), "Farlight Engine Imageboard"), E.P(E.CLASS("loginmessage"), "You need to login"), E.FORM(E.CLASS("loginform"), E.TABLE( E.TR(E.TD('LOGIN'), E.TD(E.INPUT(type = 'text', name = 'login', value = '')) ), E.TR(E.TD('PASSWORD'), E.TD(E.INPUT(type = 'text', name = 'password', value = '')) ), ), E.INPUT(type = 'submit', value = 'LOGIN'), method = 'POST', action = '/admin/login' ) ) ) return lxml.html.tostring(html)
async def zlist(self, bot, event, room, user): html = E.TABLE() html.append(E.TR(E.TH('id'), E.TH('name'))) for unused_id, game in sorted(self.games.items(), key=lambda x: x[1]['name']): html.append(E.TR(E.TD(game['id']), E.TD(game['name']))) html_data = lxml.html.tostring(html, pretty_print=True).decode('utf-8') await bot.send_room_html(room, html_data)
def term_type_table(self): """Table showing all of the term type string for the concept.""" args = [self.term_types[0]] for term_type in self.term_types[1:]: args += [builder.BR(), term_type] term_types = builder.TD(*args) table = builder.TABLE(builder.TR(builder.TD("Term Type"), term_types)) table.set("class", "term-type-table") return table
def list_boards_menu(board_list, purpose): """need to put boards table creating to a separate function in future""" posts_num_cell = E.DIV(E.SPAN('????', style = 'display:inline-block; width:4em; text-align:center;'), E.INPUT(type='number', size='6', min='0', value='1', style = 'width: 6em;'), E.SELECT(E.OPTION('Секунды', value='1'), E.OPTION('Минуты', value='60'), E.OPTION('Часы', value='3600'), E.OPTION('Дни', value='86400', selected='') ), E.BUTTON('GET', onclick='get_posts_num_from_time(this)', type = 'button')) tablerows = [E.TR(E.TD(E.A(b.address, href = '/'+b.address)), E.TD(b.tablename), E.TD(str(b.name)), E.TD(str(b.fullname)), E.TD(str(b.description)), E.TD(str(b.category)), E.TD(str(b.pictures)), E.TD(str(b.bumplimit)), E.TD(str(b.maxthreads)), E.TD(copy.copy(posts_num_cell)) )for b in board_list] #purpose will be applyed later html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Creating board"), E.SCRIPT(type = 'text/javascript', src = '/adminscript.js') #js ), E.BODY( E.DIV(E.CLASS('adminupdiv'), E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')), E.H2(E.CLASS("heading"), "Listing boards"), ), E.TABLE( E.CLASS("boardstable"), E.TR(E.TH('Адрес'), E.TH('Таблица'), E.TH('Название'), E.TH('Полное название'), E.TH('Описание'), E.TH('Категория'), E.TH('Максимум картинок'), E.TH('Бамплимит'), E.TH('Максимум тредов'), E.TH('Постов за последнее время') ), *tablerows ) ) ) return lxml.html.tostring(html)
def html_page_return(board, thread, default_style): html = E.HTML( E.HEAD( E.META(**{'http-equiv':"Default-Style", 'content':default_style, 'id':'stylemetatag'}), E.TITLE("/"+board+"/ - №"+str(thread)), #title E.SCRIPT(type = 'text/javascript', src = '/mainscript.js'), #js *initiate.style_cache ), E.BODY( E.P(E.CLASS("board"), board, id = 'board'), E.P(E.CLASS("thread"), str(thread), id = 'thread'), E.TABLE( E.CLASS("maintable"), E.THEAD(E.TR(E.TD( E.TABLE(E.TR(E.TD(E.CLASS('left'), copy.copy(initiate.board_cache_navigation)), E.TD(E.CLASS('right'), utilfunctions.generate_right_up_corner_menu()), ), id='headblock'), E.HR(E.CLASS("delimeter")), )), id = 'header'), E.TBODY(E.TR(E.TD( E.H2(E.CLASS("boardname"), E.A('/' + board + '/ - '+ initiate.board_cache[board].name, href = '/' + board), ), E.HR(E.CLASS("delimeter")), initiate.board_cache[board].post_form, #need to make it depending on post_form_type E.SCRIPT('function open_form() {document.getElementById("postform").style.display = "block"; document.getElementById("closeform").style.display = "block"; document.getElementById("threadcreate").style.display = "none";}'), E.SCRIPT('function close_form() {document.getElementById("postform").style.display = "none"; document.getElementById("closeform").style.display = "none"; document.getElementById("threadcreate").style.display = "block";}'), E.H3(E.A('Ответить в тред', href = "javascript:open_form();"), id = 'threadcreate'), E.H4(E.A('Скрыть форму', href = "javascript:close_form();"), id = 'closeform'), E.HR(E.CLASS("delimeter")), EM('main', '', id = 'mainframe'), E.DIV('', id = 'optionsdiv'), )), id = 'mainpart'), E.TFOOT(E.TR(E.TD( E.DIV( E.HR(E.CLASS("delimeter"), id = 'end') ), initiate.board_cache_navigation, E.DIV('powered by ', E.A('Farlight Imageboard Engine', href='https://github.com/Alpherie/farlight_board_engine', target='_blank', ), id='credentials'), )), id = 'footer'),#we make it a footer ), onload = 'threadfunc()' ) ) return lxml.html.tostring(html)
def __add_row(self, rows, name, label): """Helper method to create a row for the definition meta table.""" values = getattr(self, name) if values: label = builder.TD(label) if not isinstance(values, list): values = [values] args = [values[0]] for value in values[1:]: args.append(builder.BR()) args.append(value) values = builder.TD(*args) rows.append(builder.TR(label, values))
def visit_Register(self, node): """Generate a Register DIV with heading, bitfield table, field listing, etc.""" ap = self.addressparagraph(node) ap.text += ' ' + register_format(node) root = E.DIV(ap, self.heading(node.name), CLASS('register'), *[E.P(d, CLASS('description')) for d in node.description], id="REG_" + node.name) if node.space: # We need bitfield tables. table = E.TABLE(CLASS('bitfield')) rows = [] for startbit in range(0, node.space.size, 16): endbit = startbit + 16 row = E.TR(CLASS('fields')) cells = [] for obj, start, size in node.space[startbit:endbit]: if obj: cell = E.TD(obj.name, CLASS('std_field')) else: cell = E.TD('.', CLASS('reserved_field')) cell.attrib['colspan'] = str(size) cells.append(cell) row.extend(reversed(cells)) rows.append(row) rows.append( E.TR( CLASS('bit_numbers'), *[ E.TD(str(n - 1)) for n in range(endbit, startbit, -1) ])) table.extend(reversed(rows)) root.append(table) fieldlist = E.UL(CLASS('fieldlist'), *self.visitchildren(node, reverse=True)) root.append(fieldlist) elif node.width != node.parent.width: # We have a truncated field, i.e. not all the bits that the # component allows. root.append(E.P('Bits {}:0 only.'.format(node.width - 1))) return root
def main(): parser = argparse.ArgumentParser(description='Get an HTML table from an OPML file with web resources ordered by Google PageRank.') parser.add_argument('--input', nargs=1, required=True, help='name of the OPML input file') parser.add_argument('--output', nargs=1, required=True, help='name of the HTML output file') args = parser.parse_args() input_file = args.input[0] output_file = args.output[0] tree = etree.parse(input_file) elems = tree.xpath("//opml/body/outline/outline") counter = 0 buggy = [] urls = [] for elem in elems: url = elem.attrib["htmlUrl"] title = elem.attrib["title"] pr = False retries = 3 while retries != 0: try: pr = int(pagerank.GetPageRank(url)) retries = 0 except Exception as e: retries -= 1 time.sleep(3) if pr != False: print url, title, pr urls.append({'title':title, "url":url, "pagerank":pr}) counter += 1 else: buggy.append({'url':url, 'title':title}) f = open(output_file, "w") headers = ["Title", "URL", "PageRank"] sorted_urls = sorted(urls, key=lambda k:k["pagerank"]) sorted_urls_as_a_list = [] sorted_urls.reverse() style = "border: 1px solid black" for elem in sorted_urls: print elem["title"], elem["url"], elem["pagerank"] sorted_urls_as_a_list.append(E.TR(E.TD(elem["title"], style=style), E.TD(E.A(elem["url"],href=elem["url"]), style=style), E.TD(str(elem["pagerank"]), style=style))) html = E.HTML(E.HEAD(), E.BODY(E.TABLE(*tuple(sorted_urls_as_a_list), style="border: 1px solid black; border-collapse: collapse"))) htmlcode = lxml.html.tostring(html) f.write(htmlcode) f.close()
def html(self): from lxml.html import builder as E return E.TABLE( E.CLASS("instruct"), E.TR(E.TH("Instruction", colspan="2")), E.TR( E.TD(str(tuple(self.outPointers)) + " ← " + self.name + str(tuple(self.inPointers)), colspan="2")), E.TR( E.TD(*[E.DIV(str(k)) for k in self.outData]), E.TD(*[E.DIV(str(k)) for k in self.inData]), ), )
async def show_help(self, bot, room, user, event): table = E.TABLE( E.TR(E.TH("command"), E.TH("arguments"), E.TH("details")), ) html = E.DIV(E.P("Command list:"), table) for command in self.commands: table.append( E.TR( E.TD(', '.join(command.aliases)), E.TD('\xa0'.join(arg.get_help_name() for arg in command.arguments)), E.TD(command.get_help()))) html_data = lxml.html.tostring(html, pretty_print=True).decode('utf-8') print(html_data) await bot.send_room_html(room, html_data)
def main_page_gen(default_style): html = E.HTML( E.HEAD( E.META(**{'http-equiv':"Default-Style", 'content':default_style, 'id':'stylemetatag'}), E.TITLE("U2ch - Main Page"), E.SCRIPT(type = 'text/javascript', src = '/mainscript.js'), #js *initiate.style_cache ), E.BODY( E.UL(initiate.stats_cache, style = "display: none;", id = "mblstatscache"), E.TABLE( E.CLASS("maintable"), E.THEAD(E.TR(E.TD(E.DIV(E.CLASS("mainslogandiv"), E.SPAN("U2CH"), E.SPAN("", style="display: inline-block; width: 5em;"), E.SPAN("Viewing above imageboards"), ), E.DIV(E.CLASS("mainimagediv"), E.IMG(src="u-2.jpg", style="width:496px;height:334px;"), ), )), id = 'header'), E.TBODY(E.TR(E.TD( E.HR(E.CLASS("delimeter")), E.DIV(E.CLASS("mblcontainer"), E.DIV(E.CLASS("mblcentering"), initiate.board_cache_main_page, ), ), E.HR(E.CLASS("delimeter")), )), id = 'mainpart'), E.TFOOT(E.TR(E.TD( E.DIV('powered by ', E.A('Farlight Imageboard Engine', href='https://github.com/Alpherie/farlight_board_engine', target='_blank', ), id='credentials'), )), id = 'footer'), ), onload = 'mainpagefunc()' ) ) return lxml.html.tostring(html)
def visit_Instance(self, node): """ Create a table row for this Instance and a new file giving it a memory map of its own. """ # If we're writing files, write another one for the instance and # create an HTML link. Otherwise just give it a name. try: relativefile = htmlpathjoin(self.subdir, node.name + self.extension) filename = os.path.join(self.path, relativefile) except TypeError: linkelement = node.name else: obj = type(self)(output=filename) try: obj.offset = node.offset + self.base except TypeError: obj.offset = node.offset obj.inst = node.name obj.breadcrumbs = E.A(self.title, href=htmlpathjoin('..', self.filename)) obj.styledir = htmlpathjoin(self.styledir, '..') obj.execute(node.binding) linkelement = E.A(node.name, href=relativefile) # And provide a table row for the MemoryMap desc = node.description or node.binding.description if isinstance(self.base, int): offset = '0x{:0{}X}'.format(node.offset + self.base, self.address_nibbles) else: offset = '{}+0x{:0{}X}'.format(self.base, node.offset, self.address_nibbles) return E.TR( E.TD(linkelement, CLASS('peripheral')), E.TD(offset, CLASS('paddress')), E.TD('0x{:0{}X}'.format(node.size, self.address_nibbles), CLASS('psize')), E.TD(CLASS('pdesc'), *[E.P(d) for d in desc]))
def row(self): """HTML markup for the link.""" if not hasattr(self, "_row"): label = builder.TD(self.__label) if self.__indent: label.set("class", "indent") if self.__external: display = url = self.__value else: doc_id = Doc.extract_id(self.__value) display = f"CDR{doc_id:d}" url = f"QcReport.py?Session=guest&DocId={doc_id:d}" link = builder.A(display, href=url) args = f"{self.__text} (", link, ")" self._row = builder.TR(label, builder.TD(*args)) return self._row
def draw_table(self, table, table_num=None): style = 'tt %s %s' % ( table.attrib.get('style', self.defaults['table_style']), table.attrib.get('align', self.defaults['table_align'])) cellpadding = '3' cellspacing = '0' htmltable = E.TABLE(cellpadding=cellpadding, ) htmltable.attrib['cellspacing'] = cellspacing htmltable.attrib['class'] = style # Add caption, if it exists if 'title' in table.attrib and table.attrib['title']: caption = '' if table_num and self.pis['tablecount'] == 'yes': caption = 'Table ' + str(table_num) + ': ' htmltable.append(E.CAPTION(caption + table.attrib['title'])) # Draw headers header_row = E.TR() col_aligns = [] for header in table.findall('ttcol'): th = E.TH() if header.text: th.text = header.text header_align = header.attrib.get('align', self.defaults['ttcol_align']) th.attrib['class'] = header_align # Store alignment information col_aligns.append(header_align) header_row.append(th) htmltable.append(E.THEAD(header_row)) # Draw body body = E.TBODY() tr = E.TR() num_columns = len(col_aligns) for i, cell in enumerate(table.findall('c')): col_num = i % num_columns if col_num == 0 and i != 0: # New row body.append(tr) tr = E.TR() td = E.TD() if cell.text: # Add text td.text = cell.text for child in cell: # Add any inline elements (references) for element in self._expand_ref(child): td.append(element) # Get alignment from header td.attrib['class'] = col_aligns[col_num] tr.append(td) body.append(tr) # Add final row htmltable.append(body) # Add to body buffer self.buf.append(self._serialize(htmltable))
def make_summary_row(test, result): def output(suffix): rel_path = test.url_map[test.url] return urllib.quote(os.path.join(test.name, rel_path) + suffix) if test.enabled: s = ResultSummary(result) return B.TR( B.TD(test.name), B.TD('%d (%d)' % (s.insertions, s.insertion_blocks)), B.TD('%d (%d)' % (s.deletions, s.deletion_blocks)), B.TD(B.A('original', href=output('')), ' ', B.A('benchmark', href=output(READABLE_SUFFIX)), ' ', B.A('result', href=output(RESULT_SUFFIX)), ' ', B.A('diff', href=output(DIFF_SUFFIX))), B.TD(test.notes)) else: return B.TR(B.CLASS('skipped'), B.TD('%s (SKIPPED)' % test.name), B.TD('N/A'), B.TD('N/A'), B.TD('N/A'), B.TD(test.notes))
def write_top(self, left_header, right_header): """ Buffers the header table """ for i in range(max(len(left_header), len(right_header))): if i < len(left_header): left = left_header[i] else: left = '' if i < len(right_header): right = right_header[i] else: right = '' # Add row to header_rows buffer left_td = E.TD(left) left_td.attrib['class'] = 'left' right_td = E.TD(right) right_td.attrib['class'] = 'right' tr = E.TR(left_td, right_td) self.buffers['header_rows'].append(self._serialize(tr))
def get_sections(lines, position, hierarchy): trs = [] pattern = re.compile('(?<=#)(.+)') while position < len(lines): line = lines[position] line = line.replace('\n', '') if line == '': position += 1 continue match = pattern.search(line) if match is None: return trs, position hierarchy.append(match.group(1)) divs, pos = get_boards(lines, position + 1, hierarchy) hierarchy.pop() trs.append(E.TR(E.TD(E.CLASS('header'), match.group(1)))) trs.append(E.TR(E.TD(E.CLASS('list'), *divs))) position = pos return trs, position
def related_info_table(self): """Table at the bottom of the report to links to other information.""" if not hasattr(self, "_related_info_table"): self._related_info_table = None rows = [drug_link.row for drug_link in self.drug_links] rows += [summary_ref.row for summary_ref in self.summary_refs] rows += [external_ref.row for external_ref in self.external_refs] rows += [name_link.row for name_link in self.name_links] rows += [pdq_term.row for pdq_term in self.pdq_terms] if self.thesaurus_ids: label = "NCI Thesaurus ID" args = [self.thesaurus_ids[0]] for id in self.thesaurus_ids[1:]: args += [builder.BR(), id] rows.append(builder.TR(builder.TD(label), builder.TD(*args))) if rows: self._related_info_table = builder.TABLE(*rows) self._related_info_table.set("class", "related-info-table") return self._related_info_table
def password_change_menu(): html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Administration and moderation") ), E.BODY( E.H1(E.CLASS("heading"), "Farlight Engine Imageboard"), E.P(E.CLASS("loginmessage"), "Change your password"), E.FORM(E.CLASS("loginform"), E.INPUT(type = 'hidden', name = 'action', value = 'change'), E.INPUT(type = 'hidden', name = 'instance', value = 'password'), E.TABLE( E.TR(E.TD('OLD PASSWORD'), E.TD(E.INPUT(type = 'password', name = 'old_passwd', value = '')) ), E.TR(E.TD('NEW PASSWORD'), E.TD(E.INPUT(type = 'password', name = 'new_passwd', value = '')) ), E.TR(E.TD('NEW PASSWORD AGAIN'), E.TD(E.INPUT(type = 'password', name = 'new_passwd_again', value = '')) ), ), E.INPUT(type = 'submit', value = 'LOGIN'), method = 'POST', action = '/admin' ) ) ) return lxml.html.tostring(html)
def list_bans_menu(ban_list, purpose): """need to put bans and boards table creating to a joint function in future""" tablerows = [E.TR(E.TD(str(b.id)), E.TD(b.ip), E.TD(b.initiator), E.TD(time.strftime('%d/%m/%Y %H:%M', time.localtime(b.date))), E.TD(str(b.level)), E.TD(E.BUTTON('Снять', type = 'button', onclick = 'remove_ban(this);')) )for b in ban_list] #purpose will be applyed later html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Creating board"), E.SCRIPT(type = 'text/javascript', src = '/adminscript.js') #js ), E.BODY( E.DIV(E.CLASS('adminupdiv'), E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')), E.H2(E.CLASS("heading"), "Listing bans"), ), E.TABLE( E.CLASS("boardstable"), E.TR(E.TH('ID'), E.TH('IP'), E.TH('Забанивший'), E.TH('Дата'), E.TH('Уровень'), E.TH('') ), *tablerows ) ) ) return lxml.html.tostring(html)
async def zlistsaves(self, bot, event, game_id, room, user): room_id = room.room_id specific_savegame_dir = os.path.join( self.save_dir, ZGameModule.escape_room_id(room_id), game_id) os.makedirs(specific_savegame_dir, exist_ok=True) filenames = [(f, os.path.getmtime(os.path.join(specific_savegame_dir, f))) for f in os.listdir(specific_savegame_dir) if os.path.isfile(os.path.join(specific_savegame_dir, f))] print(specific_savegame_dir, filenames) filenames.sort(key=lambda x: x[1]) html = E.TABLE() if not filenames: await bot.send_room_text( room, "No savegames for '{}' in this room".format(game_id)) return for f, s in filenames: timestamp = datetime.fromtimestamp(s) html.append(E.TR(E.TD(timestamp.isoformat(' ')), E.TD(f))) html_data = lxml.html.tostring(html, pretty_print=True).decode('utf-8') await bot.send_room_html(room, html_data)
def add_row(self, rows, level=0): """Create an HTML node to show this term and recurse for children. Pass: rows - sequence of rows to which we add new rows level - level of indent in the hierarchy Return: node object ready for insertion into an HTML tree """ args = [" " * (level - 1) * 2 + "+-"] if level else [] args += self.qc_link, " (", self.cdr_id, ")" row = builder.TR(builder.TD(*args)) if self.focus: row.set("class", "focus") rows.append(row) for child in self.children: child.add_row(rows, level + 1)
def insert_iref_index(self): # Write the heading self.write_heading('Index', autoAnchor='rfc.index') table = E.TABLE() # Sort iref items alphabetically, store by first letter alpha_bucket = {} keys = list(self._iref_index.keys()) keys.sort(key=str.upper) for key in keys: letter = key[0].upper() if letter in alpha_bucket: alpha_bucket[letter].append(key) else: alpha_bucket[letter] = [key] for letter in sorted(alpha_bucket.keys()): # Add letter element table.append(E.TR(E.TD(E.STRONG(letter)))) for item in sorted(alpha_bucket[letter]): # Add item element anchor = self._iref_index[item].anchor or '' if anchor: anchor = '#' + anchor td = E.TD(E.A(item, href=anchor)) else: td = E.TD(item) table.append(E.TR(E.TD(' '), td)) subkeys = list(self._iref_index[item].subitems.keys()) subkeys.sort(key=str.upper) for name in subkeys: subitem = self._iref_index[item].subitems[name] # Add subitem element td = E.TD() td.text = (u'\u00a0\u00a0') # Spaces anchor = subitem.anchor or '' anchor = '#' + anchor td.append(E.A(name, href=anchor)) table.append(E.TR(E.TD(' '), td)) self.buf.append(self._serialize(table))
def list_manifests(service): '''Replies to the client with criteria list for a service. The output should be similar to installadm list. Args service - the name of the service being listed Returns None Raises None ''' print 'Content-Type: text/html' # HTML is following print # blank line, end of headers print '<html>' print '<head>' sys.stdout.write('<title>%s %s</title>' % (_('Manifest list for'), service)) print '</head><body>' port = 0 try: smf.AISCF(FMRI="system/install/server") except KeyError: # report the internal error to error_log and requesting client sys.stderr.write( _("error:The system does not have the " "system/install/server SMF service.")) sys.stdout.write( _("error:The system does not have the " "system/install/server SMF service.")) return services = config.get_all_service_names() if not services: # report the error to the requesting client only sys.stdout.write(_('error:no services on this server.\n')) return found = False if config.is_service(service): service_ctrl = AIService(service) found = True # assume new service setup path = service_ctrl.database_path if os.path.exists(path): try: aisql = AIdb.DB(path) aisql.verifyDBStructure() except StandardError as err: # report the internal error to error_log and # requesting client sys.stderr.write( _('error:AI database access ' 'error\n%s\n') % err) sys.stdout.write( _('error:AI database access ' 'error\n%s\n') % err) return # generate the list of criteria for the criteria table header criteria_header = E.TR() for crit in AIdb.getCriteria(aisql.getQueue(), strip=False): criteria_header.append(E.TH(crit)) # generate the manifest rows for the criteria table body names = AIdb.getManNames(aisql.getQueue()) table_body = E.TR() allcrit = AIdb.getCriteria(aisql.getQueue(), strip=False) colspan = str(max(len(list(allcrit)), 1)) for manifest in names: # iterate through each manifest (and instance) for instance in range( 0, AIdb.numInstances(manifest, aisql.getQueue())): table_body.append(E.TR()) # print the manifest name only once (from instance 0) if instance == 0: href = '../' + service + '/' + manifest row = str(AIdb.numInstances(manifest, aisql.getQueue())) table_body.append( E.TD(E.A(manifest, href=href, rowspan=row))) else: table_body.append(E.TD()) crit_pairs = AIdb.getManifestCriteria(manifest, instance, aisql.getQueue(), onlyUsed=True, humanOutput=True) # crit_pairs is an SQLite3 row object which doesn't # support iteritems(), etc. for crit in crit_pairs.keys(): formatted_val = AIdb.formatValue( crit, crit_pairs[crit]) # if we do not get back a valid value ensure a # hyphen is printed (prevents "" from printing) if formatted_val and crit_pairs[crit]: table_body.append( E.TD(formatted_val, align="center")) else: table_body.append( E.TD(lxml.etree.Entity("nbsp"), align="center")) # print the default manifest at the end of the table, # which has the same colspan as the Criteria List label else: href = '../' + service + '/default.xml' table_body.append( E.TR( E.TD(E.A("Default", href=href)), E.TD(lxml.etree.Entity("nbsp"), colspan=colspan, align="center"))) web_page = E.HTML( E.HEAD(E.TITLE(_("OmniOS Automated " "Installation Webserver"))), E.BODY( E.H1( _("Welcome to the OmniOS " "Automated Installation webserver!")), E.P( _("Service '%s' has the following " "manifests available, served to clients " "matching required criteria.") % service), E.TABLE(E.TR(E.TH(_("Manifest"), rowspan="2"), E.TH(_("Criteria List"), colspan=colspan)), criteria_header, table_body, border="1", align="center"), )) print lxml.etree.tostring(web_page, pretty_print=True) # service is not found, provide available services on host if not found: sys.stdout.write(_('Service <i>%s</i> not found. ') % service) sys.stdout.write(_('Available services are:<p><ol><i>')) host = socket.gethostname() for service_name in config.get_all_service_names(): # assume new service setup port = config.get_service_port(service_name) sys.stdout.write( '<a href="http://%s:%d/cgi-bin/' 'cgi_get_manifest.py?version=%s&service=%s">%s</a><br>\n' % (host, port, VERSION, service_name, service_name)) sys.stdout.write('</i></ol>%s' % _('Please select a service ' 'from the above list.')) print '</body></html>'
def board_creation_menu(): #here is the html board creation menu html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Creating board") ), E.BODY( E.DIV(E.CLASS('adminupdiv'), E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')), E.H2(E.CLASS("heading"), "Create new board"), ), E.DIV(E.CLASS("boardcreateform"), E.FORM( E.INPUT(type = 'hidden', name = 'action', value = 'create'), E.INPUT(type = 'hidden', name = 'instance', value = 'board'), E.TABLE( E.TR(E.TD('Address'), E.TD(E.INPUT(type = 'text', name = 'address', value = '')) ), E.TR(E.TD('Tablename'), E.TD(E.INPUT(type = 'text', name = 'tablename', value = '')) ), E.TR(E.TD('Name'), E.TD(E.INPUT(type = 'text', name = 'name', value = '')) ), E.TR(E.TD('Fullname'), E.TD(E.INPUT(type = 'text', name = 'fullname', value = '')) ), E.TR(E.TD('Description'), E.TD(E.INPUT(type = 'text', name = 'description', value = '')) ), E.TR(E.TD('Pics number'), E.TD(E.INPUT(type = 'number', name = 'picsnum', value = '', min = '0', max = '10')) ), E.TR(E.TD('Bumplimit'), E.TD(E.INPUT(type = 'number', name = 'bumplimit', value = '', min = '0')) ), E.TR(E.TD('Max threads'), E.TD(E.INPUT(type = 'number', name = 'maxthreads', value = '', min = '-1')) ), E.TR(E.TD(E.INPUT(type='checkbox', name='delposts', value='1', checked='checked'), 'Удаление постов', colspan='2', style='text-align:center;')), E.TR(E.TD(E.INPUT(type='checkbox', name='delopposts', value='1', checked='checked'), 'Удаление тредов', colspan='2', style='text-align:center;')), ), E.INPUT(type = 'submit', value = 'Create'), method='POST', action='/admin/' ) ) ) ) return lxml.html.tostring(html)
def pr_table(token, jira_url, delta): u""" Return an Element that renders all changes in `delta` as a table listing merged PRs.abs Arguments: token: The github token to access the github API with. jira_url: The base url of the JIRA instance to link JIRA tickets to. delta (VersionDelta): The AMIs to compare. """ version = delta.new or delta.base match = re.search(u"github.com/(?P<org>[^/]*)/(?P<repo>.*)", version.repo) api = GitHubAPI(match.group(u'org'), match.group(u'repo'), token) try: prs = api.get_pr_range(delta.base.sha, delta.new.sha) change_details = E.TABLE( E.CLASS(u"wrapped"), E.TBODY( E.TR( E.TH(u"Merged By"), E.TH(u"Author"), E.TH(u"Title"), E.TH(u"PR"), E.TH(u"JIRA"), E.TH(u"Release Notes?"), ), *[ E.TR( E.TD( E.A( pull_request.merged_by.login, href=pull_request.merged_by.html_url, )), E.TD( E.A( pull_request.user.login, href=pull_request.user.html_url, )), E.TD(pull_request.title), E.TD( E.A( str(pull_request.number), href=pull_request.html_url, )), E.TD( format_jira_references(jira_url, pull_request.body)), E.TD(u""), ) for pull_request in sorted( prs, key=lambda pr: pr.merged_by.login) ])) except Exception: # pylint: disable=broad-except LOGGER.exception(u'Unable to get PRs for %r', delta) change_details = E.P("Unable to list changes") return SECTION( E.H3(u"Changes for {} (".format(delta.app), E.A(GITHUB_PREFIX.sub(u'', version.repo), href=version.repo), ")"), E.P(E.STRONG(u"Before: "), E.A(delta.base.sha, href=format_commit_url(delta.base))), E.P(E.STRONG(u"After: "), E.A(delta.new.sha, href=format_commit_url(delta.new))), change_details, )
def create_table(): """HTML generation by lxml.html tree.""" divisions = ['All', 'E', 'CMS', 'T', 'A', 'AE', 'PPD', 'AD/APC', 'TD', 'CD', 'ND', 'LBN', 'Other'] pubtypes = ['All', 'PUB', 'THESIS', 'CONF', 'TM', 'FN', 'SLIDES', 'POSTER'] dates = [YEAR_2, YEAR_1, YEAR, MONTH_2, MONTH_1, MONTH] years = [YEAR_2, YEAR_1, YEAR] months = [MONTH_2, MONTH_1, MONTH] # This is a doctype work around for a lxml.etree bug doctype_wa = etree.parse(StringIO('''<!DOCTYPE html>\n<html>\n</html>''')) head_tag = E.HEAD( E.META({'charset': 'utf-8'}), E.TITLE("FERMILAB RESEARCH AT A GLANCE"), E.STYLE( {'type': 'text/css'}, "td {text-align: right;}", " td.l {text-align: left;padding: 7px;}", " a.t {display: block;}" ) ) body = E.BODY(E.P( E.A("Fermilab Technical Publications", href="http://ccd.fnal.gov/techpubs/fermilab_spires.html") )) tag_h3 = E.H3("FERMILAB RESEARCH AT A GLANCE") tag_p = E.P("Glossary at end.") tag_p_and_i = E.P(E.I("Updated: " + DATE_TIME_STAMP)) body.append(tag_h3) body.append(tag_p) body.append(tag_p_and_i) table = E.TABLE() tag_tr_td = E.TR(E.TD, E.TD("Date")) for division in divisions: if division == 'A': division = 'AT' tag_tr_td.append(E.TD(division)) table.append(tag_tr_td) pub_table_row = E.TR() for pubtype in pubtypes: pub_table_row.append(E.TD(pubtype)) pub_type_datelist = E.TD() year_list = E.UL() month_list = E.UL() for year in years: year_list.append(E.LI(year)) for month in months: month_list.append(E.LI(month)) pub_type_datelist.append(year_list) pub_type_datelist.append(month_list) pub_type_datelist.append(E.UL()) pub_table_row.append(pub_type_datelist) pub_type_datelist = E.TD() for division in divisions: tdg = E.TD() list_of_searches = E.UL() for date in dates: if division == 'All': division = '' if pubtype == 'All': pubtype = '' search = 'find r fermilab ' + pubtype if division == 'Other': for good_division in divisions[1:len(divisions)-1]: if good_division == 'AD/APC': search += ' not (r AD or APC)' else: search += ' not r ' + good_division elif division == 'AD/APC': search = 'find r fermilab ' + pubtype + \ ' and (r AD or APC)' else: search += ' ' + division search += ' and de ' + date search = re.sub(r'\s+', ' ', search) result = perform_request_search(p=search, cc="Fermilab") result = len(result) if result == 0: hit_number = E.LI() else: link = search.replace(' ', '+') link = 'https://inspirehep.net/search?cc=Fermilab&p=' + link link += '&rg=100&sf=earliestdate' hit_number = E.LI(E.A({'class': 't'}, str(result), href=link)) list_of_searches.append(hit_number) if date == YEAR or date == MONTH: tdg.append(list_of_searches) list_of_searches = E.UL() pub_table_row.append(tdg) table.append(pub_table_row) pub_table_row = E.TR() glos = E.H4('Glossary') table2 = E.TABLE() glos_tr_td = E.TR( E.TD({'class': 'l'}, "E: Experimental papers"), E.TD({'class': 'l'}, "PPD: Particle Physics Division papers") ) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "T: Particle Physics Division \ Theoretical Physics Department papers"), E.TD({'class': 'l'}, "AD/APC: Accelerator Division \ and Accelerator Physics Center papers")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "AT: Fermilab Center for Particle \ Astrophysics theoretical papers"), E.TD({'class': 'l'}, "TD: Technical Division papers")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "AE: Fermilab Center for Particle \ Astrophysics experimental papers"), E.TD({'class': 'l'}, "CD: Computing Sector papers")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "ND: Neutrino Division papers"), E.TD({'class': 'l'}, "LBN: Long Baseline Neutrino \ Sector papers")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, " "), E.TD({'class': 'l'}, " ")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, " "), E.TD({'class': 'l'}, " ")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, " "), E.TD({'class': 'l'}, " ")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "PUB: Paper intended for \ publication in a journal"), E.TD({'class': 'l'}, "FN: Physics note - short paper not \ fitting the other categories")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "CONF: Paper written as part of a \ conference"), E.TD({'class': 'l'}, "SLIDES: Slides presented at a \ conference or lecture")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "THESIS: Ph.D. thesis based on \ work done at Fermilab"), E.TD({'class': 'l'}, "POSTER: Poster presented at a \ conference")) table2.append(glos_tr_td) glos_tr_td = E.TR(E.TD({'class': 'l'}, "TM: Technical memo"), E.TD({'class': 'l'}, "")) table2.append(glos_tr_td) body.append(table) body.append(glos) body.append(table2) doctype_wa.getroot().append(head_tag) doctype_wa.getroot().append(body) out = lxml.html.tostring(doctype_wa, encoding='UTF-8', pretty_print=True, method='html').rstrip('\n') return out
def _lxml_form_generator(self): """Is used for generating lxml post form""" formargs = [] formargs.append(E.TR( E.TD('EMAIL'), E.TD(E.INPUT(type = 'text', name = 'email', value = '', id = 'emailfield'), E.INPUT(type = 'submit', value = 'POST', id = 'postbutton') ), ) ) formargs.append(E.TR( E.TD('THEME'), E.TD(E.INPUT(type = 'text', name = 'theme', value = '', size = '50')), ) ) formargs.append(E.TR( E.TD('NAME'), E.TD(E.INPUT(type = 'text', name = 'name', value = '', size = '50')), ) ) formargs.append(E.TR( E.TD('TEXT'), E.TD(E.TEXTAREA(name = 'text', rows = '8', cols = '50', placeholder = 'POST')), ) ) if self.pictures == 0: pass elif self.pictures == 1: formargs.append(E.TR(#should add checking if pics are available E.TD('PICTURE'), E.TD(E.INPUT(type = 'file', name = 'file0', accept = 'image/*'), id = 'filecellone'), ) ) else: formargs.append(E.TR(#should add checking if pics are available E.TD('PICTURE'), E.TD(E.INPUT(type = 'file', name = 'file0', accept = 'image/*'), E.BUTTON('+', type = 'button', onclick = 'add_file_input(this);', id = '0filebutton'), E.SPAN(str(self.pictures), style = 'display:none;', id = 'maxfiles'), id = 'filecellmany'), ) ) formargs.append(E.TR(#should add checking if deleting is available E.TD('PASSWORD'), E.TD(E.INPUT(type = 'password', name = 'password', value = '', size = '10'), id = 'passwordcell'), ) ) if True:#should add checking if captcha is available formargs.append(E.TR( E.TD( E.CENTER('CAPTCHA WILL BE HERE'), colspan = '2' ) ) ) formargs.append(E.TR(E.TD('CAPTCHA'), E.TD(E.INPUT(type = 'text', name = 'captcha', value = '')), ) ) form = E.FORM(E.CLASS("postform"), #postform E.INPUT(type = 'hidden', name = 'action', value = 'post'), E.INPUT(type = 'hidden', name = 'op', value = '0', id = 'op_referer'), E.SCRIPT('document.getElementById("op_referer").value = document.getElementById("thread").innerHTML;'), E.TABLE(*formargs), method = 'POST', action = '/'+self.address, enctype = 'multipart/form-data', id = 'postform') return form