### Sound Creation and Playback Setup Source: https://github.com/brython-dev/brython/blob/master/www/gallery/music/play_song_part.html Decodes an audio buffer, sets up playback parameters like loop start/end times and duration, and initiates playback. It also starts a timer to update the cursor position. ```python def createSoundWithBuffer(blob): def play(buffer): d = buffer.duration Config.dxPerSecond = rule.width / d Config.audioSource.buffer = buffer offset = d * (start.left - rule.left + start.width) / rule.width offset = max(0, offset) length = d * (end.x - start.x - start.width) / rule.width print('song length', format_time(d), 'selection length', format_time(length)) Config.audioSource.loop = True Config.length = length Config.audioSource.loopEnd = offset + length Config.audioSource.loopStart = offset print('loopStart', format_time(offset), 'loopEnd', format_time(Config.audioSource.loopEnd)) Config.startTime = Config.context.currentTime Config.t = offset Config.timer = timer.set_interval(set_cursor, 50) Config.audioSource.start(Config.startTime, offset) set_play() def onload(ev): Config.buffer = ev.target.result Config.context = window.AudioContext.new() Config.audioSource = Config.context.createBufferSource() Config.audioSource.connect(Config.context.destination) Config.context.decodeAudioData(Config.buffer, play) reader = window.FileReader.new() reader.bind('load', onload) reader.readAsArrayBuffer(Config.blob) ``` -------------------------------- ### Configuration and Control Setup Source: https://github.com/brython-dev/brython/blob/master/www/gallery/music/play_song_part.html Sets up the positions and dimensions of various UI elements like controls, rule, before, selection, after, start, cursor, and end. It calculates margins and sizes based on window dimensions. ```python class Config: pass def set_controls_position(): controls.left = (left_margin + selection.left + start.width + int(selection.width / 2) - int(controls.width / 2)) load_btn = document["song"] controls = document["controls"] before = document["before"] selection = document["selection"] after = document["after"] start = document["start"] cursor = document["cursor"] end = document["end"] w = window.innerWidth left_margin = int(0.05 * w) rule = document["rule"] rule.top = controls.top + controls.height + 10 rule.height = int(0.3 * window.innerHeight) rule.left = left_margin + start.width rule.width = int(0.8 * w) before.left = 0 selection.left = 0 selection.width = rule.width selection.height = rule.height after.left = rule.left + rule.width start.top = rule.top + rule.height + 5 start.left = left_margin min_start_pos = start.left cursor.left = rule.left cursor.top = rule.y cursor.height = rule.height cursor.width = 3 end.left = rule.left + rule.width end.top = rule.top + rule.height + 5 max_end_pos = end.left ElementMove(end) ElementMove(start) ``` -------------------------------- ### Start Local Brython Development Server Source: https://github.com/brython-dev/brython/blob/master/CONTRIBUTING.md Run this command in your terminal to start a local server for testing changes. This command is used when Brython is installed directly from the source code. ```bash python3 server.py ``` -------------------------------- ### Install Brython Package Source: https://github.com/brython-dev/brython/blob/master/setup/README.rst Install the Brython package using pip. This is the first step to using Brython. ```bash pip install brython ``` -------------------------------- ### Install Brython Application Locally Source: https://github.com/brython-dev/brython/blob/master/www/doc/en/deploy.md Once installed as a package, users can install the Brython application into a specific directory using this command. This is useful for local testing or deployment. ```console python -m --install ``` -------------------------------- ### start() Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html Begins dispatching messages received on the port. This method is necessary to start message delivery after the port has been created or entangled. ```APIDOC port.start() ``` -------------------------------- ### Example Ajax POST Request Source: https://github.com/brython-dev/brython/blob/master/www/doc/en/browser.ajax.md A practical example demonstrating how to send a POST request with data and handle the response. ```APIDOC ```python from browser import document, ajax def on_complete(req): if req.status == 200 or req.status == 0: document["result"].html = req.text else: document["result"].html = "error " + req.text req = ajax.Ajax() req.bind('complete', on_complete) # send a POST request to the url req.open('POST', url, True) req.set_header('content-type', 'application/x-www-form-urlencoded') # send data as a dictionary req.send({'x': 0, 'y': 1}) ``` ``` -------------------------------- ### Install Brython Distribution Locally Source: https://github.com/brython-dev/brython/blob/master/README.md After installing the Brython package via pip, run this command in a new directory to set up the Brython distribution files locally. This includes brython.js and brython_stdlib.js. ```bash brython-cli install ``` -------------------------------- ### HTML Example with Style Element Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html Demonstrates how to use the style element to apply custom styling to an HTML document. This example styles emphasis text as red and normal text as black. ```html My favorite book

