Published unlisted
Edited
Mar 3, 2020
3 stars
Insert cell
Insert cell
Insert cell
jupyterlab_services = require('https://unpkg.com/@jupyterlab/services@5.0.0-alpha.0/dist/dist/index.js')
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
output('3*3')
Insert cell
Insert cell
viewof outputTest = output(`[(j*j,j^2) for j in range(15)]`)
Insert cell
outputTest
Insert cell
Insert cell
pythonCell()
Insert cell
Insert cell
viewof pCellVersion = pythonCell(
{
value: `import sys
print(sys.version)`
},
true
)
Insert cell
viewof pCellFor = pythonCell({
value: `for i in range(5):
print(i)`
})
Insert cell
viewof pCellGraphic = pythonCell(
{
value: `import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png')
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()

# fig.savefig("test.png")
plt.show()`
},
true
)
Insert cell
Insert cell
viewof ra = reactiveOutput(
[],
`a = 50
a`,
(_, a) => Number(a),
`del a`
)
Insert cell
viewof rb = reactiveOutput(
[],
`b = 5
b`,
(_, b) => Number(b),
`del b`
)
Insert cell
viewof rc = reactiveOutput(
[ra, rb],
`c = ${ra} + ${rb}
c`,
(_, c) => Number(c),
`del c`
)
Insert cell
Insert cell
Insert cell
async function output(code, div0, throwOnError) {
function escape(str) {
const escapeRE = /</g;
return str.replace(escapeRE, '&lt;');
}
function appendMIME(content, div) {
for (const mime in content.data) {
switch (mime) {
case 'text/plain': {
const result = content.data['text/plain'];
div.appendChild(html`<pre>${escape(result)}`);
div.value = result;
break;
}
case 'text/html': {
const result = html`<div>${content.data['text/html']}`;
div.appendChild(result);
div.value = result;
break;
}
case 'image/svg+xml': {
const image = html`<img src="data:${mime},${encodeURIComponent(
content.data[mime]
)}">`;
div.appendChild(image);
break;
}
case 'image/png':
case 'image/jpeg': {
const image = html`<img src="data:${mime};base64,${content.data[mime]}">`;
div.appendChild(image);
break;
}
default: {
div.appendChild(
html`<pre style="max-height: 500px; overflow-y: auto;">${escape(
JSON.stringify(content)
)}`
);
div.value = content;
}
}
}
}

const future = session.kernel.requestExecute({ code }, true);
const div = div0 || html``;
let errored;
future.onIOPub = msg => {
console.log(msg);
switch (msg.msg_type) {
case 'execute_input': {
div.value = undefined;
break;
}
case 'execute_result': {
appendMIME(msg.content, div);
break;
}
case 'stream': {
if (msg.content.name === 'stdout') {
div.appendChild(
html`<pre style="max-height: 500px; overflow-y: auto;">${escape(
msg.content.text
)}`
);
div.value = msg.content.text;
} else {
div.appendChild(
html`<pre style="max-height: 500px; overflow-y: auto;">${escape(
JSON.stringify(msg.content)
)}`
);
div.value = msg.content;
}
break;
}
case 'display_data': {
appendMIME(msg.content, div);
break;
}
case 'error': {
if (throwOnError) {
errored = msg.content;
}
// firefox with 75ch drops characters to the next line randomly...
div.appendChild(
html`<pre style="width: 75ch; white-space: pre-wrap; word-break: break-all;">${msg.content.traceback.map(
s => {
return ansi_up.ansi_to_html(s);
}
)}`
);
div.value = msg.content;
// div.appendChild(
// html`<pre style="color:red;">${
// msg.content.ename
// }: ${msg.content.evalue.replace('<', '&lt;')}`
// );
break;
}
default: {
//
// div.value = msg;
}
}
};
await future.done;
if (errored)
throw new Error(
`${errored.ename}: ${errored.evalue}, traceback: ${errored.traceback}`
);
return div;
}
Insert cell
async function reactiveOutput(inputs, code, transform, cleanup) {
// idea for better scoping: wrap the body in a function and then delete it
// const formatBody = body.trim().split('\n').filter().map((l,i,a) => (i !== a.length ? ' ' : ' return ')+l).join('\n')
// const code = `def ${DOM.uid('jupyter_cell').id.replace('-','_')}():
// ${formatBody}`
const out = await output(code, false, true);
if (cleanup) {
const cleanupFuture = session.kernel.requestExecute(
{ code: cleanup },
true
);
let errored;
cleanupFuture.onIOPub = msg => {
if (msg.msg_type === 'error') errored = msg.content;
};
await cleanupFuture.done;
if (errored)
throw new Error(
`${errored.ename}: ${errored.evalue}, traceback: ${errored.traceback}`
);
}
const div = html`${out}`;
div.value = transform(inputs, out.value);
return div;
}
Insert cell
CodeMirrorURL = 'https://unpkg.com/codemirror@5/'
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more