In [ ]:
import IPython
IPython.version_info
In [ ]:
%install_ext https://raw.github.com/kikocorreoso/brythonmagic/master/brythonmagic.py
In [ ]:
%load_ext brythonmagic
In [ ]:
%%HTML
<script type="text/javascript" src="https://brython.info/src/brython_dist.js"></script>
In [ ]:
%%brython -c my_container
# 假如要列出所產生的 html 則使用 -p
from browser import doc, html
# This will be printed in the js console of your browser
print('Hello world!')
# This will be printed in the container div on the output below
doc["my_container"] <= html.P("文字位於 div 標註內",
style = {"backgroundColor": "cyan"})
In [ ]:
%%brython
from browser import alert
alert('Hello world!, Welcome to the brythonmagic!')
In [ ]:
%%brython -c simple_example
from browser import doc, html
for i in range(10):
doc["simple_example"] <= html.P(i)
In [ ]:
%%brython -c table
from browser import doc, html
table = html.TABLE()
for i in range(10):
color = ['cyan','#dddddd'] * 5
table <= html.TR(
html.TD(str(i+1) + ' x 2 =', style = {'backgroundColor':color[i]}) +
html.TD((i+1)*2, style = {'backgroundColor':color[i]}))
doc['table'] <= table
In [ ]:
%%brython -c canvas_example
from browser.timer import request_animation_frame as raf
from browser.timer import cancel_animation_frame as caf
from browser import doc, html
from time import time
import math
# First we create a table to insert the elements
table = html.TABLE(cellpadding = 10)
btn_anim = html.BUTTON('Animate', Id="btn-anim", type="button")
btn_stop = html.BUTTON('Stop', Id="btn-stop", type="button")
cnvs = html.CANVAS(Id="raf-canvas", width=256, height=256)
table <= html.TR(html.TD(btn_anim + btn_stop) +
html.TD(cnvs))
doc['canvas_example'] <= table
# Now we access the canvas context
ctx = doc['raf-canvas'].getContext( '2d' )
# And we create several functions in charge to animate and stop the draw animation
toggle = True
def draw():
t = time() * 3
x = math.sin(t) * 96 + 128
y = math.cos(t * 0.9) * 96 + 128
global toggle
if toggle:
toggle = False
else:
toggle = True
ctx.fillStyle = 'rgb(200,200,20)' if toggle else 'rgb(20,20,200)'
ctx.beginPath()
ctx.arc( x, y, 6, 0, math.pi * 2, True)
ctx.closePath()
ctx.fill()
def animate(i):
global id
id = raf(animate)
draw()
def stop(i):
global id
print(id)
caf(id)
doc["btn-anim"].bind("click", animate)
doc["btn-stop"].bind("click", stop)
In [ ]:
%%HTML
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.js"></script>
In [ ]:
%%brython -c simple_d3
from browser import window, document, html
from javascript import JSObject
d3 = window.d3
container = JSObject(d3.select("#simple_d3"))
svg = container.append("svg").attr("width", 100).attr("height", 100)
circle1 = svg.append("circle").style("stroke", "gray").style("fill", "gray").attr("r", 40)
circle1.attr("cx", 50).attr("cy", 50).attr("id", "mycircle")
circle2 = svg.append("circle").style("stroke", "gray").style("fill", "white").attr("r", 20)
circle2.attr("cx", 50).attr("cy", 50)
def over(ev):
document["mycircle"].style.fill = "blue"
def out(ev):
document["mycircle"].style.fill = "gray"
document["mycircle"].bind("mouseover", over)
document["mycircle"].bind("mouseout", out)
In [ ]:
%%brython -c manipulating
from browser import document, html
def hide(ev):
divs = document.get(selector = 'div.input')
for div in divs:
div.style.display = "none"
def show(ev):
divs = document.get(selector = 'div.input')
for div in divs:
div.style.display = "inherit"
document["manipulating"] <= html.BUTTON('Hide code cells', Id="btn-hide")
document["btn-hide"].bind("click", hide)
document["manipulating"] <= html.BUTTON('Show code cells', Id="btn-show")
document["btn-show"].bind("click", show)
In [ ]:
from random import randint
n = 100
x = [randint(0,800) for i in range(n)]
y = [randint(0,600) for i in range(n)]
r = [randint(25,50) for i in range(n)]
red = [randint(0,255) for i in range(n)]
green = [randint(0,255) for i in range(n)]
blue = [randint(0,255) for i in range(n)]
In [ ]:
%%brython -c other_d3 -i x y r red green blue
from browser import window, document, html
d3 = window.d3
WIDTH = 800
HEIGHT = 600
container = d3.select("#other_d3")
svg = container.append("svg").attr("width", WIDTH).attr("height", HEIGHT)
class AddShapes:
def __init__(self, x, y, r, red, green, blue, shape = "circle", interactive = True):
self.shape = shape
self.interactive = interactive
self._color = "gray"
self.add(x, y, r, red, green, blue)
def over(self, ev):
self._color = ev.target.style.fill
document[ev.target.id].style.fill = "white"
def out(self, ev):
document[ev.target.id].style.fill = self._color
def add(self, x, y, r, red, green, blue):
for i in range(len(x)):
self.idx = self.shape + '_' + str(i)
self._color = "rgb(%s,%s,%s)" % (red[i], green[i], blue[i])
shaped = svg.append(self.shape).style("stroke", "gray").style("fill", self._color).attr("r", r[i])
shaped.attr("cx", x[i]).attr("cy", y[i]).attr("id", self.idx)
if self.interactive:
document[self.idx].bind("mouseover", self.over)
document[self.idx].bind("mouseout", self.out)
plot = AddShapes(x, y, r, red, green, blue, interactive = True)
In [ ]:
%%HTML
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js"></script>
In [ ]:
%%brython -c ol_map
# we need to get map png in SSL
# take a look at http://gis.stackexchange.com/questions/83953/openlayer-maps-issue-with-ssl
from browser import document, window
from javascript import JSConstructor, JSObject
## Div layout
document['ol_map'].style.width = "800px"
document['ol_map'].style.height = "400px"
document['ol_map'].style.border = "1px solid black"
OpenLayers = window.OpenLayers
## Map
_map = JSConstructor(OpenLayers.Map)('ol_map')
## Addition of a OpenStreetMap layer
_layer = JSConstructor(OpenLayers.Layer.OSM)( 'Simple OSM map')
_map.addLayer(_layer)
## Map centered on Lon, Lat = (-3.671416, 40.435897) and a zoom = 14
## with a projection = "EPSG:4326" (Lat-Lon WGS84)
_proj = JSConstructor(OpenLayers.Projection)("EPSG:4326")
_center = JSConstructor(OpenLayers.LonLat)(-3.671416, 40.435897)
_center.transform(_proj, _map.getProjectionObject())
_map.setCenter(_center, 10)
## Addition of some points around the defined location
lons = [-3.670, -3.671, -3.672, -3.672, -3.672,
-3.671, -3.670, -3.670]
lats = [40.435, 40.435, 40.435, 40.436, 40.437,
40.437, 40.437, 40.436]
site_points = []
site_style = {}
points_layer = JSConstructor(OpenLayers.Layer.Vector)("Point Layer")
_map.addLayer(points_layer)
for lon, lat in zip(lons, lats):
point = JSConstructor(OpenLayers.Geometry.Point)(lon, lat)
point.transform(_proj, _map.getProjectionObject())
_feat = JSConstructor(OpenLayers.Feature.Vector)(point)
points_layer.addFeatures(_feat)
In [ ]:
%%brython -s styling
from browser import doc, html
# Changing the background color
body = doc[html.BODY][0]
body.style = {"backgroundColor": "#99EEFF"}
# Changing the color of the imput prompt
inps = body.get(selector = ".input_prompt")
for inp in inps:
inp.style = {"color": "blue"}
# Changin the color of the output cells
outs = body.get(selector = ".output_wrapper")
for out in outs:
out.style = {"backgroundColor": "#E0E0E0"}
# Changing the font of the text cells
text_cells = body.get(selector = ".text_cell")
for cell in text_cells:
cell.style = {"fontFamily": """"Courier New", Courier, monospace""",
"fontSize": "20px"}
# Changing the color of the code cells.
code_cells = body.get(selector = ".CodeMirror")
for cell in code_cells:
cell.style = {"backgroundColor": "#D0D0D0"}
In [ ]: