def test_dom_create(self): print(html().documentElement) print(html().URL) somebody = document.createElement('sometag') print(str(somebody)) comm = document.createComment('hi there here is a comment') print(comm) print(html().createElement('sometag'))
def test_domonic_render(self): test = html( head( meta(_charset="utf-8"), # meta(**{"http-equiv": "X-UA-Compatible"},, _content="IE=edge"), title("eventual.technology"), meta(_name="viewport", _content="width=device-width, initial-scale=1"), meta(_name="description", _content="eventual technology"), meta(_name="keywords", _content="website, html5, javascript, python, software, aws"), meta(_name="author", _content="eventual.technology"), meta(_property="og:title", _content="eventual technology"), meta(_property="og:image", _content=""), meta(_property="og:url", _content=""), meta(_property="og:site_name", _content="eventual.technology"), meta(_property="og:description", _content=""), meta(_name="twitter:title", _content="eventual technology"), meta(_name="twitter:image", _content=""), meta(_name="twitter:url", _content="eventual.technology"), meta(_name="twitter:card", _content="") ), body( header( h1(a(_href="mailto:[email protected]")), h2("07535784121") ), footer( img(_class="logo", _src="static/img/logo.svg", _alt="eventual technology") ) ) ) # print(render(test)) pass
def test_dom_querySelector(self): dom1 = html( div( div( div( div( div( div( div( div(_id="thing"), span(_id="fun"), div("asdfasdf", div(), div("yo"), _class="test this thing"))))))))) result = dom1.querySelector('#thing') # print('--') print("RESULT>>>>>", result) # print('--') result = dom1.querySelector('span') # print('--') print("RESULT>>>>>", result) result = dom1.querySelector('.test') # print('--') print("RESULT>>>>>", result) result = dom1.getElementsByClassName('this') # print('--') print("RESULT>>>>>", result) pass
def test_dom(self): # test div html and innerhtml update content sometag = div("asdfasdf", div(), div("yo"), _id="someid") self.assertEqual(sometag.tagName, 'div') self.assertEqual( str(sometag), '<div id="someid">asdfasdf<div></div><div>yo</div></div>') sometag.html('test') self.assertEqual(str(sometag), '<div id="someid">test</div>') sometag.innerHTML = 'test2' self.assertEqual(str(sometag), '<div id="someid">test2</div>') # same test on body tag bodytag = body("test", _class="why") self.assertEqual(str(bodytag), '<body class="why">test</body>') # print(bodytag) bodytag.html("bugs bunny") self.assertEqual(str(bodytag), '<body class="why">bugs bunny</body>') # print('THIS:',bodytag) # sometag.innerText() print(sometag.getAttribute('_id')) self.assertEqual(sometag.getAttribute('_id'), 'someid') print(sometag.getAttribute('id')) self.assertEqual(sometag.getAttribute('_id'), 'someid') mydiv = div("I like cake", div(_class='myclass').html(div("1"), div("2"), div("3"))) print(mydiv) # print(sometag.innerText()) # print(sometag.nodeName) # assert(sometag.nodeName, 'DIV') # TODO - i checked one site in chrome, was upper case. not sure if a standard? print(sometag.setAttribute('id', 'newid')) print(sometag) print(sometag.lastChild) print(sometag.hasChildNodes) # print('>>',sometag.textContent()) # TODO - will have a think. either strip or render tagless somehow sometag.removeAttribute('id') print(sometag) sometag.appendChild(footer('test')) print(sometag) print(sometag.children) print(sometag.firstChild) htmltag = html() print(htmltag) htmltag.write('sup!') htmltag.className = "my_cool_css" print(htmltag) print('-END-')
async def world(request): # check the diffs against our diff map return response.html( str( html( head(), body( link(_rel="stylesheet", _type="text/css", _href=CDN_CSS.BOOTSTRAP_4), str(World(request))))))
def test_dQuery_serialize(self): page = html( form( select(_name="single", ).html(option("Single", _selected=True), option("Single2")), br(), select(_name="multiple", _multiple="multiple").html( option("Multiple", _selected="selected"), option("Multiple2"), option("Multiple3", _selected="selected")), input(_type="text", _id="lname", _name="lname"))) º(page) print(º('form').serialize())
def test_dom_events(self): print(html().documentElement) print(html().URL) site = html() somebody = document.createElement('div') site.appendChild(somebody) print(site) def test(evt, *args, **kwargs): print('test ran!') print(evt) print(evt.target) site.addEventListener('click', test) somebody.addEventListener('anything', test) print(site.listeners) # site.removeEventListener('click', test) # print( site.listeners ) site.dispatchEvent(Event('click')) somebody.dispatchEvent(Event('anything'))
def test_dQuery_text(self): page = html( form( select(_name="single", ).html(option("a", _selected=True), option("b")), ), div('hi'), div(span('there'))) º(page) assert º('div').text() == ['hi', 'there'] º('div').text('test') assert º('div').text() == ['test', 'test'] assert str( page ) == '<html><form><select name="single"><option selected="True">a</option><option>b</option></select></form><div>test</div><div>test</div></html>'
def _write_html(self): # Load the css style style_css_path = Path(__file__).parent.joinpath('style.css') with open(style_css_path) as f: style_css_string = "".join(f.readlines()) # Create the root HTML and head doc = html(_lang="en", _dir="ltr") doc.append( head( meta(_charset="utf-8"), title(self.title), link(_href="https://fonts.gstatic.com", _rel="preconnect"), link( _href= "https://fonts.googleapis.com/css2?family=Roboto&display=swap", _rel="stylesheet"), style(style_css_string), script( _type="text/javascript", _src= "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" ), script( '"MathJax.Hub.Config({' 'config: ["MMLorHTML.js"],' 'jax: ["input/TeX", "output/HTML-CSS", "output/NativeMML"],' 'extensions: ["tex2math.js", "tex2jax.js", MathMenu.js", "MathZoom.js"],' '"HTML-CSS": { availableFonts: ["TeX"] }' '});")', _type="text/x-mathjax-config"))) # Create the body tag body_tag = body( div( h1(self.title, _id="title"), h4("Name: ______________________", _id="name"), _id="header", ), hr()) # Create empty problems tag and # Iterate through list of elements problems_tag = div(_id="problems") for elem in self.prob_list: problems_tag.append(elem.get_html_tag()) # Insert the tags respectively body_tag.append(problems_tag) doc.append(body_tag) return doc
def test_dom_normalize(self): dom1 = html() wrapper = dom1.createElement("div") wrapper.appendChild(dom1.createTextNode("Part 1 ")) wrapper.appendChild(dom1.createTextNode("Part 2 ")) wrapper.appendChild("Part 3 ") print('--') print(dom1) print('--') print(len(wrapper.childNodes)) # 2 wrapper.normalize() print(len(wrapper.childNodes)) # 1 print(wrapper.childNodes[0].textContent) # "Part 1 Part 2 " pass
def test_dom_contains(self): site = html() somebody = document.createElement('div') site.appendChild(somebody) print(site) another_div = div() print(site.contains(somebody)) another_div = div() print(site.contains(another_div)) another_div = document.createElement('div') print(site.contains(another_div)) third_div = document.createElement('div') another_div.appendChild(third_div) site.appendChild(another_div) print(site.contains(third_div))
def test_dom_getElementById(self): dom1 = html( div( div( div( div( div( div( div( div("asdfasdf", div(), div("yo"), _id="test"))))))))) result = dom1.getElementById('test') print('--') print(result) print('--') pass
def test_dQuery_hello(self): d = html(head(body(li(_class='things'), div(_id="test")))) º(d) print('---** -') print(º('#test')) print('---** -') print(º('.things')) print('---** -') print('a::') a = º('<div class="test2"></div>') print(a) print('b::') b = º('#test').append(a) print(b) print(d) pass
def test_dom_remove(self): dom1 = html( div( div( div( div( div( div( div( div("asdfasdf", div(), div("yo"), _id="test"))))))))) result = dom1.getElementById('test') print("owner:", result.ownerDocument) result.remove() print(result) print('--') print(dom1) print('--') pass
async def play(request): jquery = script(_src="https://code.jquery.com/jquery-3.5.1.min.js") request.ctx.session['game'] = None game = Game(request) request.ctx.session['game'] = asdict(game.state) board = main(game.heading, *[''.join([str(el) for el in row]) for row in game.grid], Game.js_code, _id="gameboard", _style=f"width:{TILE_SIZE*SIZE}px;") return response.html( str( html( head( jquery, link(_rel="stylesheet", _type="text/css", _href=CDN_CSS.MVP), link(_rel="stylesheet", _type="text/css", _href=CDN_CSS.BALLOON)), body(str(board)))))
def getAccountSummaryStrs(accountSummary: AccountSummary): retStrs = dict() dom = body() if (accountSummary.name == "Total"): allAccounts = True else: allAccounts = False if (allAccounts): dom.appendChild(h1(f"Summary for all Accounts\n")) else: dom.appendChild(h1(f"Summary for Account: {accountSummary.name}\n")) dom.appendChild(h2(f"Account Owner: {accountSummary.owner}\n")) summary = table() summary.appendChild(tr(td("Date account opened"),td(f"{accountSummary.dateOpened.date()}"))) summary.appendChild(tr(td("Total cash invested in account"),td(f"£{accountSummary.totalCashInvested:,.0f}"))) summary.appendChild(tr(td("Total Dividends re-invested in account"),td(f"£{accountSummary.totalDiviReInvested:,.0f}"))) summary.appendChild(tr(td("Total invested in securities"), td(f"£{accountSummary.totalInvestedInSecurities:,.0f}"))) summary.appendChild(tr(td("Total current market value"), td(f"£{accountSummary.totalMarketValue:,.0f}"))) summary.appendChild(tr(td("Cash Balance"), td(f"£{accountSummary.cashBalance:,.0f}"))) if (accountSummary.totalOtherAccounts > 0): summary.appendChild(tr(td("Total held in other accounts"), td(f"£{accountSummary.totalOtherAccounts:,.0f}"))) summary.appendChild(tr(td("Total Account Value"), td(f"£{accountSummary.totalValue():,.0f}"))) summary.appendChild(tr(td("Paper Capital Gain"), td(f"£{accountSummary.totalPaperGainForTax:,.0f} ({accountSummary.totalPaperGainForTaxPerc():0.2f}%)"))) summary.appendChild(tr(td("Realised Capital gain"), td(f"£{accountSummary.totalRealisedGain():,.0f}"))) summary.appendChild(tr(td("Total Capital gain"), td(f"£{accountSummary.totalRealisedGain()+accountSummary.totalPaperGainForTax:,.0f}"))) summary.appendChild(tr(td("Total Dividends"), td(f"£{accountSummary.totalDividends():,.0f}"))) summary.appendChild(tr(td("Avg Dividend Yield"), td(f"{mean(accountSummary.dividendYieldByYear.values()) if len(accountSummary.dividendYieldByYear) > 0 else 0:,.0f}%"))) summary.appendChild(tr(td("Total Income"), td(f"£{accountSummary.totalIncome():,.0f}"))) summary.appendChild(tr(td("Avg Income Yield"), td(f"{accountSummary.avgIncomeYield():.2f}%"))) summary.appendChild(tr(td("Avg Total Yield"), td(f"{accountSummary.avgTotalYield():.2f}%"))) summary.appendChild(tr(td("Total Divi + Income"), td(f"£{accountSummary.totalIncome() + accountSummary.totalDividends():,.0f}"))) summary.appendChild(tr(td("Total Fees paid"), td(f"£{accountSummary.totalFees():,.0f}"))) summary.appendChild(tr(td("Total Dealing costs"), td(f"£{accountSummary.totalDealingCosts():,.0f}"))) summary.appendChild(tr(td("Total Return (Paper gain, dividends paid, realised gain, less fees and costs)"),td(f"£{accountSummary.totalGainLessFees():,.0f} ({accountSummary.totalGainPerc():,.0f}%)"))) summary.appendChild(tr(td("Current Return of investments (Market value less Cash invested)"), td(f"£{accountSummary.totalGainFromInvestments():,.0f} ({accountSummary.totalGainFromInvPerc():0.2f}%)"))) summary.appendChild(tr(td("Average return per year"),td(f"£{accountSummary.avgReturnPerYear():,.0f}"))) dom.appendChild(summary) dom.appendChild(h2("Tax liability")) currentTaxYear = getTaxYear(datetime.now()) lastTaxYear = getTaxYear(datetime.now() - timedelta(weeks=52)) if len(accountSummary.mergedAccounts) == 0: #Single account accounts = [accountSummary] else: accounts = accountSummary.mergedAccounts for yr in [lastTaxYear, currentTaxYear]: dom.appendChild(h3(f"Tax Year {yr}")) tx = table() tx.appendChild(tr(th(' Account '),th(' Capital Gain '),th(' Taxable CG '),th(' CG Tax '),th(' CGT Rem Allowance '), th(' Divi '),th(' Taxable Divi '),th(' Divi Tax '),th(' Divi All Rem '),th(' Income '),th(' Income Tax '))) totalCG = Decimal(0.0) totalTaxableCG = Decimal(0.0) totalCGT = Decimal(0.0) totalDivi = Decimal(0.0) totalTaxableDivi = Decimal(0.0) totalDiviTax = Decimal(0.0) totalIncome = Decimal(0.0) totalIncomeTax = Decimal(0.0) for account in accounts: band = account.taxBandByYear.get(yr, 'lower') cg = account.realisedGainForTaxByYear.get(yr, Decimal(0.0)) if len(account.realisedGainForTaxByYear) > 0 else Decimal(0.0) totalCG += cg taxablecg = account.taxableCG(yr) totalTaxableCG += taxablecg cgt = account.calcCGT(band, yr) totalCGT += cgt divi = account.dividendsByYear.get(yr, Decimal(0.0)) totalDivi += divi taxableDivi = account.taxableDivi(yr) totalTaxableDivi += taxableDivi diviTax = account.calcDividendTax(band, yr) totalDiviTax += diviTax income = account.totalIncomeByYear(yr) totalIncome += income incomeTax = account.calcIncomeTax(band, yr) totalIncomeTax += incomeTax accountLocation = f"./{account.name}-Summary.html#Tax%20Liability" tx.appendChild(tr(td(a(f"{account.name}", _href=accountLocation)),td(f"£{cg:,.0f}"), td(f"£{taxablecg:,.0f}"), td(f"£{cgt:,.0f}"), td("-"), td(f"£{divi:,.0f}"), td(f"£{taxableDivi:,.0f}"), td(f"£{diviTax:,.0f}"), td("-"), td(f"£{income:,.0f}"), td(f"£{incomeTax:,.0f}"), )) #Note: Use last account processed to get remaining allowance info tx.appendChild(tr(td("Total"), td(f"£{totalCG:,.0f}"), td(f"£{totalTaxableCG:,.0f}"), td(f"£{totalCGT:,.0f}"), td(f"£{account.getRemainingCGTAllowance(totalTaxableCG):,.0f}"), td(f"£{totalDivi:,.0f}"), td(f"£{totalTaxableDivi:,.0f}"), td(f"£{totalDiviTax:,.0f}"), td(f"£{account.getRemainingDiviAllowance(totalTaxableDivi):,.0f}"), td(f"£{totalIncome:,.0f}"), td(f"£{totalIncomeTax:,.0f}"), )) dom.appendChild(tx) dom.appendChild(h2("Statistics By Investment Type")) dom.appendChild(h3("Fund values and returns (including other acccounts)")) fs = table() funds = accountSummary.fundTotals isTotalAcc = len(accountSummary.mergedAccounts) > 0 totalAccountValue = accountSummary.totalValue() if (totalAccountValue == 0): totalAccountValue = Decimal(1.0) if isTotalAcc: fs.appendChild(tr(th('Type'),th('Total Invested'),th('Total Market Value'),th('%Account'), ''.join([f'{th(a(acc.name, _href="./"+acc.name+"-Summary.html#Statistics%20By%20Investment%20Type"))}' for acc in accountSummary.mergedAccounts]), th('Avg Fees'),th('Avg Ret'),th('3yr Ret'),th('5yr Ret'))) else: fs.appendChild(tr(th('Type'),th('Total Invested'),th('Total Market Value'),th('%Account'),th('Avg Fees'),th('Avg Ret'),th('3yr Ret'),th('5yr Ret'))) totInvested = Decimal(0.0) totValue = Decimal(0.0) totfees = 0.0 totRet = 0.0 tot3yrRet = 0.0 tot5yrRet = 0.0 totStocks = Decimal(0.0) totBonds = Decimal(0.0) totCash = Decimal(0.0) totGold = Decimal(0.0) portPerc = accountSummary.portfolioPerc for typ, fund in funds.items(): if isTotalAcc: accFunds = (f"{acc.fundTotals[typ].totalValue if typ in acc.fundTotals else 0:,.0f}" for acc in accountSummary.mergedAccounts) fs.appendChild(tr(td(typ.name),td(f"£{fund.totalInvested:,.0f}"), td(f"£{fund.totalValue:,.0f}"),td(f"{100*fund.totalValue/totalAccountValue:0.2f}%"), ''.join([f"{td(acc)}" for acc in accFunds]), td(f"{fund.fees:0.2f}%"), td(f"{fund.actualReturn:0.2f}%"), td(f"{fund.return3Yr:0.2f}%"), td(f"{fund.return5Yr:0.2f}%") )) else: fs.appendChild(tr(td(typ.name),td(f"£{fund.totalInvested:,.0f}"), td(f"£{fund.totalValue:,.0f}"),td(f"{100*fund.totalValue/totalAccountValue:0.2f}%"), td(f"{fund.fees:0.2f}%"), td(f"{fund.actualReturn:0.2f}%"), td(f"{fund.return3Yr:0.2f}%"), td(f"{fund.return5Yr:0.2f}%") )) totInvested += fund.totalInvested totValue += fund.totalValue val = float(fund.totalValue) totfees += fund.fees * val totRet += fund.actualReturn * val tot3yrRet += fund.return3Yr * val tot5yrRet += fund.return5Yr * val if (fund.isStockType()): totStocks += fund.totalValue elif (fund.isBondType()): totBonds += fund.totalValue elif (fund.isCashType()): totCash += fund.totalValue elif (fund.isGoldType()): totGold += fund.totalValue totValue = totValue if totValue else Decimal(1.0) tot = float(totValue) if isTotalAcc: accTots = (f"{acc.totalValue():,.0f}" for acc in accountSummary.mergedAccounts) fs.appendChild(tr(td("Overall"),td(f"£{totInvested:,.0f}"), td(f"£{totValue:,.0f}"),td(f"{100*totValue/totalAccountValue:0.02f}%"), ''.join([f'{td(accTot)}' for accTot in accTots]), td(f"{totfees/tot:0.02f}%"), td(f"{totRet/tot:0.02f}%"), td(f"{tot3yrRet/tot:0.02f}%"), td(f"{tot5yrRet/tot:0.02f}%") )) else: fs.appendChild(tr(td("Overall"),td(f"£{totInvested:,.0f}"), td(f"£{totValue:,.0f}"),td(f"{100*totValue/totalAccountValue:0.02f}%"), td(f"{totfees/tot:0.02f}%"), td(f"{totRet/tot:0.02f}%"), td(f"{tot3yrRet/tot:0.02f}%"), td(f"{tot5yrRet/tot:0.02f}%") )) dom.appendChild(fs) dom.appendChild(h3("Portfolio Percentages and guardrails")) fs = table() fs.appendChild(tr(th('Type'),th(' Total Market Value '),th(' Portfolio% '),th(' Min% '),th(' Ideal%' ),th(' Max%' ),th(' Buy / (Sell) '))) stocksPerc = 100*totStocks/totalAccountValue min = int(portPerc['stocks_min']) max = int(portPerc['stocks_max']) ideal = int(portPerc['stocks_ideal']) buy = '' if stocksPerc <= min: buy = f"£{(ideal-stocksPerc)*totalAccountValue/100:,.0f}" elif stocksPerc >= max: buy = f"(£{(stocksPerc-ideal)*totalAccountValue/100:,.0f})" fs.appendChild(tr(td("Stocks"),td(f"£{totStocks:,.0f}"),td(f"{stocksPerc:0.02f}%"), td(f"{min:0.01f}%"), td(f"{ideal:0.01f}%"), td(f"{max:0.01f}%"), td(buy) )) bondsPerc = 100*totBonds/totalAccountValue min = int(portPerc['bonds_min']) max = int(portPerc['bonds_max']) ideal = int(portPerc['bonds_ideal']) buy = '' if bondsPerc <= min: buy = f"£{(ideal-bondsPerc)*totalAccountValue/100:,.0f}" elif bondsPerc >= max: buy = f"(£{(bondsPerc-ideal)*totalAccountValue/100:,.0f})" fs.appendChild(tr(td("Bonds"),td(f"£{totBonds:,.0f}"),td(f"{bondsPerc:0.02f}%"), td(f"{min:0.01f}%"), td(f"{ideal:0.01f}%"), td(f"{max:0.01f}%"), td(buy) )) cashPerc = 100*totCash/totalAccountValue min = int(portPerc['cash_min']) max = int(portPerc['cash_max']) ideal = int(portPerc['cash_ideal']) buy = '' if cashPerc <= min: buy = f"£{(ideal-cashPerc)*totalAccountValue/100:,.0f}" elif cashPerc >= max: buy = f"(£{(cashPerc-ideal)*totalAccountValue/100:,.0f})" fs.appendChild(tr(td("Cash"),td(f"£{totCash:,.0f}"),td(f"{cashPerc:0.02f}%"), td(f"{min:0.01f}%"), td(f"{ideal:0.01f}%"), td(f"{max:0.01f}%"), td(buy) )) goldPerc = 100*totGold/totalAccountValue min = int(portPerc['gold_min']) max = int(portPerc['gold_max']) ideal = int(portPerc['gold_ideal']) buy = '' if goldPerc <= min: buy = f"£{(ideal-goldPerc)*totalAccountValue/100:,.0f}" elif cashPerc >= max: buy = f"(£{(goldPerc-ideal)*totalAccountValue/100:,.0f})" fs.appendChild(tr(td("Gold"), td(f"£{totGold:,.0f}"),td(f"{goldPerc:0.02f}%"), td(f"{min:0.01f}%"), td(f"{ideal:0.01f}%"), td(f"{max:0.01f}%"), td(buy) )) fs.appendChild(tr(td("Total"), td(f"£{totGold+totCash+totBonds+totStocks:,.0f}"),td(f"{goldPerc+cashPerc+bondsPerc+stocksPerc:0.02f}%") )) dom.appendChild(fs) if (len(accountSummary.totalByInstitution) > 0): dom.appendChild(h3("Value by Institution")) fi = table() totVal = Decimal(0.0) val = Decimal(0.0) fi.appendChild(tr(th('Institution'),th('Value'),th('Total Account %') )) for inst, val in accountSummary.totalByInstitution.items(): fi.appendChild(tr(td(inst),td(f"£{val:,.0f}"), td(f"{100.0*float(val/totalAccountValue):0.02f}%") )) totVal += val fi.appendChild(tr(td("Total"),td(f"£{totVal:,.0f}"), td(f"{100.0*float(totVal/totalAccountValue):0.02f}%") )) dom.appendChild(fi) dom.appendChild(h3("Fund Risks")) fr = table() fr.appendChild(tr(th('Type'),th('Alpha'),th('Beta'),th('Sharpe'),th('Std Dev'),th('Maturity yrs') )) totAlpha = 0.0 totBeta = 0.0 totSharpe = 0.0 totSD = 0.0 totalNonShareVal = 0.0 totMat = 0.0 totMatVal = 0.0 for typ, fund in funds.items(): if (typ != FundType.SHARE): totPerc = fund.alpha3Yr+fund.beta3Yr+fund.sharpe3Yr+fund.stdDev3Yr fr.appendChild(tr(td(typ.name),td(f"{fund.alpha3Yr:0.02f}"), td(f"{fund.beta3Yr:0.02f}"),td(f"{fund.sharpe3Yr:0.02f}"), td(f"{fund.stdDev3Yr:0.02f}", td(f"{fund.maturity:0.02f}")) )) val = float(fund.totalValue) if (totPerc > 0): totalNonShareVal += val totAlpha += fund.alpha3Yr * val totBeta += fund.beta3Yr * val totSharpe += fund.sharpe3Yr * val totSD += fund.stdDev3Yr * val if (fund.maturity > 0): totMat += fund.maturity * val totMatVal += val if totalNonShareVal == 0: totalNonShareVal = 1.0 if totMatVal == 0: totMatVal = 1.0 fr.appendChild(tr(td("Overall"),td(f"{totAlpha/totalNonShareVal:0.02f}"), td(f"{totBeta/totalNonShareVal:0.02f}"), td(f"{totSharpe/totalNonShareVal:0.02f}"),td(f"{totSD/totalNonShareVal:0.02f}"),td(f"{totMat/totMatVal:0.02f}") )) dom.appendChild(fr) dom.appendChild(h3("Geographical Spread")) fr = table() fr.appendChild(tr(th('Type'),th('Americas'),th('Americas-Emerging'),th('Asia'),th('Asia-Emerging'),th('UK'),th('Europe'),th('Europe-Emerging'),th('Total') )) totamer = 0.0 totamerem = 0.0 totasia = 0.0 totasiaem = 0.0 totuk = 0.0 toteuro = 0.0 toteuroem = 0.0 totVal = 0.0 for typ, fund in funds.items(): totPerc = fund.americas + fund.americasEmerging + fund.asia + fund.asiaEmerging + fund.uk + fund.europe + fund.europeEmerging fr.appendChild(tr(td(typ.name),td(f"{fund.americas:0.02f}%"), td(f"{fund.americasEmerging:0.02f}%"), td(f"{fund.asia:0.02f}%"),td(f"{fund.asiaEmerging:0.02f}%"), td(f"{fund.uk:0.02f}%"), td(f"{fund.europe:0.02f}%"),td(f"{fund.europeEmerging:0.02f}%"), td(f"{totPerc:0.02f}%") )) if (totPerc != 0): val = float(fund.totalValue) totamer += (fund.americas * val) totamerem += (fund.americasEmerging * val) totasia += (fund.asia * val) totasiaem += (fund.asiaEmerging * val) totuk += (fund.uk * val) toteuro += (fund.europe * val) toteuroem += (fund.europeEmerging * val) totVal += val totVal = totVal if totVal else 1.0 totPerc = (totamer + totamerem + totasia + totasiaem + totuk + toteuro + toteuroem)/totVal fr.appendChild(tr(td("Overall"),td(f"{totamer/totVal:0.02f}%"), td(f"{totamerem/totVal:0.02f}%"), td(f"{totasia/totVal:0.02f}%"),td(f"{totasiaem/totVal:0.02f}%"),td(f"{totuk/totVal:0.02f}%"), td(f"{toteuro/totVal:0.02f}%"),td(f"{toteuroem/totVal:0.02f}%"), td(f"{totPerc:0.02f}%") )) dom.appendChild(fr) dom.appendChild(h3("Fund Diversity")) fr = table() fr.appendChild(tr(th('Type'),th('Cyclical'),th('Sensitive'),th('Defensive'),th('Total') )) totCyc = 0.0 totSens = 0.0 totDef = 0.0 totVal = 0.0 for typ, fund in funds.items(): if (typ != FundType.SHARE): totPerc = fund.cyclical+fund.sensitive+fund.defensive fr.appendChild(tr(td(typ.name),td(f"{fund.cyclical:0.02f}%"), td(f"{fund.sensitive:0.02f}%"),td(f"{fund.defensive:0.02f}%"),td(f"{totPerc:0.02f}%"))) if (totPerc != 0): val = float(fund.totalValue) totCyc += fund.cyclical * val totSens += fund.sensitive * val totDef += fund.defensive * val totVal += val totVal = totVal if totVal else 1.0 totPerc = (totCyc + totSens + totDef)/totVal fr.appendChild(tr(td("Overall"),td(f"{totCyc/totVal:0.2f}%"), td(f"{totSens/totVal:0.2f}%"),td(f"{totDef/totVal:0.2f}%"),td(f"{totPerc:0.2f}%"))) dom.appendChild(fr) startYear = accountSummary.dateOpened endYear = datetime.now(timezone.utc) + timedelta(days=365) # Make sure we have this tax year # endYear = datetime.now(timezone.utc) procYear = startYear dom.appendChild(h2("Yearly breakdown")) byYear = table() byYear.appendChild(tr(th('Year'),th('Cash In'),th('Cash Out'),th('Agg Invested'),th('Gain Realised'),th('Dividends'),th('Yield%'),th('Dealing Costs'),th('Fees'))) while procYear < endYear: taxYear = getTaxYear(procYear) yearRow = tr() yearRow.appendChild(td(f"{taxYear}")) yearRow.appendChild(td(f"£{accountSummary.cashInByYear.get(taxYear, Decimal(0.0)):,.0f}")) yearRow.appendChild(td(f"£{accountSummary.cashOutByYear.get(taxYear, Decimal(0.0)):,.0f}")) yearRow.appendChild(td(f"£{accountSummary.aggInvestedByYear.get(taxYear, Decimal(0.0)):,.0f}")) yearRow.appendChild(td(f"£{accountSummary.realisedGainForTaxByYear.get(taxYear, Decimal(0.0)):,.0f}")) yearRow.appendChild(td(f"£{accountSummary.dividendsByYear.get(taxYear, Decimal(0.0)):,.0f}")) yearRow.appendChild(td(f"{accountSummary.dividendYieldByYear.get(taxYear, Decimal(0.0)):,.0f}%")) yearRow.appendChild(td(f"£{accountSummary.dealingCostsByYear.get(taxYear, Decimal(0.0)):,.0f}")) yearRow.appendChild(td(f"£{accountSummary.feesByYear.get(taxYear, Decimal(0.0)):,.0f}")) byYear.appendChild(yearRow) procYear += timedelta(days=365) dom.append(byYear) getSecurityStrs(accountSummary, allAccounts, dom, retStrs) dom.appendChild(h2(f"Payments by Tax Year")) for yr in [lastTaxYear, currentTaxYear]: dom.appendChild(h3(f"Tax Year {yr}")) dom.appendChild(h3(f"Dividend Payments")) txnTable = table() if (allAccounts): txnTable.appendChild(tr(th('Account'),th('Date'),th('Txn Type'), th('Desc'),th('Amount'))) else: txnTable.appendChild(tr(th('Date'),th('Txn Type'), th('Desc'),th('Amount'))) total = Decimal(0) txns = sorted(accountSummary.dividendTxnsByYear[yr] if yr in accountSummary.dividendTxnsByYear else list(), key= lambda txn: txn.date) for txn in txns: row = tr() if (allAccounts): accountLocation = f"./{txn.accountName}-Summary.html#Dividend%20Payments" row.appendChild(td(a(f"{txn.accountName}", _href=accountLocation))) row.appendChild(td(f"{txn.date}")) row.appendChild(td(f"{txn.type}")) row.appendChild(td(f"{txn.desc}")) row.appendChild(td(f"£{txn.credit if txn.credit != 0 else -txn.debit:0.2f}")) total += txn.credit txnTable.appendChild(row) txnTable.appendChild(tr(td(" "),td("Total"),td(" "),td(f"£{total:,.0f}"))) dom.append(txnTable) dom.appendChild(h3(f"Income Payments")) txnTable = table() if (allAccounts): txnTable.appendChild(tr(th('Account'),th('Date'),th('Txn Type'), th('Desc'),th('Amount'))) else: txnTable.appendChild(tr(th('Date'),th('Txn Type'), th('Desc'),th('Amount'))) total = Decimal(0) txns = list(accountSummary.incomeTxnsByYear[yr]) if yr in accountSummary.incomeTxnsByYear else list() txns.extend(accountSummary.interestTxnsByYear[yr] if yr in accountSummary.interestTxnsByYear else list()) txns = sorted(txns, key= lambda txn: txn.date) for txn in txns: row = tr() if (allAccounts): accountLocation = f"./{txn.accountName}-Summary.html#Income%20Payments" row.appendChild(td(a(f"{txn.accountName}", _href=accountLocation))) row.appendChild(td(f"{txn.date}")) row.appendChild(td(f"{txn.type}")) row.appendChild(td(f"{txn.desc}")) row.appendChild(td(f"£{txn.credit if txn.credit != 0 else -txn.debit:0.2f}")) total += txn.credit txnTable.appendChild(row) txnTable.appendChild(tr(td(" "),td("Total"),td(" "),td(f"£{total:,.0f}"))) dom.append(txnTable) dom.append(h2('Account transactions')) txnTable = table() if (allAccounts): txnTable.appendChild(tr(th('Date'),th('Account'),th('Txn Type'), th('Desc'),th('Amount'),th('Balance'))) else: txnTable.appendChild(tr(th('Date'),th('Txn Type'), th('Desc'),th('Amount'),th('Balance'))) for txn in accountSummary.transactions: detailLocation = f"./{txn.accountName}/{txn.symbol}.txt" row = tr() row.appendChild(td(f"{txn.date}")) if (allAccounts): accountLocation = f"./{txn.accountName}-Summary.html#Income%20Payments" row.appendChild(td(a(f"{txn.accountName}", _href=accountLocation))) row.appendChild(td(f"{txn.type}")) row.appendChild(td(f"{txn.desc}")) row.appendChild(td(f"£{txn.credit if txn.credit != 0 else -txn.debit:0.2f}")) row.appendChild(td(f"£{txn.accountBalance:0.2f}")) txnTable.appendChild(row) dom.appendChild(txnTable) ht = html(meta(_charset='UTF-8')) ht.append(dom) retStrs[f"{accountSummary.name}-Summary.html"] = f"{ht}" return retStrs
setInterval(function () { // get position of div var x = parseInt(p1.style.left, 10), y = parseInt(p1.style.top, 10); // update position // left/right if (keys[keyCodes.left]) { x -= 1; } else if (keys[keyCodes.right]) { x += 1; } // up/down if (keys[keyCodes.up]) { y -= 1; } else if (keys[keyCodes.down]) { y += 1; } // set div position p1.style.left = x + 'px'; p1.style.top = y + 'px'; }, 1/30); """)) render(html(head(classless_css, jquery, code), body(game)), 'sf2.html')
from domonic.javascript import * from domonic.html import * from domonic.components import Websocket from domonic.events import * from domonic.CDN import * # generate the webpage that makes the socket connection back to our server page = html( head(title("Test Capturing Browser Events")), script(_src="https://code.jquery.com/jquery-3.5.1.min.js"), body( Websocket(drag_events=True, hashchange_events=True, wheel_events=True, clipboard_events=True), # canvas(_id="canvas", _width="500", _height="500"), div(_class="dropzone", ).html( div( _id="draggable", _draggable="true", _ondragstart="event.dataTransfer.setData('text/plain',null)", ).html("This div is draggable")), div(_class="dropzone"), )) # render the page you need to visit while the socket server is running render(page, 'events.html') # run an update loop from here. somedata = {} # def update(): # somedata = {}
import sys sys.path.insert(0, '../..') from domonic.html import * from domonic.javascript import * from domonic.CDN import * from domonic.aframe import * from domonic.constants.color import * _scripts = script(""" //alert('hi world!') """) spheres = [] for loop in range(1000): rand = lambda x: -(x) + Math.random() * (x * 2) r = Math.random() * 2 s = sphere(_position=f"{rand(20)} {rand(20)} {rand(20)}", _radius=f"{r}", _color=Color.random_hex()) spheres.append(s) _scene = scene(*spheres, sky(_color=Color.paleskyblue)) _webpage = html(head(), body(script(_src=CDN_JS.AFRAME_1_2), str(_scene), _scripts)) render(_webpage, 'hello2.html')
page = html( # make a canvas style(''' canvas { background: #131c35 linear-gradient(black,#192853, black); display:block; position:absolute; top:0; left:0; right:0; bottom:0; } ''', _type="text/css"), body(input(_placeholder="localhost:1", _id="host"), input(_placeholder="port", _id="port"), input(_placeholder="password", _id="password"), script(_scr=CDN_JS.JQUERY_3_5_1), canvas(_id="canvas", _width="1280", _height="800")), # listen on the socket and call draw when we get a message script(''' //const socket = new WebSocket('ws://0.0.0.0:5555'); const socket = new WebSocket('ws://domain.com:5560'); // your nginx should listen on 5560 and forward to 5555 socket.onmessage = function(event) { data = JSON.parse(event.data); draw(); }; // TOOD - dont send json. just data with seperator function stringify_object(object, depth=0, max_depth=2) { // change max_depth to see more levels, for a touch event, 2 is good if (depth > max_depth) return 'Object'; const obj = {}; for (let key in object) { let value = object[key]; if (value instanceof Node) // specify which properties you want to see from the node value = {id: value.id}; else if (value instanceof Window) value = 'Window'; else if (value instanceof Object) value = stringify_object(value, depth+1, max_depth); if(key=="originalEvent"){ // note im stripping this one off continue; } obj[key] = value; } return depth? obj: JSON.stringify(obj); } $(canvas).ready(function() { $("canvas").on('mousedown', function(event){ socket.send( stringify_object(event) ); }); $("canvas").on('mouseup', function(event){ socket.send( stringify_object(event) ); }); $("body").on("keydown", function(event){ socket.send( stringify_object(event) ); }) $("body").on("keyup", function(event){ socket.send( stringify_object(event) ); }) $("canvas").on("mousemove", function(event){ //socket.send( stringify_object(event) ); }) }); '''), # draw the data script(''' var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var WIDTH=canvas.width; var HEIGHT=canvas.height; function resizeCanvas(){ canvas.width = window.innerWidth; canvas.height = window.innerHeight; WIDTH=canvas.width; HEIGHT=canvas.height; } function animate() { socket.send('!'); // send any old message to trigger socket response. so i can control the framerate // draw(); } function draw() { console.log(data); data = data.flat(); // context.clearRect(0, 0, WIDTH, HEIGHT); // context.globalCompositeOperation = "source-over"; var i, r; for(i = 0; i < data.length; i++ ) { // point = data[i]; // context.save(); // context.translate(point.x,point.y); // context.rotate( point.rotation ); // context.restore(); r = data[i]; drawRect(r[0],r[1],r[2],r[3],r[4]); } } function drawRect(x,y,width,height,color){ context.beginPath(); context.fillStyle = color.substr(0,7); context.fillRect(x, y, width, height); //context.lineWidth = 2; //context.strokeStyle = '#000'; //context.stroke(); context.fill(); } var intID; function setFramerate(val){ clearInterval(this.intID) this.intID = setInterval( function(){ animate(); }, 1000/val ); // window.requestAnimationFrame(animate); } setFramerate(60); resizeCanvas(); '''))
page = html( head(title("Conway's Game of Life")), style(''' canvas { display:block; position:absolute; top:0; left:0; right:0; bottom:0; } ''', _type="text/css"), body( canvas(_id="canvas", _width="500", _height="500"), # listen on the socket and call draw when we get a message script(''' const socket = new WebSocket('ws://0.0.0.0:5555'); socket.onmessage = function(event) { grid = JSON.parse(event.data); draw(); }; socket.send('!'); '''), # draw the grid script(''' var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var WIDTH=canvas.width; var HEIGHT=canvas.height; var CELLSIZE = 5; function resizeCanvas(){ canvas.width = window.innerWidth; canvas.height = window.innerHeight; WIDTH=canvas.width; HEIGHT=canvas.height; } function animate() { socket.send('!'); // send any old message to trigger socket response. so i can control the framerate // draw(); } function draw() { context.clearRect(0, 0, WIDTH, HEIGHT); //console.log(grid); var x, y; for(x = 0; x < grid.length; x++) { row = grid[x]; for(y = 0; y<row.length; y++) { //drawRect(x*CELLSIZE,y*CELLSIZE, grid[x][y]); drawCell(x*CELLSIZE,y*CELLSIZE, grid[x][y]); } } socket.send('!'); } /* function drawRect(x, y, state){ context.beginPath(); if(state === 1){ context.fillStyle = 'black'; }else{ context.fillStyle = 'white'; } //context.lineWidth = 2; //context.strokeStyle = '#000'; //context.stroke(); //context.stroke(); //context.rect(x, y, CELLSIZE, CELLSIZE); context.fillRect(x, y, CELLSIZE, CELLSIZE); context.fill(); } */ function drawCell(x, y, state){ context.beginPath(); if(state === 1){ context.fillStyle = 'black'; }else{ context.fillStyle = 'white'; } context.arc(x, y, 1, 0, 2 * Math.PI, false); context.lineWidth = 2; context.strokeStyle = '#000'; context.stroke(); context.fill(); } /* var intID; function setFramerate(val){ clearInterval(this.intID) this.intID = setInterval( function(){ animate(); }, 1000/val ); // window.requestAnimationFrame(animate); } setFramerate(60); resizeCanvas(); */ ''')))
import sys sys.path.insert(0, '../..') import os from domonic.html import * from domonic.aframe import * from domonic.CDN import * _scripts = script(""" //alert('yo world!') """) _scene = scene( box(_position="-1 0.5 -3", _rotation="0 45 0", _color="#4CC3D9"), sphere(_position="0 1.25 -5", _radius="1.25", _color="#EF2D5E"), cylinder(_position="1 0.75 -3", _radius="0.5", _height="1.5", _color="#FFC65D"), plane(_position="0 0 -4", _rotation="-90 0 0", _width="4", _height="4", _color="#7BC8A4"), sky(_color="#ECECEC")) _webpage = html( head(), body(link(_rel="stylesheet", _type="text/css", _href=CDN_CSS.MARX), script(_src=CDN_JS.AFRAME_1_2), str(_scene), _scripts)) render(_webpage, 'hello.html')
from domonic.html import * from domonic.CDN import CDN_CSS MARGIN = 3 # set some data keyboard = [['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['shift', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'backspace'], ['numerals', 'comma', 'space', 'period', 'enter']] # create a template key_tmpl = lambda key: div(_style=f"display:inline;margin:{MARGIN}px;").html( button(key, _style="background-color:white;color:black;")) # generate keyboard kb = div() for rows in keyboard: row = div(_style=f"margin:{MARGIN*2}px;") for key in rows: row.appendChild(key_tmpl(key)) kb.appendChild(str(row)) # render webpage css = link(_rel="stylesheet", _href=CDN_CSS.MARX) render(html(head(css), body(kb, _style="background-color:#d1d5db;")), "keyboard.html")
page = html( # make a canvas style(''' canvas { background: #131c35 linear-gradient(black,#192853, black); display:block; position:absolute; top:0; left:0; right:0; bottom:0; } ''', _type="text/css"), body(canvas(_id="canvas", _width="1000", _height="600")), # listen on the socket and call draw when we get a message script(''' const socket = new WebSocket('ws://0.0.0.0:5555'); socket.onmessage = function(event) { atoms = JSON.parse(event.data); draw(); }; '''), # draw the atoms script(''' var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var WIDTH=canvas.width; var HEIGHT=canvas.height; function resizeCanvas(){ canvas.width = window.innerWidth; canvas.height = window.innerHeight; WIDTH=canvas.width; HEIGHT=canvas.height; } function animate() { socket.send('!'); // send any old message to trigger socket response. so i can control the framerate // draw(); } function draw() { context.clearRect(0, 0, WIDTH, HEIGHT); var i, point; for(i = 0; i < atoms.length; i++ ) { point = atoms[i]; context.save(); context.translate(point.x,point.y); context.rotate( point.rotation ); context.restore(); // window.console.log(point); drawAtom(point,i); } } function drawAtom(p,i){ context.beginPath(); context.fillStyle = 'white'; context.arc(p.x, p.y, p.z, 0, 2 * Math.PI, false); // var gradient = context.createRadialGradient(p.x, p.y, p.width*p.z, p.x, p.y, 0); // gradient.addColorStop( 0, 'black' ); // gradient.addColorStop( 1, 'white' ); // context.fillStyle = gradient; context.lineWidth = 2; context.strokeStyle = '#000'; context.stroke(); context.fill(); } var intID; function setFramerate(val){ clearInterval(this.intID) this.intID = setInterval( function(){ animate(); }, 1000/val ); // window.requestAnimationFrame(animate); } setFramerate(60); resizeCanvas(); '''))
from domonic.html import * classless_css = link(_rel="stylesheet", _href="https://unpkg.com/marx-css/css/marx.min.css") jquery = script(_src="https://code.jquery.com/jquery-3.5.1.min.js") code = script(''' function add(){ $('#results').html( Number($('#a').val()) + Number($('#b').val()) )}; ''') calc = article( div(label('Add numbers:'), input(_id='a'), span('+'), input(_id='b'), button('Calculate', _id="calculate_button", _onclick="add();"), div('Result:', div(_id="results")))) render(html(head(classless_css, jquery, code), body(calc)), 'calc.html') # // TODO - serve # from domonic.terminal import ls, touch # import time # ls( "| open .") # touch( "1.hi") # time.sleep(1) # touch( "2.how") # time.sleep(1) # touch( "3.are") # time.sleep(1) # touch( "4.you")
app = Sanic(name='✊✋✌') app.static('/assets', './assets') # create a template page_wrapper = lambda content: html( head( script(_src="https://code.jquery.com/jquery-3.5.1.min.js"), link(_rel="stylesheet", _type="text/css", _href=CDN_CSS.MVP), script(_type="text/javascript").html(""" document.addEventListener('keydown', send_keypress); function send_keypress(event) { var choice = ""; if( event.key == 'r' || event.key == 'R' ){ choice="✊"; } if( event.key == 'p' || event.key == 'P' ){ choice="✋"; } if( event.key == 's' || event.key == 'S' ){ choice="✌"; } $.get('/move?choice='+choice, function(response){ $("#game").html(response); }); }; """)), body(str(content))) choices = ['✊', '✋', '✌'] def get_choice():
output = html( head( title("domonic", _id="title"), link( _rel="stylesheet", _type="text/css", _href= "https://cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.css" ), style(css), script(js), ), body( header( a( img(_width="149", _height="149", _src= "https://github.blog/wp-content/uploads/2008/12/forkme_right_white_ffffff.png?resize=149%2C149", _class="attachment-full size-full", _alt="Fork me on GitHub", _style="float:right;", **{'_data-recalc-dims': '1'}), _href=repo, )), article( h1("domonic!", _class="titleStyle"), # h2(":)"),h3(":)"),h4(":)"),h5(":)"),h6(":)"), div("This webpage was created with ", a("domonic", _href=repo)), code("python3 -m pip install domonic"), # code("pip3 install domonic"), a(" go to the repo >>", _href=repo, _style="font-size:15px;"), br(), br(), nav("Nav:", a("Go back to here again", _href=""), "|", a("repo", _href=repo)), br(), img(_src="http://placekitten.com/400/400", _alt="some text", _title="some text"), br(), ol(''.join([f'{li("some item")}' for thing in range(5)])), table(tr(th("A"), th("B"), th("C")), tr(td("test"), td("test"), td("test")), tr(td("test"), td("test"), td("test")), _style="width:100%"), span("spaf", _style="color:fuchsia")), section( figure( img(_src="http://placekitten.com/200/200", _alt="some text", _title="some text"), br(), ), figcaption("a cat"), br(), dl(dt("coffee"), dd("hot drink"), dt("milk"), dd("cold drink")), form( label("this is a label:", _for="some_input"), br(), input(_id="some_input", _name="some_input", _type="text", _placeholder="cool"), br(), input(" yer or no?", _type="radio"), br(), input(_value="send", _type="button"), comment("This webpage was created with 'domonic'"), )), iframe("test", _data_test="test", _src="https://www.google.com"), noscript("Your browser does not support javascript"), footer( address("Where: Earth"), select(option("test1", _value="test1"), option("test2", _value="test2"), option("test3", _value="test3")), button("cool button"), sup("sup!"), sub("sub!"), textarea("test"), details(summary(small("domonic 2020.")))), p(var("a"), "(", var("b"), "+", var("c"), ")=", var("ab"), "+", var("ac")), tbody("test"), thead("test"), tfoot("test"), aside("test"), hgroup("test"), pre("test"), em("test"), s("test"), cite("test"), q("test"), dfn("test"), abbr("test"), var("test"), samp("test"), kbd("test"), i("test"), b("test"), u("test"), mark("test"), ruby("test"), rt("test"), rp("test"), bdi("test"), bdo("test"), ins("test"), video("test"), audio("test"), canvas("test"), caption("test"), colgroup("test"), fieldset("test"), legend("test"), datalist("test"), optgroup("test"), option("test"), output("test"), # s***e ----- progress("test"), meter("test"), menu("test"), font("test", **{"_data-test": "test"}), # map("test"), # del("test"), # object("test"), # time("test"), ), _lang="")
def test_domonic_x3dom(self): x3dom_test = html( head( meta(**{"_http-equiv": "X-UA-Compatible"}, _content="IE=edge"), title("My first X3DOM page"), script(_type='text/javascript', _src='https://www.x3dom.org/download/x3dom.js'), script(""" $(document).ready(function(){ var screenshotCount = 0; //Every time the user clicks on the 'take screenhot' button $("#btnTakeScreenshot").on("click", function() { //Get data url from the runtime var imgUrl = document.getElementById("canvas").runtime.getScreenshot(); //Create preview image... var newScreenshotImage = document.createElement('img'); newScreenshotImage.src = imgUrl; newScreenshotImage.id = "screenshot_" + screenshotCount; $('#screenshotPreviews').append(newScreenshotImage); //...and download link var newScreenshotDownloadLink = document.createElement('a'); newScreenshotDownloadLink.href = imgUrl; newScreenshotDownloadLink.download = "screenshot_" + screenshotCount + ".png"; newScreenshotDownloadLink.innerHTML = "Speichern"; $('#screenshotPreviews').append(newScreenshotDownloadLink); screenshotCount++; $('#screenshotCount').html(screenshotCount); }); }); """), link(_rel='stylesheet', _type='text/css', _href='https://www.x3dom.org/download/x3dom.css')), body( h1("Animate Objects with X3DOM!"), p("Learn how to animate objects."), x3d(_width='500px', _height='400px').append( scene( transform(_DEF="ball").append( shape(appearance(material(_diffuseColor='1 0 0')), sphere())), timeSensor(_DEF="time", _cycleInterval="2", _loop="true"), PositionInterpolator(_DEF="move", _key="0 0.5 1", _keyValue="0 0 0 0 3 0 0 0 0"), Route(_fromNode="time", _fromField="fraction_changed", _toNode="move", _toField="set_fraction"), Route(_fromNode="move", _fromField="value_changed", _toNode="ball", _toField="translation"))))) render(str(x3dom_test), "sphere_test.html")
def __str__(self): # classless_css = link(_rel="stylesheet", _href="https://unpkg.com/marx-css/css/marx.min.css") if self.dark_mode: classless_css = link(_rel="stylesheet", _href=CDN_CSS.WATER_LATEST) else: classless_css = link(_rel="stylesheet", _href=CDN_CSS.MARX) jquery = script(_src="https://code.jquery.com/jquery-3.5.1.min.js") code = script(''' $(document).on( "click", ".close", function() { var _id = $(this).data('ref'); $('#'+_id).css("display","none"); }); $(document).on( "click", ".open", function() { var _id = $(this).data('ref'); $('#'+_id).css("display","block"); }); // When the user clicks anywhere outside of the modal, close it //window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none"; // } //} // pass an ElementID and an endpoint to redraw that div with the endpoints response window.redraw = function( _id, endpoint ){ $.get( endpoint, function( data ) { window.console.log(data) $( "#"+_id ).html( $(data).html() ); }); } ''') styles = style(''' .domonic-container { padding:20px; } .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4); } .modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; } .btn-sm { font-size:10px; padding: 0px; padding-left: 2px; padding-right: 2px; } .del { background-color:red; } .go { background-color:green; } ''') dm_button = div( link(_rel="stylesheet", _href=CDN_CSS.BALLOON), a("🌕🌖🌗🌘🌑🌒🌓🌔🌕🌑", **{"_aria-label":"Join the battle. Do you want DarkMode or not?"}, **{"_data-balloon-pos":"down"}, _href="/toggle_dark_mode" ) ) dm_button.style.textAlign = "center" return str( html( '<!DOCTYPE HTML>', head(classless_css, jquery, code, styles), body( dm_button, div(self.content, _class="domonic-container")) ) )
# <!DOCTYPE html> page = lambda content: html(_lang="en", _class="no-js", _dir="auto").html( head( meta(_charset="UTF-8"), meta(_name="viewport", _content="width=device-width"), title("Unique page title - My Site"), script(''' document.documentElement.classList.remove('no-js'); document.documentElement.classList.add('js'); ''', _type="module"), link(_rel="stylesheet", _href="/assets/css/styles.css"), meta(_name="description", _content="Page description"), meta(_property="og:title", _content="Unique page title - My Site"), meta(_property="og:description", _content="Page description"), meta(_property="og:image", _content=f"https://www.{DOMAIN}.com/image.jpg"), meta(_property="og:image:alt", _content="Image description"), meta(_property="og:locale", _content="en_GB"), meta(_property="og:type", _content="website"), meta(_name="twitter:card", _content="summary_large_image"), meta(_property="og:url", _content=f"https://www.{DOMAIN}.com/page"), link(_rel="canonical", _href=f"https://www.{DOMAIN}.com/page"), link(_rel="icon", _href="/favicon.ico"), link(_rel="icon", _href="/favicon.svg", _type="image/svg+xml"), link(_rel="apple-touch-icon", _href="/apple-touch-icon.png"), link(_rel="manifest", _href="/my.webmanifest"), meta(_name="theme-color", _content="#FF00FF")), body(content, script(_src="/assets/js/script.js", _type="module"))) content = div("Hello World!")