My favorite book of all time has got to be A Cat's Life. It is a book by P. Rahmel that talks about the Felis Catus in modern human society.

``` -------------------------------- ### Dynamic Content Loading and Highlighting Source: https://github.com/brython-dev/brython/blob/master/www/demo.html Manages dynamic content display by loading and showing different example panels. It also highlights the source code of the displayed example using the `highlight` module. ```python from browser import document, html, highlight # create first menu entry def home(ev): global current if current is not None: document[current].style.display = "none" document <= document[current] document["a"+current].style.fontWeight = "normal" example_id = "home" ev.target.style.fontWeight = "bold" document["panel"].clear() document["panel"] <= document[example_id] document[example_id].style.display="block" current = example_id anchor = html.A("Home", Class="menu", href="#", id="ahome") anchor.bind("click", home) document["menu"] <= html.LI(anchor) current = "home" def load_example(ev): global current # remove dialogs for dialog in document.select(".brython-dialog-main"): dialog.remove() if current is not None: document[current].style.display = "none" document <= document[current] document["a"+current].classList.remove("selected") example_id = ev.target.num example = document[example_id] ev.target.classList.add("selected") document["panel"].clear() document["panel"] <= example example.style.display="block" script = example.get(selector="script")[0] src = script.text while src.startswith("\n"): src = src[1:] indent = 0 while src[indent] == ' ': indent += 1 src = "\n".join(line[indent:] for line in src.split("\n")) src = highlight.highlight(src) code_elt = example.get(selector="pre") if code_elt: code_elt[0].html = src.html else: example <= src current = example_id for example in document.get(selector=".example"): # add the Python source inside the example # create a menu entry button = example.get(selector="button")[0] anchor = html.A(button.text, Class="menu", href="#", id="a"+example.id) anchor.num = example.id anchor.bind("click", load_example) document["menu"] <= html.LI(anchor) # hide the element example.style.display = "none" ``` -------------------------------- ### Example: Line Game State Management Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html This example demonstrates using the History API to manage state in a game without full page reloads. It uses pushState and replaceState to update the current coordinate and allows navigation through game states. ```html Line Game - 5

You are at coordinate 5 on the line.

Advance to 6 or retreat to 4?

Your name is : ``` -------------------------------- ### Install Development Requirements with Pipenv Source: https://github.com/brython-dev/brython/blob/master/CONTRIBUTING.md Installs the development requirements for Brython using pipenv. This is the recommended method for setting up the development environment. ```bash $ pipenv install --dev ``` -------------------------------- ### Navigation Toolbar Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html Demonstrates using `a` elements for navigation links within a `nav` element. Includes a placeholder `a` element. ```html

