Python kernel based on xeus

Simple code execution

In [ ]:
a = 3
In [ ]:
a
In [ ]:
b = 89

def sq(x):
    return x * x

sq(b)
In [ ]:
print

Redirected streams

In [ ]:
import sys

print("Error !!", file=sys.stderr)

Error handling

In [ ]:
"Hello"

def dummy_function():
    import missing_module
In [ ]:
dummy_function()

Code completion

press tab to see what is available in sys module

In [ ]:
from sys import

Code inspection

using the question mark

In [ ]:
?print

by pressing shift+tab

In [ ]:
print(

Input support

In [ ]:
name = input('Enter your name: ')
In [ ]:
'Hello, ' + name

Rich representation

In [ ]:
class Person:
    def __init__(self, name="John Doe", address="Paris", picture=""):
        self.name = name
        self.address = address
        self.picture = picture

    def _repr_mimebundle_(self, include=None, exclude=None):
        return {
            "text/html": """<img src="{}">
                  <div><i class='fa-user fa'></i>: {}</div>
                  <div><i class='fa-map fa'></i>: {}</div>""".format(self.picture, self.name, self.address) 
        }
In [ ]:
james = Person("James Smith", "Boston")
display(james)
In [ ]:
marie = Person("Marie Curie", "Poland", "./marie.png")
display(marie)

Matplotlib

In [ ]:
%matplotlib inline
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
In [ ]:
fig = plt.figure()
plt.plot(np.sin(np.linspace(0, 20, 100)));
In [ ]:
%matplotlib widget
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
In [ ]:
fig = plt.figure()
plt.plot(np.sin(np.linspace(0, 20, 100)));

Widgets support

Basic widgets

In [ ]:
from ipywidgets import IntSlider
In [ ]:
slider = IntSlider()
In [ ]:
slider
In [ ]:
slider.value
In [ ]:
slider
In [ ]:
slider.value = 36

Widget interacts

In [ ]:
from ipywidgets import interact
In [ ]:
@interact
def foo(x = ['a', 'b'], n=(1, 10)):
    print(x * n)

Binary buffers support for widgets

In [ ]:
from ipywidgets import Video
video = Video.from_file("Big.Buck.Bunny.mp4")
video

Higher-level widgets libraries support

In [ ]:
import matplotlib
matplotlib.use("agg")

try:
    from urllib.request import urlretrieve
except ImportError:
    from urllib import urlretrieve
import os

import itk

from itkwidgets import view

# Download data
file_name = '005_32months_T2_RegT1_Reg2Atlas_ManualBrainMask_Stripped.nrrd'
if not os.path.exists(file_name):
    url = 'https://data.kitware.com/api/v1/file/564a5b078d777f7522dbfaa6/download'
    urlretrieve(url, file_name)

image = itk.imread(file_name)
view(image)

IPython.display module

In [ ]:
from IPython.display import clear_output, display, update_display
from time import sleep

Update display

In [ ]:
class Square:
    color = 'PeachPuff'
    def _repr_html_(self):
        return '''
        <div style="background: %s; width: 200px; height: 100px; border-radius: 10px;">
        </div>''' % self.color
square = Square()

display(square, display_id='some-square')
In [ ]:
square.color = 'OliveDrab'
update_display(square, display_id='some-square')

Clear output

In [ ]:
print("hello")
sleep(3)
clear_output()             # will flicker when replacing "hello" with "goodbye"
print("goodbye")
In [ ]:
print("hello")
sleep(3)
clear_output(wait=True)   # prevents flickering
print("goodbye")

Display classes

In [ ]:
from IPython.display import HTML
HTML('''
        <div style="background: aliceblue; width: 200px; height: 100px; border-radius: 10px;">
        </div>''')
In [ ]:
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
In [ ]:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 
\end{eqnarray}""")
In [ ]:
from IPython.display import SVG
SVG(url='https://jupyter.org/assets/main-logo.svg')
In [ ]:
from IPython.display import SVG
SVG(filename='./logo.svg')
In [ ]:
from time import sleep
from IPython.display import ProgressBar

for i in ProgressBar(10):
    sleep(0.1)
In [ ]:
from IPython.display import JSON
JSON(['foo', {'bar': ('baz', None, 1.0, 2)}], metadata={}, expanded=True, root='test')
In [ ]:
from IPython.display import GeoJSON
GeoJSON(
  data={
      "type": "Feature",
      "geometry": {
          "type": "Point",
          "coordinates": [11.8, -45.04]
      }
  }, url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
  layer_options={
      "basemap_id": "celestia_mars-shaded-16k_global",
      "attribution" : "Celestia/praesepe",
      "tms": True,
      "minZoom" : 0,
      "maxZoom" : 5
  }
)