def classEdit() -> dialog.Dialog: d = dialog.Dialog("Class(es)", ok_cancel = True, default_css = False) def toggleLevels(event): if event.target.checked: del d.select("#levelList")[0].attrs["readonly"] else: d.select("#levelList")[0].attrs["readonly"] = '' d.panel <= html.P("Enter one or more classes and corresponding hit dice, separating multiple entries by a comma (,).") d.panel <= html.LABEL("Class List:", For = "classList") d.panel <= html.INPUT(id = "classList") d.panel <= html.P("For the hit dice, write each entry as the number of sides of the associated die (ex. \"6\" for a d6).") d.panel <= html.LABEL("Dice List:", For = "diceList") d.panel <= html.INPUT(id = "diceList") d.panel <= html.P("If you need to edit class levels, enter them here like the dice.") d.panel <= html.LABEL("Edit Level(s)?", For = "levelsCheck") levelsCheck = html.INPUT(id = "levelsCheck", type = "checkbox") levelsCheck.bind("change", toggleLevels) d.panel <= levelsCheck d.panel <= html.BR() d.panel <= html.LABEL("Level List:", For = "levelList") d.panel <= html.INPUT(id = "levelList", readonly = '') return d
def start(event): "get parameter values and reinitialize data" mean = float(document["mean"].value) stdev = float(document["stdev"].value) ssize = int(document["ssize"].value) decs = 6 # max of decimal places to test document['approxmean'].text = "" document['samplevalues'].text = "" d = [] for i in range(ssize): d.append(gauss(mean, stdev)) s = sum(d) # s = 0 # for e in d: # #print e # s += e for p in range(0, decs): form = "%%1.%df" % p #print form % (s/len(d)) document['approxmean'] <= html.P(form % (s / len(d))) for e in d: document['samplevalues'] <= html.P(str(e))
def output_data(req): if document.select('#data_on_page'): document['xls_link'].clear() if document.select('#rt1'): document['output_txt'].clear() global _name _name = req.text link_xls = html.P( html.IMG(loading='lazy', src='/static/img/xlsx_logo.png', width='45px', height='49px', Class='mr-2') + html.A('Скачать данные в формате xlsx', href=f'/static/combs/{_name}.xlsx')) link_txt = html.P( html.IMG(loading='lazy', src='/static/img/txt_logo.png', width='45px', height='49px', Class='mr-2') + html.A('Скачать данные в формате txt', href=f'/static/combs/{_name}.txt')) document['xls_link'] <= link_xls document['xls_link'] <= link_txt document['xls_link'] <= html.P( html.IMG(loading='lazy', src='/static/img/arrow_b.png', width='45px', height='49px', Class='mr-2') + html.A('Вывести данные на странице ниже', id='data_on_page', href='#output-txt')) document["data_on_page"].bind('click', output_txt_data)
def build_tree(e): if e is None: tmp = html.DIV(html.P(""), Class='leaf') else: tmp = html.DIV(html.P(e.value), Class='leaf') tmp <= build_tree(e.left) tmp <= build_tree(e.right) return tmp
def __init__(self, loginmessage, returnaction=None, id=None): DialogBox.__init__(self, "Log In", id=id) self.returnaction = returnaction self <= html.P(loginmessage) self.loginbox = InputBox(self.checkuserexists, id="loginbox") self <= self.loginbox self <= Button("Log In", self.checkuserexists) self <= html.HR() self <= html.P("Don't have a username?\nClick below to create one") self <= Button("Create username", self.openusernamedialog)
def init_cards(): for i in range(7): card = html.DIV(Class='ac_card') card <= html.IMG( src=f'/static/img/fall/random_thumbnails/{thumbnail[i]}.png', Class='ac_card_thumbnail') cc = html.DIV(Class='ac_card_content') cc <= html.P(peoples[i]) cc <= html.P(f'在 {towns[i]} 上傳') card <= cc card <= html.DIV(upload_time[i], Class='ac_card_time') document['ac_cards'] <= card
def update_cards(): if ci + 6 >= 20: print('stop update') return for i, card in enumerate(document['ac_cards'].children): card.children[ 0].src = f'/static/img/fall/random_thumbnails/{thumbnail[ci + i]}.png' cc = html.DIV(Class='ac_card_content') cc <= html.P(peoples[ci + i]) cc <= html.P(f'在 {towns[ci+i]} 上傳') card.replaceChild(cc, card.children[1]) card.children[2].text = upload_time[ci + i] card.style = {'transition': 'none', 'transform': 'none'}
def spellTableCreate() -> dialog.Dialog: d = dialog.Dialog("Create Spell Table", ok_cancel = True, default_css = False) d.panel <= html.P("Select an ability to be the source of magical power:") for a in ("intelligence", "wisdom", "charisma"): d.panel <= html.INPUT( id = a + "`spellTableAbilityRadio", name = "ability", value = a, type = "radio" ) d.panel <= html.LABEL(a.capitalize(), For = a + "`spellTableAbilityRadio") d.panel <= html.BR() d.panel <= html.P("Select a class that does not yet have a spell table:") return d
def setup(self, container): def _make_handler(worldname): def _handler(e): print("Handling %s for %s" % (e, worldname)) for ele in container.get(selector=".world-container"): ele.class_name = "world-container world-container-hidden" container[ "world-container_" + worldname].class_name = "world-container world-container-enabled" for ele in container.get(selector=".world-bar-item"): ele.class_name = "world-bar-item" container["world_" + worldname].class_name += " world-button-enabled" return _handler for key, value in sorted(self.game.worlds.items(), key=lambda e: e[1].sortorder): baritem = html.DIV( id="world_" + key, Class="world-bar-item" + (" world-button-enabled" if value.sortorder == 0 else "")) baritem <= html.IMG(src=value.image, title=value.name) baritem <= html.P(value.name, Class="world-text") baritem.bind("click", _make_handler(key)) container["colonies"] <= baritem
def formatted(inputstring): output = [] stringlist = inputstring.split("\n\n") for s in stringlist: s = s.strip() if s[:3] == "## ": output.append(html.H2(s[3:])) else: while " http" in s: start = s.index(" http") end1 = s.find(" ", start+1) if end1 < 0: end1 = 1e12 end2 = s.find("\n", start+1) end = min(end1, end2) if end < 0: end = None link = s[start+1:end] s = s.replace(link, f" <a href='{link}'>{link}</a>") markup = [("`", "code"), ("**", "bold"), ("*", "italic")] for (code, className) in markup: while code in s: L = len(code) start = s.index(code) end = s.find(code, start+L) text = s[start:end+L] s = s.replace(text, f" <span class='{className}'>{text[L:-L]}</span>") s = s.replace("\n", "<br />\n") output.append(html.P(s)) return output
def draw_contact_bigButton(): panel = document["main_panel"] p = html.P("Send an email to GeneXpresso:") p.style.textAlign = "center" p.style.fontSize = "large" p.style.font = "20px verdana" p.style.textAlign = "center" panel <= html.BR() panel <= html.BR() panel <= html.BR() panel <= html.BR() #panel <= p form = html.FORM() form.style.fontSize = "large" form.style.font = "20px verdana" form.action = "mailto:[email protected]" form.method = "POST" form.style.textAlign = "center" global buttonSendEmail buttonSendEmail = html.INPUT() buttonSendEmail.type = "submit" buttonSendEmail.value = "Send" button_style_default(buttonSendEmail) buttonSendEmail.bind('mouseout', mouse_out_send_email) buttonSendEmail.bind('mouseover', mouse_over_send_email) form <= buttonSendEmail panel <= form
def deleteSheetRequest(event): sheet = event.target["id"].split('`')[1] box = dialog.Dialog("Confirm Deletion", ok_cancel=("Delete", "Cancel")) box.panel <= html.P( "Are you sure you want to delete sheet \"" \ + sheet + "\"? (The file will remain on disk, " \ + "but will be inaccessible)" ) def delete(clickEvent): box.close() ajaxPostJSON( "/user/", {"method": "delete", "sheetName": sheet}, lambda r : sheetReplyGeneric(r, { "noErrorTitle": "Deleted", "noErrorBody": "Sheet \"{0[0]}\" has been deleted.\n" \ + "A backup copy will remain in the server's recycle bin, " \ + "just in case.", "errorTitle": "Deletion Error" }, [ "sheetName" ]) ) box.ok_button.bind("click", delete)
def __init__(self, title, message, *, top=None, left=None, default_css=True, remove_after=None, ok=False): """If remove_after is set, number of seconds after which the dialog is removed.""" Dialog.__init__(self, title, top=top, left=left, default_css=default_css) self.panel <= html.DIV(message) if ok: ok = ok if isinstance(ok, str) else "Ok" self.ok_button = html.BUTTON(ok, Class="brython-dialog-button") self.panel <= html.P() self.panel <= html.DIV(self.ok_button, style={"text-align": "center"}) self.ok_button.bind("click", lambda ev: self.remove()) if remove_after: if not isinstance(remove_after, (int, float)): raise TypeError("remove_after should be a number, not " + str(remove_after.__class__.__name__)) window.setTimeout(self.close, remove_after * 1000)
def delete(evt, elt): dialog_window.style.display = "block" dialog.clear() dialog_title = dialog_window.select_one(".dialog_title") dialog_title.clear() dialog_title <= html.SPAN("Remove script") dialog <= f"Do you really want to delete script {current} ?" dialog <= html.P() dialog <= html.BUTTON("Ok") + html.BUTTON("Cancel") @dialog.select("button")[0].bind("click") def confirm_delete(evt): db = request.result tx = db.transaction("scripts", "readwrite") store = tx.objectStore("scripts") cursor = store.delete(current) dialog_window.style.display = "none" # when record is added, show message def ok(evt): open_scripts.remove(current) editor.text = "" print_line_nums() draw_file_browser() cursor.bind('success', ok) @dialog.select("button")[1].bind("click") def cancel_delete(evt): dialog_window.style.display = "none"
async def _restart_decision_making(): global vda_running # Terminate any current VDA and clear the log. if vda_running: # Kill the current VDA job. signal('choice', 'quit') # Wait till it's dead before continuing. await get_signal('quit_done') document['dm'].textContent = '' # Reword "start" to "restart". document['start-button'].textContent = 'Restart decision making' # Parse the problem definition. try: scenario = JS.JSON.parse(document['problem-definition'].value) except Exception as e: # There's no more specific exception type to use at the Python # level. document['dm'].textContent = str(e) return interact_args, alts, namer = setup_interactive(scenario) # Begin VDA. try: vda_running = True prefs = await interact(**interact_args) document['dm'] <= H.P(T( results_text(scenario, prefs, alts, namer))) except Quit: signal('quit_done') finally: vda_running = False
def __init__(self, message, returnaction=None, id=None): DialogBox.__init__(self, "Create User Name", id=id) self.returnaction = returnaction self <= html.P(message) self.usernamebox = InputBox(self.checkuserexists, id="usernamebox") self <= self.usernamebox self <= Button("Create Username", self.checkuserexists)
def draw(self, parent_node): self.node = html.DIV(Class="task", Id=self.id, draggable=True) self.node.style.backgroundColor = DB["TASKS_COLORS"][self.color] parent_node <= self.node self.zprogress = html.DIV(Class="task_progress") self.progress_text = html.P("%d" % self.progress + "%", Class="task_progress_text") self.zprogress <= self.progress_text self.progress_bar = html.DIV(Class="task_progress_bar") self.progress_bar.style.width = percent(self.progress) self.zprogress <= self.progress_bar self.command_delete = html.DIV("X", Class="task_command_delete") self.command = html.TABLE(html.TR( html.TD(self.zprogress, Class="task_command") + html.TD(self.command_delete)), Class="task_command") self.node <= self.command self.zdesc = html.P(Class="task_desc") self.node <= self.zdesc self.node.drop_id = self.id self.node.task = self self.node.bind('dragstart', self.drag_start) self.node.bind('dragover', self.drag_over) self.node.bind('drop', self.drag_drop) self.node.bind('click', self.color_change) self.zprogress.task = self self.zprogress.bind('click', self.make_progress) self.command_delete.task = self self.command_delete.bind('click', self.task_delete) self.zdesc.task = self self.zdesc.desc = self.desc self.zdesc.bind('click', self.task_edit) self.set_text() for task in self.tasks: task.draw(self.node)
def __init__(self, pageindex, title, backgroundcolour): super().__init__(title, backgroundcolour) self.viewed = False self.chartbox = ws.ColumnPanel(className="chartcontainer") self.description = html.DIV(Class="description") self.databox = html.TEXTAREA(Class="databox") self.codebox = html.TEXTAREA(Class="codebox") self.attach(ws.RowPanel([ html.DIV([ self.description, html.P("How the data is structured:", Class="boxlabel"), self.databox, html.P("Code to generate the charts:", Class="boxlabel"), self.codebox ], Class="leftpane"), self.chartbox ]))
def update_table(doc, global_vars): for row in doc["var_accordion"]: row.remove() for k, v in global_vars["editor_ns"].items(): card_div = html.DIV(Class="card") card_header = html.DIV(id=f"h_{k}", Class="card-header", **{ "data-toggle": "collapse", "data-target": f"#c_{k}", "aria-expanded": "false", "aria-controls": f"c_{k}" }) card_header_varname = html.SPAN("", Class="card_header_inner") card_header_varvalue = html.SPAN( "", Class="card_header_inner card_header_inner_value") card_header_varname <= html.P(k, Class="card_font card_header_text") card_header_varvalue <= html.P(repr(v), Class="card_font card_header_text", **{ "data-toggle": "collapse", "data-target": f"#c_{k}", "aria-expanded": "false", "aria-controls": f"c_{k}" }) card_header <= card_header_varname card_header <= card_header_varvalue card_div <= card_header card_content = html.DIV(id=f"c_{k}", Class="collapse hide card_content_root", **{ "aria-labelledby": f"h_{k}", "data-parent": "#var_accordion" }) card_content <= html.DIV("[object information table to be added]", Class="card-body card_font") card_div <= card_content doc["var_accordion"] <= card_div
def show_results(self): """ show table of results""" doc['container'].clear() doc['container'] <= html.DIV( 'Browser Version: %s' % window.navigator.userAgent) _v = sys.implementation.version doc['container'] <= html.DIV('Brython Version: %s.%s.%s' % (_v.major, _v.minor, _v.micro)) doc['container'] <= html.DIV( 'Brython debug mode: %s' % sys.brython_debug_mode) doc['container'] <= html.DIV( 'CPython Version: %s' % self.cpython_version) doc['container'] <= html.P(html.I('Results are in milliseconds (ms)')) _table = html.TABLE() _tr = html.TR() _tr <= html.TH('Benchmark') _tr <= html.TH('Code') _tr <= html.TH('Brython') _tr <= html.TH('CPython') _tr <= html.TH('Difference') _tr <= html.TH('X Faster') _table <= _tr for _filename in self._timings.keys(): _tr = html.TR() _tr <= html.TD(_filename) _tr <= html.TD( highlight.highlight(self._timings[_filename]['code'])) for _platform in ('brython', 'cpython'): _tr <= html.TD('%5.0f' % self._timings[_filename][_platform], style={'text-align': 'right'}) _diff = self._timings[_filename]['cpython'] - self._timings[ _filename]['brython'] _x = self._timings[_filename]['cpython'] / self._timings[ _filename]['brython'] if _x > 1: _color = "green" elif _x < 0.5: _color = "red" else: _color = "black" _tr <= html.TD('%5.0f' % _diff, style={'text-align': 'right'}) _tr <= html.TD('%4.2f' % _x, style={ 'color': _color, 'text-align': 'right' }) _table <= _tr doc['container'] <= _table
def spellTableSetMaxLevel(className : str, currentMaxLevel : int) -> dialog.Dialog: d = dialog.Dialog( "Maximum " + className + " Spell Level", ok_cancel = True, default_css = False ) d.panel <= html.P("Enter a new maximum spell level (1 to 9 inclusive):") d.panel <= html.INPUT( id = "newMaxSpellLevel", type = "number", min = 1, max = 9, value = currentMaxLevel ) return d
def draw_task(self, task, parent_node): node = html.DIV(Class="task", Id=task.id, draggable=True) node.style.backgroundColor = self.kanban.tasks_colors[task.color_id] parent_node <= node progress = html.DIV(Class="task_progress") progress_text = html.P("%d%%" % task.progress, Class="task_progress_text") progress <= progress_text progress_bar = html.DIV(Class="task_progress_bar") progress_bar.style.width = percent(task.progress) progress <= progress_bar command_delete = html.DIV("X", Class="task_command_delete") command = html.TABLE(html.TR( html.TD(progress, Class="task_command") + html.TD(command_delete)), Class="task_command") node <= command desc = html.P(Id="desc %s" % task.id, Class="task_desc") desc.html = task.desc node <= desc node.bind('dragstart', ev_callback(self.drag_start, task)) node.bind('dragover', self.drag_over) node.bind('drop', ev_callback(self.drag_drop, task)) node.bind('click', ev_callback(self.change_task_color, task, node)) progress.progress_bar = progress_bar progress.progress_text = progress_text progress.bind('click', ev_callback(self.make_task_progress, task, progress)) command_delete.bind('click', ev_callback(self.remove_task, task)) desc.bind('click', ev_callback(self.edit_task, task)) self.draw_tasks(task, node)
def output_txt_data(e): if not document.select('#rt1'): link_txt = f'static/combs/{_name}.txt' def read(f): document['rt1'].value = f.read() div = html.DIV(html.P(), Class='form-group') div <= html.TEXTAREA(id="rt1", rows="20", cols="30", autocomplete="off", Class='form-control') document['output_txt'] <= div ajax.get(link_txt, oncomplete=read)
def __init__(self, title="", message="", style={}, top=None, left=None, remove_after=None, ok=False): """If remove_after is set, number of seconds after which the dialog is removed.""" Dialog.__init__(self, title, style, top, left) self.panel <= html.DIV(message) if ok: ok_button = html.BUTTON("Ok") self.panel <= html.P() self.panel <= html.DIV(ok_button, style={"text-align": "center"}) ok_button.bind("click", lambda ev: self.remove()) if remove_after: if not isinstance(remove_after, (int, float)): raise TypeError("remove_after should be a number, not " + str(remove_after.__class__.__name__)) window.setTimeout(self.close, remove_after * 1000)
async def asker(a, b): # Present the choices as a list with buttons. global n_questions n_questions += 1 buttons = {} def button(the_id, text): buttons[the_id] = lambda _: signal('choice', the_id) return H.BUTTON(T(text), id = the_id) def display_item(item): # Display the item as a list with one criterion and value # per list item. Highlight the criteria value that differ # between the two options. return H.UL([ H.LI([T(name + ': '), (T(value) if a[i] == b[i] else H.STRONG(T(value)))]) for i, (name, value) in enumerate(zip(criterion_names, item))]) document['dm'] <= H.DIV( [H.P(T('Q{}: Which would you prefer?'.format(n_questions))), H.UL([ H.LI([button('option_a', 'Option A'), display_item(a)]), H.LI([button('option_b', 'Option B'), display_item(b)]), H.LI([button('equal', 'Equal'), T('The two options are equally preferable')])])], Class = 'query') for button, callback in buttons.items(): document[button].bind('click', callback) # Wait for the user to click a button. choice = await get_signal('choice') if choice == 'quit': raise Quit() # Replace the buttons with indicators of the user's decision. for button in buttons: document[button].replaceWith(H.SPAN( T('your choice' if button == choice else 'not chosen'), Class = 'chosen' if button == choice else 'not-chosen')) # Return the choice. return dict(option_a = GT, option_b = LT, equal = EQ)[choice]
def go(ev): "actual process: compute clusterings of initial segments" new = float(document["newvalue"].value) if data[-1] >= new: alert( "Please provide the points in increasing order. Last input ignored." ) document['newvalue'].value = "" document[ 'newvalue'].placeholder = "Please input one additional value and submit it" return document['newvalue'].disabled = True document['submitnewbutton'].disabled = True data.append(new) for i in range(nclus - 1, len(data)): b = getJenksBreaks(data[:i], nclus - 1) document['allclus'] <= html.P(t(data, b)) b = getJenksBreaks(data, nclus) document['bestclus'].text = t(data, b)
def exercice_08(): r_value = randint(1, 50) def btn_creates(index): btn = document.select('#request') if btn: btn[0].remove() classes = ( f'btn btn-{choice(["default", "primary", "error"])} btn-ghost') if index == r_value: classes += ' selenium' print('selenium') create_btn('fieldset', 'Botão', classes) document.select_one('.terminal-alert-error').remove() fieldset = document.select_one('fieldset') fieldset <= html.P( 'Encontre a classe .selenium no elementos que estão surgindo') for index in range(0, 51): timer.set_timeout(partial(btn_creates, index), index * 500)
def draw_home(): panel = document["main_panel"] panel <= "Use GeneXpresso search and analysis tools to analyze differences in gene expressions"\ " between DNA microarray datasets. Refer to the User Guide for detailed instructions,"\ " and feel free to contact us at [email protected] if you have any questions or feedback." panel <= html.BR() panel <= html.BR() draw_home1() draw_home2() draw_home_samples('', '') draw_home_title_description() draw_home3() panel <= html.BR() p = html.P("Powered by ") p.style.textAlign = "left" p.style.fontSize = "small" p.style.font = "12px verdana" panel <= p panel <= html.IMG(src="gcp.png", width="150")
def render(self): app = group(html.DIV(), [ html.H1("HI THERE!"), html.H2("GOOD TO SEE YOU!"), html.P("Some things about me:"), html.UL([html.LI("I am"), html.LI("Does this work")]), html.H2("here is a nice little ticker"), TickerWithDescription().render(), TextField("here is a prop being passed").render() ]) return app # app = html.DIV(id="hithere") # # app <= html.H1("hi there", id="what") # thing = group(app, [WithGroups().render()]) # # thing = app # document["root"] <= thing # thid = document["hithere"] # thid.innerHTML = "hedy" # print(document.getElementById("hithere").innerHTML) # document["what"] <= html.H1("buy")
def on_complete(req): document['minha-div'] <= html.P(req.text)