``` -------------------------------- ### Inserted Content - Poor Form Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html Illustrates an example of 'ins' elements crossing paragraph boundaries, considered poor form. ```HTML ``` -------------------------------- ### HTML dl Element: Metadata Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html Example of using dl to mark up metadata, including multiple labels for one value. ```html
Last modified time
2004-12-23T23:33Z
Recommended update interval
60s
Authors
Editors
Robert Rothman
Daniel Jackson
``` -------------------------------- ### Run Brython Development Server Source: https://github.com/brython-dev/brython/blob/master/www/doc/en/dev_env.md Starts the Brython development server on the default port 8000. This server serves files from the 'brython_directory/www' and creates the 'static_doc' folder. ```bash python server.py ``` -------------------------------- ### HTML Microdata Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html An example of HTML using Microdata to express RDF statements about a work, including its title, creator, and different formats. ```html
Title
Just a Geek
By
Wil Wheaton
Format
Print
Ebook
``` -------------------------------- ### Code Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html Demonstrates the 'code' element for marking up computer code fragments. ```HTML fruitdb ``` -------------------------------- ### Multiple Select Element Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html Illustrates an HTML select element configured for multiple option selections. All options are selected by default in this example. ```html ``` -------------------------------- ### Select, Read, and Save Local Files with Brython Source: https://github.com/brython-dev/brython/blob/master/www/demo.html This example demonstrates how to allow users to select a local file, read its content into a textarea, and then save the textarea's content back to a file. It utilizes the DOM File API and data URIs for saving. ```python from browser import bind, window, document load_btn = document["rtfile1"] save_btn = document["save_file"] @bind(load_btn, "input") def file_read(ev): def onload(event): """Triggered when file is read. The FileReader instance is event.target. The file content, as text, is the FileReader instance's "result" attribute.""" document['rt1'].value = event.target.result # display "save" button save_btn.style.display = "inline" # set attribute "download" to file name save_btn.attrs["download"] = file.name # Get the selected file as a DOM File object file = load_btn.files[0] # Create a new DOM FileReader instance reader = window.FileReader.new() # Read the file content as text reader.readAsText(file) reader.bind("load", onload) @bind(save_btn, "mousedown") def mousedown(evt): """Create a "data URI" to set the downloaded file content Cf. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs """ content = window.encodeURIComponent(document['rt1'].value) # set attribute "href" of save link save_btn.attrs["href"] = "data:text/plain," + content ``` -------------------------------- ### Markdown with Executable Python Example Source: https://github.com/brython-dev/brython/blob/master/www/gallery/markdown_exec.html An example of a Markdown string containing an executable Python code block. The `markdown.mark` function processes this string. ```Python from browser import window, document, html, highlight, markdown example = """Here is a simple example: ```exec from browser import alert alert("ok") ``` """ # Transform markdown to html and insert in the document html_code, scripts = markdown.mark(example) document["right"] <= html.SPAN(html_code) ``` -------------------------------- ### Brython Specific Rich Operation Example Source: https://github.com/brython-dev/brython/wiki/How-Brython-works An example of a Brython rich operation call for true division, specifying the operation, operands, and an instruction number. ```javascript $B.rich_op('__truediv__', 1, 0, 1) ``` -------------------------------- ### GET Request with Callback Source: https://github.com/brython-dev/brython/blob/master/www/gallery/ajax.html Performs a GET request and logs the response text or 'File not found' if the status is 404. Uses a callback function to process the response. ```python from browser import document, ajax, bind output = document['output'] def show(req): if req.status == 404: log('File not found') else: log(req.text) @bind("#get_test", "click") def get(ev): output.clear() ajax.get("/ajax_get", oncomplete=show, data={"foo": 34}) ``` -------------------------------- ### WebSQL UI Setup Source: https://github.com/brython-dev/brython/blob/master/www/gallery/test_websql.html Sets up the user interface for the WebSQL application, including input fields, buttons for saving and showing messages, and a container for displaying the results table. ```python log('testing db') if db: log('ok') transaction=getattr(db, 'transaction') c=CENTER() c<=LABEL("Input Message Here:") c<=BR() c<=TEXTAREA(id='q', rows=10, cols=60)+BR() c<=BUTTON('Save To WebSQL', id='add', onclick='addMsg()') c<=BUTTON('Show Saved Message', id='Show', onclick='showAll()') c<=BR() c<=HR() tableContainer=DIV(id='tableContainer') tableContainer<=newTable() c<=tableContainer doc<=c ``` -------------------------------- ### Install Brython Application via Pip Source: https://github.com/brython-dev/brython/blob/master/www/doc/en/deploy.md After packaging, users can install your Brython application using the standard pip command. This makes the application available as a Python package. ```console pip install ``` -------------------------------- ### Run Brython Development Server without Docs Source: https://github.com/brython-dev/brython/blob/master/www/doc/en/dev_env.md Starts the Brython development server without creating the 'static_doc' folder. Use this when documentation generation is not needed during testing. ```bash python server.py --no-docs ``` -------------------------------- ### Canvas Pixel Manipulation Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html This example demonstrates how to retrieve pixel data from a canvas, manipulate it, and then put it back onto the canvas. It highlights the relationship between getImageData and putImageData. ```javascript context.putImageData(context.getImageData(x, y, w, h), p, q); ``` -------------------------------- ### Initialize Phaser Game with Brython Source: https://github.com/brython-dev/brython/blob/master/www/gallery/phaser.html Sets up a new Phaser game instance using Brython's JavaScript interop. This snippet demonstrates how to define game configuration, including type, dimensions, physics, and scene callbacks. ```python from browser import window, document import javascript Phaser = window.Phaser class Game(object): def __init__(self): self.game = window.Phaser.Game.new( { 'type': Phaser.AUTO, 'width': 800, 'height': 600, 'physics': { 'default': 'arcade', 'arcade': { 'gravity': {'y': 200} } }, 'scene': { 'preload': self.preload, 'create': self.create } } ) def preload(self, *args): this = javascript.this() this.load.setBaseURL('//labs.phaser.io') this.load.image('sky', 'assets/skies/space3.png') this.load.image('logo', 'assets/sprites/phaser3-logo.png') this.load.image('red', 'assets/particles/red.png') def create(self, *args): this = javascript.this() this.add.image(400, 300, 'sky') particles = this.add.particles('red') emitter = particles.createEmitter({ 'speed': 100, 'scale': {'start': 1, 'end': 0}, 'blendMode': 'NORMAL' }) logo = this.physics.add.image(400, 100, 'logo') logo.setVelocity(100, 200) logo.setBounce(1, 1) logo.setCollideWorldBounds(True) emitter.startFollow(logo) GAME = Game() ``` -------------------------------- ### Pie Chart Example Source: https://github.com/brython-dev/brython/blob/master/www/gallery/brycharts/demo.html Illustrates how to create a pie chart to visualize proportions. Each slice represents a data point. ```python from browser import document, html import brywidgets as ws import brycharts chartbox = ws.RowPanel(className="chartcontainer") document <= chartbox data_pie = { 'labels': ['Red', 'Blue', 'Yellow', 'Green'], 'datasets': [{ 'label': 'Colors', 'data': [300, 50, 100, 40], 'backgroundColor': [ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)' ] }] } chart_pie = brycharts.PieChart(data=data_pie) chart_pie.render(parent=chartbox) ``` -------------------------------- ### HTML Element Example Source: https://github.com/brython-dev/brython/blob/master/www/benchmarks/performance/data/html5lib_spec.html This example demonstrates how to use the element to set the document base URL. Relative links within the document will be resolved against this base URL. ```html This is an example for the <base> element

Visit the archives.

``` -------------------------------- ### Brython Setup for Raphaël Source: https://github.com/brython-dev/brython/blob/master/www/gallery/raphael/playground_py.html Initializes the Raphaël canvas and sets up an event listener for a 'Run' button. This code must be executed in a Brython environment. ```python from browser import document, window paper = window.Raphael("canvas", 640, 480) btn = document["run"] cd = document["code"] def callback(ev): paper.clear() r = paper.rect(0, 0, 640, 480, 10) r.attr({'fill': "#fff", 'stroke":"none"}) exec(cd.value) btn.bind('click', callback) callback(None) ``` -------------------------------- ### Start Python HTTP Server (Default Port) Source: https://github.com/brython-dev/brython/blob/master/releases/README.txt Starts the built-in Python HTTP server on the default port (8000). Use this to serve local files for web development. ```python python -m http.server ```