Merge pull request #6843 from minrk/nbformat4-examples

update example notebooks to v4
Thomas Kluyver 11 years ago
commit edc0adb797

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -1,4 +1,157 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Widget related imports\n",
"from IPython.html import widgets\n",
"from IPython.display import display, clear_output, Javascript\n",
"from IPython.utils.traitlets import Unicode\n",
"\n",
"# nbconvert related imports\n",
"from IPython.nbconvert import get_export_names, export_by_name\n",
"from IPython.nbconvert.writers import FilesWriter\n",
"from IPython.nbformat import current\n",
"from IPython.nbconvert.utils.exceptions import ConversionException"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a text Widget without displaying it. The widget will be used to store the notebook's name which is otherwise only available in the front-end."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"notebook_name = widgets.Text()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the current notebook's name by pushing JavaScript to the browser that sets the notebook name in a string widget."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"js = \"\"\"var model = IPython.notebook.kernel.widget_manager.get_model('{model_id}');\n",
"model.set('value', IPython.notebook.notebook_name);\n",
"model.save();\"\"\".format(model_id=notebook_name.model_id)\n",
"display(Javascript(data=js))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"filename = notebook_name.value\n",
"filename"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the widget that will allow the user to Export the current notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"exporter_names = widgets.Dropdown(values=get_export_names(), value='html')\n",
"export_button = widgets.Button(description=\"Export\")\n",
"download_link = widgets.HTML(visible=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Export the notebook when the export button is clicked."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"file_writer = FilesWriter()\n",
"\n",
"def export(name, nb):\n",
" \n",
" # Get a unique key for the notebook and set it in the resources object.\n",
" notebook_name = name[:name.rfind('.')]\n",
" resources = {}\n",
" resources['unique_key'] = notebook_name\n",
" resources['output_files_dir'] = '%s_files' % notebook_name\n",
"\n",
" # Try to export\n",
" try:\n",
" output, resources = export_by_name(exporter_names.value, nb)\n",
" except ConversionException as e:\n",
" download_link.value = \"<br>Could not export notebook!\"\n",
" else:\n",
" write_results = file_writer.write(output, resources, notebook_name=notebook_name)\n",
" \n",
" download_link.value = \"<br>Results: <a href='files/{filename}'><i>\\\"{filename}\\\"</i></a>\".format(filename=write_results)\n",
" download_link.visible = True\n",
" \n",
"def handle_export(widget):\n",
" with open(filename, 'r') as f:\n",
" export(filename, current.read(f, 'json'))\n",
"export_button.on_click(handle_export)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Display the controls."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"display(exporter_names, export_button, download_link)"
]
}
],
"metadata": {
"kernelspec": {
"codemirror_mode": {
@ -9,160 +162,8 @@
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:dc519f61f8a484b3a8f0b05ad1891fad701324c837325b12d31cce4f31647c2f"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Widget related imports\n",
"from IPython.html import widgets\n",
"from IPython.display import display, clear_output, Javascript\n",
"from IPython.utils.traitlets import Unicode\n",
"\n",
"# nbconvert related imports\n",
"from IPython.nbconvert import get_export_names, export_by_name\n",
"from IPython.nbconvert.writers import FilesWriter\n",
"from IPython.nbformat import current\n",
"from IPython.nbconvert.utils.exceptions import ConversionException"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a text Widget without displaying it. The widget will be used to store the notebook's name which is otherwise only available in the front-end."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"notebook_name = widgets.Text()"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the current notebook's name by pushing JavaScript to the browser that sets the notebook name in a string widget."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"js = \"\"\"var model = IPython.notebook.kernel.widget_manager.get_model('{model_id}');\n",
"model.set('value', IPython.notebook.notebook_name);\n",
"model.save();\"\"\".format(model_id=notebook_name.model_id)\n",
"display(Javascript(data=js))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"filename = notebook_name.value\n",
"filename"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the widget that will allow the user to Export the current notebook."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"exporter_names = widgets.Dropdown(values=get_export_names(), value='html')\n",
"export_button = widgets.Button(description=\"Export\")\n",
"download_link = widgets.HTML(visible=False)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Export the notebook when the export button is clicked."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"file_writer = FilesWriter()\n",
"\n",
"def export(name, nb):\n",
" \n",
" # Get a unique key for the notebook and set it in the resources object.\n",
" notebook_name = name[:name.rfind('.')]\n",
" resources = {}\n",
" resources['unique_key'] = notebook_name\n",
" resources['output_files_dir'] = '%s_files' % notebook_name\n",
"\n",
" # Try to export\n",
" try:\n",
" output, resources = export_by_name(exporter_names.value, nb)\n",
" except ConversionException as e:\n",
" download_link.value = \"<br>Could not export notebook!\"\n",
" else:\n",
" write_results = file_writer.write(output, resources, notebook_name=notebook_name)\n",
" \n",
" download_link.value = \"<br>Results: <a href='files/{filename}'><i>\\\"{filename}\\\"</i></a>\".format(filename=write_results)\n",
" download_link.visible = True\n",
" \n",
"def handle_export(widget):\n",
" with open(filename, 'r') as f:\n",
" export(filename, current.read(f, 'json'))\n",
"export_button.on_click(handle_export)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Display the controls."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"display(exporter_names, export_button, download_link)"
],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,141 +1,139 @@
{
"metadata": {
"name": "",
"signature": "sha256:5f38c57d9570e4b6f6edf98c38a7bff81cd16365baa11fd40265f1504bfc008c"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Factoring Polynomials with SymPy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is an example that uses [SymPy](http://sympy.org/en/index.html) to factor polynomials."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.html.widgets import interact\n",
"from IPython.display import display"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from sympy import Symbol, Eq, factor, init_printing\n",
"init_printing(use_latex='mathjax')"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x = Symbol('x')"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def factorit(n):\n",
" display(Eq(x**n-1, factor(x**n-1)))"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice how the output of the `factorit` function is properly formatted LaTeX."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"factorit(12)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"latex": [
"$$x^{12} - 1 = \\left(x - 1\\right) \\left(x + 1\\right) \\left(x^{2} + 1\\right) \\left(x^{2} - x + 1\\right) \\left(x^{2} + x + 1\\right) \\left(x^{4} - x^{2} + 1\\right)$$"
],
"metadata": {},
"output_type": "display_data",
"text": [
" 12 \u239b 2 \u239e \u239b 2 \u239e \u239b 2 \u239e \u239b 4 2 \u239e\n",
"x - 1 = (x - 1)\u22c5(x + 1)\u22c5\u239dx + 1\u23a0\u22c5\u239dx - x + 1\u23a0\u22c5\u239dx + x + 1\u23a0\u22c5\u239dx - x + 1\u23a0"
]
}
],
"prompt_number": 5
},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Factoring Polynomials with SymPy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is an example that uses [SymPy](http://sympy.org/en/index.html) to factor polynomials."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from IPython.html.widgets import interact\n",
"from IPython.display import display"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from sympy import Symbol, Eq, factor, init_printing\n",
"init_printing(use_latex='mathjax')"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = Symbol('x')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def factorit(n):\n",
" display(Eq(x**n-1, factor(x**n-1)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice how the output of the `factorit` function is properly formatted LaTeX."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"interact(factorit, n=(2,40));"
],
"language": "python",
"data": {
"text/latex": [
"$$x^{12} - 1 = \\left(x - 1\\right) \\left(x + 1\\right) \\left(x^{2} + 1\\right) \\left(x^{2} - x + 1\\right) \\left(x^{2} + x + 1\\right) \\left(x^{4} - x^{2} + 1\\right)$$"
],
"text/plain": [
" 12 \u239b 2 \u239e \u239b 2 \u239e \u239b 2 \u239e \u239b 4 2 \u239e\n",
"x - 1 = (x - 1)\u22c5(x + 1)\u22c5\u239dx + 1\u23a0\u22c5\u239dx - x + 1\u23a0\u22c5\u239dx + x + 1\u23a0\u22c5\u239dx - x + 1\u23a0"
]
},
"metadata": {},
"outputs": [
{
"latex": [
"$$x^{21} - 1 = \\left(x - 1\\right) \\left(x^{2} + x + 1\\right) \\left(x^{6} + x^{5} + x^{4} + x^{3} + x^{2} + x + 1\\right) \\left(x^{12} - x^{11} + x^{9} - x^{8} + x^{6} - x^{4} + x^{3} - x + 1\\right)$$"
],
"metadata": {},
"output_type": "display_data",
"text": [
" 21 \u239b 2 \u239e \u239b 6 5 4 3 2 \u239e \u239b 12 11 \n",
"x - 1 = (x - 1)\u22c5\u239dx + x + 1\u23a0\u22c5\u239dx + x + x + x + x + x + 1\u23a0\u22c5\u239dx - x + x\n",
"\n",
"9 8 6 4 3 \u239e\n",
" - x + x - x + x - x + 1\u23a0"
]
}
],
"prompt_number": 6
},
"output_type": "display_data"
}
],
"source": [
"factorit(12)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"data": {
"text/latex": [
"$$x^{21} - 1 = \\left(x - 1\\right) \\left(x^{2} + x + 1\\right) \\left(x^{6} + x^{5} + x^{4} + x^{3} + x^{2} + x + 1\\right) \\left(x^{12} - x^{11} + x^{9} - x^{8} + x^{6} - x^{4} + x^{3} - x + 1\\right)$$"
],
"text/plain": [
" 21 \u239b 2 \u239e \u239b 6 5 4 3 2 \u239e \u239b 12 11 \n",
"x - 1 = (x - 1)\u22c5\u239dx + x + 1\u23a0\u22c5\u239dx + x + x + x + x + x + 1\u23a0\u22c5\u239dx - x + x\n",
"\n",
"9 8 6 4 3 \u239e\n",
" - x + x - x + x - x + 1\u23a0"
]
},
"metadata": {},
"outputs": []
"output_type": "display_data"
}
],
"metadata": {}
"source": [
"interact(factorit, n=(2,40));"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": []
}
]
],
"metadata": {
"signature": "sha256:5f38c57d9570e4b6f6edf98c38a7bff81cd16365baa11fd40265f1504bfc008c"
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,4 +1,162 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import base64\n",
"from __future__ import print_function # py 2.7 compat.\n",
"from IPython.html import widgets # Widget definitions.\n",
"from IPython.utils.traitlets import Unicode # Traitlet needed to add synced attributes to the widget."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a custom widget that allows the user to upload file data to the notebook server. The file data is sent via a statefull `value` attribute of the widget. The widget has an upload failed event that fires in the front-end and is echoed to the back-end using a custom msg."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class FileWidget(widgets.DOMWidget):\n",
" _view_name = Unicode('FilePickerView', sync=True)\n",
" value = Unicode(sync=True)\n",
" filename = Unicode(sync=True)\n",
" \n",
" def __init__(self, **kwargs):\n",
" \"\"\"Constructor\"\"\"\n",
" widgets.DOMWidget.__init__(self, **kwargs) # Call the base.\n",
" \n",
" # Allow the user to register error callbacks with the following signatures:\n",
" # callback()\n",
" # callback(sender)\n",
" self.errors = widgets.CallbackDispatcher(accepted_nargs=[0, 1])\n",
" \n",
" # Listen for custom msgs\n",
" self.on_msg(self._handle_custom_msg)\n",
"\n",
" def _handle_custom_msg(self, content):\n",
" \"\"\"Handle a msg from the front-end.\n",
"\n",
" Parameters\n",
" ----------\n",
" content: dict\n",
" Content of the msg.\"\"\"\n",
" if 'event' in content and content['event'] == 'error':\n",
" self.errors()\n",
" self.errors(self)\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%%javascript\n",
"\n",
"require([\"widgets/js/widget\", \"widgets/js/manager\"], function(widget, manager){\n",
"\n",
" var FilePickerView = widget.DOMWidgetView.extend({\n",
" render: function(){\n",
" // Render the view.\n",
" this.setElement($('<input />')\n",
" .attr('type', 'file'));\n",
" },\n",
" \n",
" events: {\n",
" // List of events and their handlers.\n",
" 'change': 'handle_file_change',\n",
" },\n",
" \n",
" handle_file_change: function(evt) { \n",
" // Handle when the user has changed the file.\n",
" \n",
" // Retrieve the first (and only!) File from the FileList object\n",
" var file = evt.target.files[0];\n",
" if (file) {\n",
"\n",
" // Read the file's textual content and set value to those contents.\n",
" var that = this;\n",
" var file_reader = new FileReader();\n",
" file_reader.onload = function(e) {\n",
" that.model.set('value', e.target.result);\n",
" that.touch();\n",
" }\n",
" file_reader.readAsText(file);\n",
" } else {\n",
"\n",
" // The file couldn't be opened. Send an error msg to the\n",
" // back-end.\n",
" this.send({ 'event': 'error' });\n",
" }\n",
"\n",
" // Set the filename of the file.\n",
" this.model.set('filename', file.name);\n",
" this.touch();\n",
" },\n",
" });\n",
" \n",
" // Register the DatePickerView with the widget manager.\n",
" manager.WidgetManager.register_widget_view('FilePickerView', FilePickerView);\n",
"});"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following shows how the file widget can be used."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"file_widget = FileWidget()\n",
"\n",
"# Register an event to echo the filename when it has been changed.\n",
"def file_loading():\n",
" print(\"Loading %s\" % file_widget.filename)\n",
"file_widget.on_trait_change(file_loading, 'filename')\n",
"\n",
"# Register an event to echo the filename and contents when a file\n",
"# has been uploaded.\n",
"def file_loaded():\n",
" print(\"Loaded, file contents: %s\" % file_widget.value)\n",
"file_widget.on_trait_change(file_loaded, 'value')\n",
"\n",
"# Register an event to print an error message when a file could not\n",
"# be opened. Since the error messages are not handled through\n",
"# traitlets but instead handled through custom msgs, the registration\n",
"# of the handler is different than the two examples above. Instead\n",
"# the API provided by the CallbackDispatcher must be used.\n",
"def file_failed():\n",
" print(\"Could not load file contents of %s\" % file_widget.filename)\n",
"file_widget.errors.register_callback(file_failed)\n",
"\n",
"file_widget"
]
}
],
"metadata": {
"cell_tags": [
[
@ -15,168 +173,8 @@
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:25c43e4f530e049319d587a7e47734cab5b4b4f608f71aa234e821f43076afe8"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"import base64\n",
"from __future__ import print_function # py 2.7 compat.\n",
"from IPython.html import widgets # Widget definitions.\n",
"from IPython.utils.traitlets import Unicode # Traitlet needed to add synced attributes to the widget."
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a custom widget that allows the user to upload file data to the notebook server. The file data is sent via a statefull `value` attribute of the widget. The widget has an upload failed event that fires in the front-end and is echoed to the back-end using a custom msg."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class FileWidget(widgets.DOMWidget):\n",
" _view_name = Unicode('FilePickerView', sync=True)\n",
" value = Unicode(sync=True)\n",
" filename = Unicode(sync=True)\n",
" \n",
" def __init__(self, **kwargs):\n",
" \"\"\"Constructor\"\"\"\n",
" widgets.DOMWidget.__init__(self, **kwargs) # Call the base.\n",
" \n",
" # Allow the user to register error callbacks with the following signatures:\n",
" # callback()\n",
" # callback(sender)\n",
" self.errors = widgets.CallbackDispatcher(accepted_nargs=[0, 1])\n",
" \n",
" # Listen for custom msgs\n",
" self.on_msg(self._handle_custom_msg)\n",
"\n",
" def _handle_custom_msg(self, content):\n",
" \"\"\"Handle a msg from the front-end.\n",
"\n",
" Parameters\n",
" ----------\n",
" content: dict\n",
" Content of the msg.\"\"\"\n",
" if 'event' in content and content['event'] == 'error':\n",
" self.errors()\n",
" self.errors(self)\n",
" "
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%javascript\n",
"\n",
"require([\"widgets/js/widget\", \"widgets/js/manager\"], function(widget, manager){\n",
"\n",
" var FilePickerView = widget.DOMWidgetView.extend({\n",
" render: function(){\n",
" // Render the view.\n",
" this.setElement($('<input />')\n",
" .attr('type', 'file'));\n",
" },\n",
" \n",
" events: {\n",
" // List of events and their handlers.\n",
" 'change': 'handle_file_change',\n",
" },\n",
" \n",
" handle_file_change: function(evt) { \n",
" // Handle when the user has changed the file.\n",
" \n",
" // Retrieve the first (and only!) File from the FileList object\n",
" var file = evt.target.files[0];\n",
" if (file) {\n",
"\n",
" // Read the file's textual content and set value to those contents.\n",
" var that = this;\n",
" var file_reader = new FileReader();\n",
" file_reader.onload = function(e) {\n",
" that.model.set('value', e.target.result);\n",
" that.touch();\n",
" }\n",
" file_reader.readAsText(file);\n",
" } else {\n",
"\n",
" // The file couldn't be opened. Send an error msg to the\n",
" // back-end.\n",
" this.send({ 'event': 'error' });\n",
" }\n",
"\n",
" // Set the filename of the file.\n",
" this.model.set('filename', file.name);\n",
" this.touch();\n",
" },\n",
" });\n",
" \n",
" // Register the DatePickerView with the widget manager.\n",
" manager.WidgetManager.register_widget_view('FilePickerView', FilePickerView);\n",
"});"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following shows how the file widget can be used."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"file_widget = FileWidget()\n",
"\n",
"# Register an event to echo the filename when it has been changed.\n",
"def file_loading():\n",
" print(\"Loading %s\" % file_widget.filename)\n",
"file_widget.on_trait_change(file_loading, 'filename')\n",
"\n",
"# Register an event to echo the filename and contents when a file\n",
"# has been uploaded.\n",
"def file_loaded():\n",
" print(\"Loaded, file contents: %s\" % file_widget.value)\n",
"file_widget.on_trait_change(file_loaded, 'value')\n",
"\n",
"# Register an event to print an error message when a file could not\n",
"# be opened. Since the error messages are not handled through\n",
"# traitlets but instead handled through custom msgs, the registration\n",
"# of the handler is different than the two examples above. Instead\n",
"# the API provided by the CallbackDispatcher must be used.\n",
"def file_failed():\n",
" print(\"Could not load file contents of %s\" % file_widget.filename)\n",
"file_widget.errors.register_callback(file_failed)\n",
"\n",
"file_widget"
],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -1,4 +1,89 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"../images/ipython_logo.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Back to the main [Index](../Index.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Interactive Widgets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"IPython includes an architecture for interactive widgets that tie together Python code running in the kernel and JavaScript/HTML/CSS running in the browser. These widgets enable users to explore their code and data interactively."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tutorials"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- [Using Interact](Using Interact.ipynb)\n",
"- [Widget Basics](Widget Basics.ipynb) \n",
"- [Widget Events](Widget Events.ipynb) \n",
"- [Widget Placement](Widget Placement.ipynb) \n",
"- [Widget Styling](Widget Styling.ipynb) \n",
"- [Custom Widget](Custom Widget - Hello World.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Examples of custom widgets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- [Variable Inspector](Variable Inspector.ipynb) \n",
"- [Export As (nbconvert)](Export As (nbconvert%29.ipynb) \n",
"- [Nonblocking Console](Nonblocking Console.ipynb) \n",
"- [File Upload Widget](File Upload Widget.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Examples using `interact`/`interactive`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [Beat Frequencies](Beat Frequencies.ipynb)\n",
"* [Exploring Graphs](Exploring Graphs.ipynb)\n",
"* [Factoring](Factoring.ipynb)\n",
"* [Image Browser](Image Browser.ipynb)\n",
"* [Image Processing](Image Processing.ipynb)\n",
"* [Lorenz Differential Equations](Lorenz Differential Equations.ipynb)"
]
}
],
"metadata": {
"kernelspec": {
"codemirror_mode": {
@ -9,103 +94,8 @@
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:8e469f292b096d750dc8eeb71caa8c08b26bc722708314a26a7684c380ccd20f"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"../images/ipython_logo.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Back to the main [Index](../Index.ipynb)"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Interactive Widgets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"IPython includes an architecture for interactive widgets that tie together Python code running in the kernel and JavaScript/HTML/CSS running in the browser. These widgets enable users to explore their code and data interactively."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Tutorials"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- [Using Interact](Using Interact.ipynb)\n",
"- [Widget Basics](Widget Basics.ipynb) \n",
"- [Widget Events](Widget Events.ipynb) \n",
"- [Widget Placement](Widget Placement.ipynb) \n",
"- [Widget Styling](Widget Styling.ipynb) \n",
"- [Custom Widget](Custom Widget - Hello World.ipynb)"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Examples of custom widgets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- [Variable Inspector](Variable Inspector.ipynb) \n",
"- [Export As (nbconvert)](Export As (nbconvert%29.ipynb) \n",
"- [Nonblocking Console](Nonblocking Console.ipynb) \n",
"- [File Upload Widget](File Upload Widget.ipynb)"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Examples using `interact`/`interactive`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [Beat Frequencies](Beat Frequencies.ipynb)\n",
"* [Exploring Graphs](Exploring Graphs.ipynb)\n",
"* [Factoring](Factoring.ipynb)\n",
"* [Image Browser](Image Browser.ipynb)\n",
"* [Image Processing](Image Processing.ipynb)\n",
"* [Lorenz Differential Equations](Lorenz Differential Equations.ipynb)"
]
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because one or more lines are too long

@ -1,4 +1,220 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Console related imports.\n",
"from subprocess import Popen, PIPE\n",
"import os\n",
"from IPython.utils.py3compat import bytes_to_str, string_types\n",
"\n",
"# Widget related imports.\n",
"from IPython.html import widgets\n",
"from IPython.display import display"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define function to run a process without blocking the input."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def read_process(process, append_output):\n",
" \"\"\" Try to read the stdout and stderr of a process and render it using \n",
" the append_output method provided\n",
" \n",
" Parameters\n",
" ----------\n",
" process: Popen handle\n",
" append_output: method handle\n",
" Callback to render output. Signature of\n",
" append_output(output, [prefix=])\"\"\"\n",
" \n",
" try:\n",
" stdout = process.stdout.read()\n",
" if stdout is not None and len(stdout) > 0:\n",
" append_output(stdout, prefix=' ')\n",
" except:\n",
" pass\n",
" \n",
" try:\n",
" stderr = process.stderr.read()\n",
" if stderr is not None and len(stderr) > 0:\n",
" append_output(stderr, prefix='ERR ')\n",
" except:\n",
" pass\n",
"\n",
"\n",
"def set_pipe_nonblocking(pipe):\n",
" \"\"\"Set a pipe as non-blocking\"\"\"\n",
" try:\n",
" import fcntl\n",
" fl = fcntl.fcntl(pipe, fcntl.F_GETFL)\n",
" fcntl.fcntl(pipe, fcntl.F_SETFL, fl | os.O_NONBLOCK)\n",
" except:\n",
" pass\n",
"\n",
"kernel = get_ipython().kernel\n",
"def run_command(command, append_output, has_user_exited=None):\n",
" \"\"\"Run a command asyncronously\n",
" \n",
" Parameters\n",
" ----------\n",
" command: str\n",
" Shell command to launch a process with.\n",
" append_output: method handle\n",
" Callback to render output. Signature of\n",
" append_output(output, [prefix=])\n",
" has_user_exited: method handle\n",
" Check to see if the user wants to stop the command.\n",
" Must return a boolean.\"\"\"\n",
" \n",
" # Echo input.\n",
" append_output(command, prefix='>>> ')\n",
" \n",
" # Create the process. Make sure the pipes are set as non-blocking.\n",
" process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)\n",
" set_pipe_nonblocking(process.stdout)\n",
" set_pipe_nonblocking(process.stderr)\n",
" \n",
" # Only continue to read from the command \n",
" while (has_user_exited is None or not has_user_exited()) and process.poll() is None:\n",
" read_process(process, append_output)\n",
" kernel.do_one_iteration() # Run IPython iteration. This is the code that\n",
" # makes this operation non-blocking. This will\n",
" # allow widget messages and callbacks to be \n",
" # processed.\n",
" \n",
" # If the process is still running, the user must have exited.\n",
" if process.poll() is None:\n",
" process.kill()\n",
" else:\n",
" read_process(process, append_output) # Read remainer\n",
" \n",
" \n",
" \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the console widgets without displaying them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"console_container = widgets.VBox(visible=False)\n",
"console_container.padding = '10px'\n",
"\n",
"output_box = widgets.Textarea()\n",
"output_box.height = '400px'\n",
"output_box.font_family = 'monospace'\n",
"output_box.color = '#AAAAAA'\n",
"output_box.background_color = 'black'\n",
"output_box.width = '800px'\n",
"\n",
"input_box = widgets.Text()\n",
"input_box.font_family = 'monospace'\n",
"input_box.color = '#AAAAAA'\n",
"input_box.background_color = 'black'\n",
"input_box.width = '800px'\n",
"\n",
"console_container.children = [output_box, input_box]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Hook the process execution methods up to our console widgets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\n",
"def append_output(output, prefix):\n",
" if isinstance(output, string_types):\n",
" output_str = output\n",
" else:\n",
" output_str = bytes_to_str(output)\n",
" output_lines = output_str.split('\\n')\n",
" formatted_output = '\\n'.join([prefix + line for line in output_lines if len(line) > 0]) + '\\n'\n",
" output_box.value += formatted_output\n",
" output_box.scroll_to_bottom()\n",
" \n",
"def has_user_exited():\n",
" return not console_container.visible\n",
"\n",
"def handle_input(sender):\n",
" sender.disabled = True\n",
" try:\n",
" command = sender.value\n",
" sender.value = ''\n",
" run_command(command, append_output=append_output, has_user_exited=has_user_exited)\n",
" finally:\n",
" sender.disabled = False\n",
" \n",
"input_box.on_submit(handle_input)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the button that will be used to display and hide the console. Display both the console container and the new button used to toggle it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"toggle_button = widgets.Button(description=\"Start Console\")\n",
"def toggle_console(sender):\n",
" console_container.visible = not console_container.visible\n",
" if console_container.visible:\n",
" toggle_button.description=\"Stop Console\"\n",
" input_box.disabled = False\n",
" else:\n",
" toggle_button.description=\"Start Console\"\n",
"toggle_button.on_click(toggle_console)\n",
"\n",
"display(toggle_button)\n",
"display(console_container)"
]
}
],
"metadata": {
"kernelspec": {
"codemirror_mode": {
@ -9,225 +225,8 @@
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:3dfbc0dcb1fefc9ef028022760916b0300e14f71bf8e27589e61800841d5839c"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Console related imports.\n",
"from subprocess import Popen, PIPE\n",
"import os\n",
"from IPython.utils.py3compat import bytes_to_str, string_types\n",
"\n",
"# Widget related imports.\n",
"from IPython.html import widgets\n",
"from IPython.display import display"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define function to run a process without blocking the input."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def read_process(process, append_output):\n",
" \"\"\" Try to read the stdout and stderr of a process and render it using \n",
" the append_output method provided\n",
" \n",
" Parameters\n",
" ----------\n",
" process: Popen handle\n",
" append_output: method handle\n",
" Callback to render output. Signature of\n",
" append_output(output, [prefix=])\"\"\"\n",
" \n",
" try:\n",
" stdout = process.stdout.read()\n",
" if stdout is not None and len(stdout) > 0:\n",
" append_output(stdout, prefix=' ')\n",
" except:\n",
" pass\n",
" \n",
" try:\n",
" stderr = process.stderr.read()\n",
" if stderr is not None and len(stderr) > 0:\n",
" append_output(stderr, prefix='ERR ')\n",
" except:\n",
" pass\n",
"\n",
"\n",
"def set_pipe_nonblocking(pipe):\n",
" \"\"\"Set a pipe as non-blocking\"\"\"\n",
" try:\n",
" import fcntl\n",
" fl = fcntl.fcntl(pipe, fcntl.F_GETFL)\n",
" fcntl.fcntl(pipe, fcntl.F_SETFL, fl | os.O_NONBLOCK)\n",
" except:\n",
" pass\n",
"\n",
"kernel = get_ipython().kernel\n",
"def run_command(command, append_output, has_user_exited=None):\n",
" \"\"\"Run a command asyncronously\n",
" \n",
" Parameters\n",
" ----------\n",
" command: str\n",
" Shell command to launch a process with.\n",
" append_output: method handle\n",
" Callback to render output. Signature of\n",
" append_output(output, [prefix=])\n",
" has_user_exited: method handle\n",
" Check to see if the user wants to stop the command.\n",
" Must return a boolean.\"\"\"\n",
" \n",
" # Echo input.\n",
" append_output(command, prefix='>>> ')\n",
" \n",
" # Create the process. Make sure the pipes are set as non-blocking.\n",
" process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)\n",
" set_pipe_nonblocking(process.stdout)\n",
" set_pipe_nonblocking(process.stderr)\n",
" \n",
" # Only continue to read from the command \n",
" while (has_user_exited is None or not has_user_exited()) and process.poll() is None:\n",
" read_process(process, append_output)\n",
" kernel.do_one_iteration() # Run IPython iteration. This is the code that\n",
" # makes this operation non-blocking. This will\n",
" # allow widget messages and callbacks to be \n",
" # processed.\n",
" \n",
" # If the process is still running, the user must have exited.\n",
" if process.poll() is None:\n",
" process.kill()\n",
" else:\n",
" read_process(process, append_output) # Read remainer\n",
" \n",
" \n",
" \n",
" "
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the console widgets without displaying them."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"console_container = widgets.VBox(visible=False)\n",
"console_container.padding = '10px'\n",
"\n",
"output_box = widgets.Textarea()\n",
"output_box.height = '400px'\n",
"output_box.font_family = 'monospace'\n",
"output_box.color = '#AAAAAA'\n",
"output_box.background_color = 'black'\n",
"output_box.width = '800px'\n",
"\n",
"input_box = widgets.Text()\n",
"input_box.font_family = 'monospace'\n",
"input_box.color = '#AAAAAA'\n",
"input_box.background_color = 'black'\n",
"input_box.width = '800px'\n",
"\n",
"console_container.children = [output_box, input_box]"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Hook the process execution methods up to our console widgets."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"\n",
"def append_output(output, prefix):\n",
" if isinstance(output, string_types):\n",
" output_str = output\n",
" else:\n",
" output_str = bytes_to_str(output)\n",
" output_lines = output_str.split('\\n')\n",
" formatted_output = '\\n'.join([prefix + line for line in output_lines if len(line) > 0]) + '\\n'\n",
" output_box.value += formatted_output\n",
" output_box.scroll_to_bottom()\n",
" \n",
"def has_user_exited():\n",
" return not console_container.visible\n",
"\n",
"def handle_input(sender):\n",
" sender.disabled = True\n",
" try:\n",
" command = sender.value\n",
" sender.value = ''\n",
" run_command(command, append_output=append_output, has_user_exited=has_user_exited)\n",
" finally:\n",
" sender.disabled = False\n",
" \n",
"input_box.on_submit(handle_input)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the button that will be used to display and hide the console. Display both the console container and the new button used to toggle it."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"toggle_button = widgets.Button(description=\"Start Console\")\n",
"def toggle_console(sender):\n",
" console_container.visible = not console_container.visible\n",
" if console_container.visible:\n",
" toggle_button.description=\"Stop Console\"\n",
" input_box.disabled = False\n",
" else:\n",
" toggle_button.description=\"Start Console\"\n",
"toggle_button.on_click(toggle_console)\n",
"\n",
"display(toggle_button)\n",
"display(console_container)"
],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because it is too large Load Diff

@ -1,4 +1,190 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Variable Inspector Widget"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A short example implementation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook demonstrates how one can use the widgets already built-in to IPython to create a working variable inspector much like the ones seen in popular commercial scientific computing environments."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from IPython.html import widgets # Loads the Widget framework.\n",
"from IPython.core.magics.namespace import NamespaceMagics # Used to query namespace.\n",
"\n",
"# For this example, hide these names, just to avoid polluting the namespace further\n",
"get_ipython().user_ns_hidden['widgets'] = widgets\n",
"get_ipython().user_ns_hidden['NamespaceMagics'] = NamespaceMagics"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class VariableInspectorWindow(object):\n",
" instance = None\n",
" \n",
" def __init__(self, ipython):\n",
" \"\"\"Public constructor.\"\"\"\n",
" if VariableInspectorWindow.instance is not None:\n",
" raise Exception(\"\"\"Only one instance of the Variable Inspector can exist at a \n",
" time. Call close() on the active instance before creating a new instance.\n",
" If you have lost the handle to the active instance, you can re-obtain it\n",
" via `VariableInspectorWindow.instance`.\"\"\")\n",
" \n",
" VariableInspectorWindow.instance = self\n",
" self.closed = False\n",
" self.namespace = NamespaceMagics()\n",
" self.namespace.shell = ipython.kernel.shell\n",
" \n",
" self._popout = widgets.Popup()\n",
" self._popout.description = \"Variable Inspector\"\n",
" self._popout.button_text = self._popout.description\n",
"\n",
" self._modal_body = widgets.VBox()\n",
" self._modal_body.overflow_y = 'scroll'\n",
"\n",
" self._modal_body_label = widgets.HTML(value = 'Not hooked')\n",
" self._modal_body.children = [self._modal_body_label]\n",
"\n",
" self._popout.children = [\n",
" self._modal_body, \n",
" ]\n",
" \n",
" self._ipython = ipython\n",
" self._ipython.events.register('post_run_cell', self._fill)\n",
" \n",
" def close(self):\n",
" \"\"\"Close and remove hooks.\"\"\"\n",
" if not self.closed:\n",
" self._ipython.events.unregister('post_run_cell', self._fill)\n",
" self._popout.close()\n",
" self.closed = True\n",
" VariableInspectorWindow.instance = None\n",
"\n",
" def _fill(self):\n",
" \"\"\"Fill self with variable information.\"\"\"\n",
" values = self.namespace.who_ls()\n",
" self._modal_body_label.value = '<table class=\"table table-bordered table-striped\"><tr><th>Name</th><th>Type</th><th>Value</th></tr><tr><td>' + \\\n",
" '</td></tr><tr><td>'.join(['{0}</td><td>{1}</td><td>{2}'.format(v, type(eval(v)).__name__, str(eval(v))) for v in values]) + \\\n",
" '</td></tr></table>'\n",
"\n",
" def _ipython_display_(self):\n",
" \"\"\"Called when display() or pyout is used to display the Variable \n",
" Inspector.\"\"\"\n",
" self._popout._ipython_display_()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"inspector = VariableInspectorWindow(get_ipython())\n",
"inspector"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Test"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"b = 3.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"c = a * b"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"d = \"String\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"del b"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"inspector.close()"
]
}
],
"metadata": {
"kernelspec": {
"codemirror_mode": {
@ -9,194 +195,8 @@
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:474731659fb14b86672d1dafb2b497fa280082ab40a8a82fe2cde1b6d9b88a6e"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Variable Inspector Widget"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"A short example implementation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook demonstrates how one can use the widgets already built-in to IPython to create a working variable inspector much like the ones seen in popular commercial scientific computing environments."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.html import widgets # Loads the Widget framework.\n",
"from IPython.core.magics.namespace import NamespaceMagics # Used to query namespace.\n",
"\n",
"# For this example, hide these names, just to avoid polluting the namespace further\n",
"get_ipython().user_ns_hidden['widgets'] = widgets\n",
"get_ipython().user_ns_hidden['NamespaceMagics'] = NamespaceMagics"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class VariableInspectorWindow(object):\n",
" instance = None\n",
" \n",
" def __init__(self, ipython):\n",
" \"\"\"Public constructor.\"\"\"\n",
" if VariableInspectorWindow.instance is not None:\n",
" raise Exception(\"\"\"Only one instance of the Variable Inspector can exist at a \n",
" time. Call close() on the active instance before creating a new instance.\n",
" If you have lost the handle to the active instance, you can re-obtain it\n",
" via `VariableInspectorWindow.instance`.\"\"\")\n",
" \n",
" VariableInspectorWindow.instance = self\n",
" self.closed = False\n",
" self.namespace = NamespaceMagics()\n",
" self.namespace.shell = ipython.kernel.shell\n",
" \n",
" self._popout = widgets.Popup()\n",
" self._popout.description = \"Variable Inspector\"\n",
" self._popout.button_text = self._popout.description\n",
"\n",
" self._modal_body = widgets.VBox()\n",
" self._modal_body.overflow_y = 'scroll'\n",
"\n",
" self._modal_body_label = widgets.HTML(value = 'Not hooked')\n",
" self._modal_body.children = [self._modal_body_label]\n",
"\n",
" self._popout.children = [\n",
" self._modal_body, \n",
" ]\n",
" \n",
" self._ipython = ipython\n",
" self._ipython.events.register('post_run_cell', self._fill)\n",
" \n",
" def close(self):\n",
" \"\"\"Close and remove hooks.\"\"\"\n",
" if not self.closed:\n",
" self._ipython.events.unregister('post_run_cell', self._fill)\n",
" self._popout.close()\n",
" self.closed = True\n",
" VariableInspectorWindow.instance = None\n",
"\n",
" def _fill(self):\n",
" \"\"\"Fill self with variable information.\"\"\"\n",
" values = self.namespace.who_ls()\n",
" self._modal_body_label.value = '<table class=\"table table-bordered table-striped\"><tr><th>Name</th><th>Type</th><th>Value</th></tr><tr><td>' + \\\n",
" '</td></tr><tr><td>'.join(['{0}</td><td>{1}</td><td>{2}'.format(v, type(eval(v)).__name__, str(eval(v))) for v in values]) + \\\n",
" '</td></tr></table>'\n",
"\n",
" def _ipython_display_(self):\n",
" \"\"\"Called when display() or pyout is used to display the Variable \n",
" Inspector.\"\"\"\n",
" self._popout._ipython_display_()\n"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"inspector = VariableInspectorWindow(get_ipython())\n",
"inspector"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Test"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a = 5"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"b = 3.0"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"c = a * b"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"d = \"String\""
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"del b"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"inspector.close()"
],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,4 +1,426 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Next](Widget List.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Simple Widget Introduction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What are widgets?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Widgets are elements that exists in both the front-end and the back-end.\n",
"\n",
"![Kernel & front-end diagram](../images/FrontendKernel.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What can they be used for?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You can use widgets to build **interactive GUIs** for your notebooks. \n",
"You can also use widgets to **synchronize stateful and stateless information** between Python and JavaScript."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using widgets "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"To use the widget framework, you need to **import `IPython.html.widgets`**."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from IPython.html.widgets import *"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### repr"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Widgets have their own display `repr` which allows them to be displayed using IPython's display framework. Constructing and returning an `IntSlider` automatically displays the widget (as seen below). Widgets are **displayed inside the `widget area`**, which sits between the code cell and output. **You can hide all of the widgets** in the `widget area` by clicking the grey *x* in the margin."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"IntSlider()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### display()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also explicitly display the widget using `display(...)`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from IPython.display import display\n",
"w = IntSlider()\n",
"display(w)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Multiple display() calls"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you display the same widget twice, the displayed instances in the front-end **will remain in sync** with each other."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"display(w)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Why does displaying the same widget twice work?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Widgets are **represented in the back-end by a single object**. Each time a widget is displayed, **a new representation** of that same object is created in the front-end. These representations are called **views**.\n",
"\n",
"![Kernel & front-end diagram](images/WidgetModelView.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Closing widgets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can close a widget by calling its `close()` method."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"display(w)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"w.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Widget properties"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"All of the IPython widgets **share a similar naming scheme**. To read the value of a widget, you can query its `value` property."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"w = IntSlider()\n",
"display(w)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"w.value"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly, to set a widget's value, you can set its `value` property."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"w.value = 100"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Keys"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In addition to `value`, most widgets share `keys`, `description`, `disabled`, and `visible`. To see the entire list of synchronized, stateful properties, of any specific widget, you can **query the `keys` property**."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"w.keys"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Shorthand for setting the initial values of widget properties"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"While creating a widget, you can set some or all of the initial values of that widget by **defining them as keyword arguments in the widget's constructor** (as seen below)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"Text(value='Hello World!', disabled=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linking two similar widgets"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If you need to display the same value two different ways, you'll have to use two different widgets. Instead of **attempting to manually synchronize the values** of the two widgets, you can use the `traitlet` `link` function **to link two properties together**. Below, the values of three widgets are linked together."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from IPython.utils.traitlets import link\n",
"a = FloatText()\n",
"b = FloatSlider()\n",
"c = FloatProgress()\n",
"display(a,b,c)\n",
"\n",
"\n",
"mylink = link((a, 'value'), (b, 'value'), (c, 'value'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Unlinking widgets"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Unlinking the widgets is simple. All you have to do is call `.unlink` on the link object."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"mylink.unlink()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Next](Widget List.ipynb)"
]
}
],
"metadata": {
"kernelspec": {
"codemirror_mode": {
@ -9,437 +431,8 @@
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:c8af7f5d30b29ee52fe6a79cf0d573c9c2d5b2f522b04731249e3208671741d3"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Next](Widget List.ipynb)"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Simple Widget Introduction"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"What are widgets?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Widgets are elements that exists in both the front-end and the back-end.\n",
"\n",
"![Kernel & front-end diagram](../images/FrontendKernel.png)"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"What can they be used for?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You can use widgets to build **interactive GUIs** for your notebooks. \n",
"You can also use widgets to **synchronize stateful and stateless information** between Python and JavaScript."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Using widgets "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"To use the widget framework, you need to **import `IPython.html.widgets`**."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.html.widgets import *"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"repr"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Widgets have their own display `repr` which allows them to be displayed using IPython's display framework. Constructing and returning an `IntSlider` automatically displays the widget (as seen below). Widgets are **displayed inside the `widget area`**, which sits between the code cell and output. **You can hide all of the widgets** in the `widget area` by clicking the grey *x* in the margin."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"IntSlider()"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"display()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also explicitly display the widget using `display(...)`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.display import display\n",
"w = IntSlider()\n",
"display(w)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Multiple display() calls"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you display the same widget twice, the displayed instances in the front-end **will remain in sync** with each other."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"display(w)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Why does displaying the same widget twice work?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Widgets are **represented in the back-end by a single object**. Each time a widget is displayed, **a new representation** of that same object is created in the front-end. These representations are called **views**.\n",
"\n",
"![Kernel & front-end diagram](images/WidgetModelView.png)"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Closing widgets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can close a widget by calling its `close()` method."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"display(w)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"w.close()"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Widget properties"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"All of the IPython widgets **share a similar naming scheme**. To read the value of a widget, you can query its `value` property."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"w = IntSlider()\n",
"display(w)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"w.value"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly, to set a widget's value, you can set its `value` property."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"w.value = 100"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Keys"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In addition to `value`, most widgets share `keys`, `description`, `disabled`, and `visible`. To see the entire list of synchronized, stateful properties, of any specific widget, you can **query the `keys` property**."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"w.keys"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Shorthand for setting the initial values of widget properties"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"While creating a widget, you can set some or all of the initial values of that widget by **defining them as keyword arguments in the widget's constructor** (as seen below)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"Text(value='Hello World!', disabled=True)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Linking two similar widgets"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If you need to display the same value two different ways, you'll have to use two different widgets. Instead of **attempting to manually synchronize the values** of the two widgets, you can use the `traitlet` `link` function **to link two properties together**. Below, the values of three widgets are linked together."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.utils.traitlets import link\n",
"a = FloatText()\n",
"b = FloatSlider()\n",
"c = FloatProgress()\n",
"display(a,b,c)\n",
"\n",
"\n",
"mylink = link((a, 'value'), (b, 'value'), (c, 'value'))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Unlinking widgets"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Unlinking the widgets is simple. All you have to do is call `.unlink` on the link object."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"mylink.unlink()"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Next](Widget List.ipynb)"
]
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,4 +1,210 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Back](Widget List.ipynb) - [Next](Widget Styling.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Widget Events"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Special events"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import print_function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `Button` is not used to represent a data type. Instead the button widget is used to **handle mouse clicks**. The **`on_click` method** of the `Button` can be used to register function to be called when the button is clicked. The doc string of the `on_click` can be seen below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from IPython.html import widgets\n",
"print(widgets.Button.on_click.__doc__)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since button clicks are **stateless**, they are **transmitted from the front-end to the back-end using custom messages**. By using the `on_click` method, a button that prints a message when it has been clicked is shown below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from IPython.display import display\n",
"button = widgets.Button(description=\"Click Me!\")\n",
"display(button)\n",
"\n",
"def on_button_clicked(b):\n",
" print(\"Button clicked.\")\n",
"\n",
"button.on_click(on_button_clicked)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### on_sumbit"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **`Text`** also has a special **`on_submit` event**. The `on_submit` event **fires when the user hits return**."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"text = widgets.Text()\n",
"display(text)\n",
"\n",
"def handle_submit(sender):\n",
" print(text.value)\n",
"\n",
"text.on_submit(handle_submit)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Traitlet events"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Widget properties are IPython traitlets** and **traitlets are eventful**. To handle changes, the **`on_trait_change` method** of the widget can be used to **register a callback**. The doc string for `on_trait_change` can be seen below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(widgets.Widget.on_trait_change.__doc__)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Signatures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Mentioned in the doc string, the callback registered can have **4 possible signatures**:\n",
"\n",
"- callback()\n",
"- callback(trait_name)\n",
"- callback(trait_name, new_value)\n",
"- callback(trait_name, old_value, new_value)\n",
"\n",
"Using this method, an example of how to output an `IntSlider`'s value as it is changed can be seen below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"int_range = widgets.IntSlider()\n",
"display(int_range)\n",
"\n",
"def on_value_change(name, value):\n",
" print(value)\n",
"\n",
"int_range.on_trait_change(on_value_change, 'value')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Back](Widget List.ipynb) - [Next](Widget Styling.ipynb)"
]
}
],
"metadata": {
"cell_tags": [
[
@ -15,220 +221,8 @@
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:05a3e92089b37f68e3134587ffef6ef73830e5f8b3c515ba24640d7c803820c3"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Back](Widget List.ipynb) - [Next](Widget Styling.ipynb)"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Widget Events"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Special events"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from __future__ import print_function"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `Button` is not used to represent a data type. Instead the button widget is used to **handle mouse clicks**. The **`on_click` method** of the `Button` can be used to register function to be called when the button is clicked. The doc string of the `on_click` can be seen below."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.html import widgets\n",
"print(widgets.Button.on_click.__doc__)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since button clicks are **stateless**, they are **transmitted from the front-end to the back-end using custom messages**. By using the `on_click` method, a button that prints a message when it has been clicked is shown below."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.display import display\n",
"button = widgets.Button(description=\"Click Me!\")\n",
"display(button)\n",
"\n",
"def on_button_clicked(b):\n",
" print(\"Button clicked.\")\n",
"\n",
"button.on_click(on_button_clicked)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"on_sumbit"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **`Text`** also has a special **`on_submit` event**. The `on_submit` event **fires when the user hits return**."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"text = widgets.Text()\n",
"display(text)\n",
"\n",
"def handle_submit(sender):\n",
" print(text.value)\n",
"\n",
"text.on_submit(handle_submit)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 2,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Traitlet events"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Widget properties are IPython traitlets** and **traitlets are eventful**. To handle changes, the **`on_trait_change` method** of the widget can be used to **register a callback**. The doc string for `on_trait_change` can be seen below."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(widgets.Widget.on_trait_change.__doc__)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Signatures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Mentioned in the doc string, the callback registered can have **4 possible signatures**:\n",
"\n",
"- callback()\n",
"- callback(trait_name)\n",
"- callback(trait_name, new_value)\n",
"- callback(trait_name, old_value, new_value)\n",
"\n",
"Using this method, an example of how to output an `IntSlider`'s value as it is changed can be seen below."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"int_range = widgets.IntSlider()\n",
"display(int_range)\n",
"\n",
"def on_value_change(name, value):\n",
" print(value)\n",
"\n",
"int_range.on_trait_change(on_value_change, 'value')"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Index](Index.ipynb) - [Back](Widget List.ipynb) - [Next](Widget Styling.ipynb)"
]
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,149 +1,139 @@
{
"metadata": {
"name": "",
"signature": "sha256:9a1dd30de04270174c09ef33ca214e5b15ca3721547420087c1563ad557d78e3"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Connecting to an existing IPython kernel using the Qt Console"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"The Frontend/Kernel Model"
]
},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Connecting to an existing IPython kernel using the Qt Console"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Frontend/Kernel Model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The traditional IPython (`ipython`) consists of a single process that combines a terminal based UI with the process that runs the users code.\n",
"\n",
"While this traditional application still exists, the modern IPython consists of two processes:\n",
"\n",
"* Kernel: this is the process that runs the users code.\n",
"* Frontend: this is the process that provides the user interface where the user types code and sees results.\n",
"\n",
"IPython currently has 3 frontends:\n",
"\n",
"* Terminal Console (`ipython console`)\n",
"* Qt Console (`ipython qtconsole`)\n",
"* Notebook (`ipython notebook`)\n",
"\n",
"The Kernel and Frontend communicate over a ZeroMQ/JSON based messaging protocol, which allows multiple Frontends (even of different types) to communicate with a single Kernel. This opens the door for all sorts of interesting things, such as connecting a Console or Qt Console to a Notebook's Kernel. For example, you may want to connect a Qt console to your Notebook's Kernel and use it as a help\n",
"browser, calling `??` on objects in the Qt console (whose pager is more flexible than the\n",
"one in the notebook). \n",
"\n",
"This Notebook describes how you would connect another Frontend to a Kernel that is associated with a Notebook."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Manual connection"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To connect another Frontend to a Kernel manually, you first need to find out the connection information for the Kernel using the `%connect_info` magic:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The traditional IPython (`ipython`) consists of a single process that combines a terminal based UI with the process that runs the users code.\n",
"\n",
"While this traditional application still exists, the modern IPython consists of two processes:\n",
"\n",
"* Kernel: this is the process that runs the users code.\n",
"* Frontend: this is the process that provides the user interface where the user types code and sees results.\n",
"\n",
"IPython currently has 3 frontends:\n",
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"stdin_port\": 52858, \n",
" \"ip\": \"127.0.0.1\", \n",
" \"hb_port\": 52859, \n",
" \"key\": \"7efd45ca-d8a2-41b0-9cea-d9116d0fb883\", \n",
" \"shell_port\": 52856, \n",
" \"iopub_port\": 52857\n",
"}\n",
"\n",
"* Terminal Console (`ipython console`)\n",
"* Qt Console (`ipython qtconsole`)\n",
"* Notebook (`ipython notebook`)\n",
"\n",
"The Kernel and Frontend communicate over a ZeroMQ/JSON based messaging protocol, which allows multiple Frontends (even of different types) to communicate with a single Kernel. This opens the door for all sorts of interesting things, such as connecting a Console or Qt Console to a Notebook's Kernel. For example, you may want to connect a Qt console to your Notebook's Kernel and use it as a help\n",
"browser, calling `??` on objects in the Qt console (whose pager is more flexible than the\n",
"one in the notebook). \n",
"\n",
"This Notebook describes how you would connect another Frontend to a Kernel that is associated with a Notebook."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Manual connection"
"Paste the above JSON into a file, and connect with:\n",
" $> ipython <app> --existing <file>\n",
"or, if you are local, you can connect with just:\n",
" $> ipython <app> --existing kernel-b3bac7c1-8b2c-4536-8082-8d1df24f99ac.json \n",
"or even just:\n",
" $> ipython <app> --existing \n",
"if this is the most recent IPython session you have started.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To connect another Frontend to a Kernel manually, you first need to find out the connection information for the Kernel using the `%connect_info` magic:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%connect_info"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"{\n",
" \"stdin_port\": 52858, \n",
" \"ip\": \"127.0.0.1\", \n",
" \"hb_port\": 52859, \n",
" \"key\": \"7efd45ca-d8a2-41b0-9cea-d9116d0fb883\", \n",
" \"shell_port\": 52856, \n",
" \"iopub_port\": 52857\n",
"}\n",
"\n",
"Paste the above JSON into a file, and connect with:\n",
" $> ipython <app> --existing <file>\n",
"or, if you are local, you can connect with just:\n",
" $> ipython <app> --existing kernel-b3bac7c1-8b2c-4536-8082-8d1df24f99ac.json \n",
"or even just:\n",
" $> ipython <app> --existing \n",
"if this is the most recent IPython session you have started.\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that this magic displays everything you need to connect to this Notebook's Kernel."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Automatic connection using a new Qt Console"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also start a new Qt Console connected to your current Kernel by using the `%qtconsole` magic. This will detect the necessary connection\n",
"information and start the Qt Console for you automatically."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a = 10"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%qtconsole"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
}
],
"metadata": {}
"source": [
"%connect_info"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that this magic displays everything you need to connect to this Notebook's Kernel."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Automatic connection using a new Qt Console"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also start a new Qt Console connected to your current Kernel by using the `%qtconsole` magic. This will detect the necessary connection\n",
"information and start the Qt Console for you automatically."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 10"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%qtconsole"
]
}
]
],
"metadata": {
"signature": "sha256:9a1dd30de04270174c09ef33ca214e5b15ca3721547420087c1563ad557d78e3"
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,496 +1,485 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"NbConvert"
]
},
"cell_type": "markdown",
"metadata": {},
"source": [
"# NbConvert"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Command line usage"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`NbConvert` is the library, and the command line tool that allow to convert from notebook to other formats.\n",
"It is a technological preview in 1.0 but is already usable and highly configurable.\n",
"It ships already with many default available formats : `html`, `latex`, `markdown`, `python`, `rst` and `slides`\n",
"which are fully base on Jinja templating engine, so writing a converter for your custom format or tweeking the existing \n",
"one should be extra simple."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can invoke nbconvert by doing\n",
"\n",
"```bash\n",
"$ ipython nbconvert <options and arguments>\n",
"```\n",
"\n",
"Call `ipython nbconvert` with the `--help` flag or no aruments to get basic help on how to use it.\n",
"For more information about configuration use the `--help-all` flag"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Basic export"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will be converting `Custom Display Logic.ipynb`. \n",
"Be sure to have runed some of the cells in it to have output otherwise you will only see input in nbconvert.\n",
"Nbconvert **do not execute the code** in the notebook files, it only converts what is inside."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Command line usage"
"name": "stderr",
"output_type": "stream",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to html\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"[NbConvertApp] Loaded template html_full.tpl\n",
"[NbConvertApp] Writing 221081 bytes to 04 - Custom Display Logic.html\n"
]
},
}
],
"source": [
"%%bash\n",
"ipython nbconvert '04 - Custom Display Logic.ipynb'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Html is the default value (that can be configured) , so the verbose form would be "
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`NbConvert` is the library, and the command line tool that allow to convert from notebook to other formats.\n",
"It is a technological preview in 1.0 but is already usable and highly configurable.\n",
"It ships already with many default available formats : `html`, `latex`, `markdown`, `python`, `rst` and `slides`\n",
"which are fully base on Jinja templating engine, so writing a converter for your custom format or tweeking the existing \n",
"one should be extra simple."
"name": "stderr",
"output_type": "stream",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to html\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"[NbConvertApp] Loaded template html_full.tpl\n",
"[NbConvertApp] Writing 221081 bytes to 04 - Custom Display Logic.html\n"
]
},
}
],
"source": [
"%%bash\n",
"ipython nbconvert --to=html '04 - Custom Display Logic.ipynb'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also convert to latex, which will take care of extractin the embeded base64 encoded png, or the svg and call inkscape to convert those svg to pdf if necessary :"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can invoke nbconvert by doing\n",
"name": "stderr",
"output_type": "stream",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to latex\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"Setting Language: .UTF-8\n",
"\n",
"```bash\n",
"$ ipython nbconvert <options and arguments>\n",
"```\n",
"(process:26432): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"Call `ipython nbconvert` with the `--help` flag or no aruments to get basic help on how to use it.\n",
"For more information about configuration use the `--help-all` flag"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Basic export"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will be converting `Custom Display Logic.ipynb`. \n",
"Be sure to have runed some of the cells in it to have output otherwise you will only see input in nbconvert.\n",
"Nbconvert **do not execute the code** in the notebook files, it only converts what is inside."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"ipython nbconvert '04 - Custom Display Logic.ipynb'"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stderr",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to html\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"[NbConvertApp] Loaded template html_full.tpl\n",
"[NbConvertApp] Writing 221081 bytes to 04 - Custom Display Logic.html\n"
]
}
],
"prompt_number": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Html is the default value (that can be configured) , so the verbose form would be "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"ipython nbconvert --to=html '04 - Custom Display Logic.ipynb'"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stderr",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to html\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"[NbConvertApp] Loaded template html_full.tpl\n",
"[NbConvertApp] Writing 221081 bytes to 04 - Custom Display Logic.html\n"
]
}
],
"prompt_number": 2
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also convert to latex, which will take care of extractin the embeded base64 encoded png, or the svg and call inkscape to convert those svg to pdf if necessary :"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"ipython nbconvert --to=latex '04 - Custom Display Logic.ipynb'"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stderr",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to latex\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26432): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26472): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26512): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26552): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26592): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"[NbConvertApp] Loaded template latex_article.tplx\n",
"[NbConvertApp] Writing 41196 bytes to 04 - Custom Display Logic.tex\n"
]
}
],
"prompt_number": 3
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You should just have to compile the generated `.tex` file. If you get the required packages installed, if should compile out of the box.\n",
"(process:26472): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"For convenience we allow to run extra action after the conversion has been done, in particular for `latex` we have a `pdf` post-processor. \n",
"You can define the postprocessor tu run with the `--post` flag."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"ipython nbconvert --to=latex '04 - Custom Display Logic.ipynb' --post=pdf"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stderr",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to latex\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26658): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26698): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26738): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26778): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26818): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"[NbConvertApp] Loaded template latex_article.tplx\n",
"[NbConvertApp] Writing 41196 bytes to 04 - Custom Display Logic.tex\n",
"[NbConvertApp] Building PDF: ['pdflatex', '04 - Custom Display Logic.tex']\n"
]
}
],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Have a look at `04 - Custom Display Logic.pdf`, toward the end, where we compared `display()` vs `display_html()` and returning the object.\n",
"See how the cell where we use `display_html` was not able to display the circle, whereas the two other ones were able to select one of the oher representation they know how to display."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Customizing template"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"let's look at the first 20 lines of the `python` exporter"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"pyfile = !ipython nbconvert --to python '04 - Custom Display Logic.ipynb' --stdout\n",
"for l in pyfile[20:40]:\n",
" print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"# 1. Implementing special display methods such as `_repr_html_`.\n",
"# 2. Registering a display function for a particular type.\n",
"# \n",
"# In this Notebook we show how both approaches work.\n",
"\n",
"# Before we get started, we will import the various display functions for displaying the different formats we will create.\n",
"\n",
"# In[54]:\n",
"\n",
"from IPython.display import display\n",
"from IPython.display import (\n",
" display_html, display_jpeg, display_png,\n",
" display_javascript, display_svg, display_latex\n",
")\n",
"\n",
"\n",
"### Implementing special display methods\n",
"\n",
"# The main idea of the first approach is that you have to implement special display methods, one for each representation you want to use. Here is a list of the names of the special methods and the values they must return:\n",
"# \n"
]
}
],
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that the non-code cell are exported to the file. To have a cleaner script, we will export only the code contained in the code cells.\n",
"(process:26512): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26552): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"To do so, we will inherit the python template, and overwrite the markdown blocks to be empty."
"(process:26592): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"[NbConvertApp] Loaded template latex_article.tplx\n",
"[NbConvertApp] Writing 41196 bytes to 04 - Custom Display Logic.tex\n"
]
},
}
],
"source": [
"%%bash\n",
"ipython nbconvert --to=latex '04 - Custom Display Logic.ipynb'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You should just have to compile the generated `.tex` file. If you get the required packages installed, if should compile out of the box.\n",
"\n",
"For convenience we allow to run extra action after the conversion has been done, in particular for `latex` we have a `pdf` post-processor. \n",
"You can define the postprocessor tu run with the `--post` flag."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%writefile simplepython.tpl\n",
"{% extends 'python.tpl'%}\n",
"name": "stderr",
"output_type": "stream",
"text": [
"[NbConvertApp] Using existing profile dir: u'/Users/bussonniermatthias/.ipython/profile_default'\n",
"[NbConvertApp] Converting notebook 04 - Custom Display Logic.ipynb to latex\n",
"[NbConvertApp] Support files will be in 04 - Custom Display Logic_files/\n",
"Setting Language: .UTF-8\n",
"\n",
"{% block markdowncell -%}\n",
"{% endblock markdowncell %}\n",
"(process:26658): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"## we also want to get rig of header cell\n",
"{% block headingcell -%}\n",
"{% endblock headingcell %}\n",
"(process:26698): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"## and let's change the appearance of input prompt\n",
"{% block in_prompt %}\n",
"# This was input cell with prompt number : {{ cell.prompt_number if cell.prompt_number else ' ' }}\n",
"{%- endblock in_prompt %}"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Overwriting simplepython.tpl\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"pyfile = !ipython nbconvert --to python '04 - Custom Display Logic.ipynb' --stdout --template=simplepython.tpl\n",
"(process:26738): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"for l in pyfile[4:40]:\n",
" print l\n",
"print '...'"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"# This was input cell with prompt number : 54\n",
"from IPython.display import display\n",
"from IPython.display import (\n",
" display_html, display_jpeg, display_png,\n",
" display_javascript, display_svg, display_latex\n",
")\n",
"\n",
"\n",
"# This was input cell with prompt number : 55\n",
"get_ipython().magic(u'load soln/mycircle.py')\n",
"\n",
"\n",
"# This was input cell with prompt number : 56\n",
"class MyCircle(object):\n",
" \n",
" def _repr_html_(self):\n",
" return \"&#x25CB; (<b>html</b>)\"\n",
"\n",
" def _repr_svg_(self):\n",
" return \"\"\"<svg width='100px' height='100px'>\n",
" <circle cx=\"50\" cy=\"50\" r=\"20\" stroke=\"black\" stroke-width=\"1\" fill=\"blue\"/>\n",
" </svg>\"\"\"\n",
" \n",
" def _repr_latex_(self):\n",
" return r\"$\\bigcirc \\LaTeX$\"\n",
"\n",
" def _repr_javascript_(self):\n",
" return \"alert('I am a circle!');\"\n",
"\n",
"\n",
"# This was input cell with prompt number : 57\n",
"c = MyCircle()\n",
"\n",
"\n",
"# This was input cell with prompt number : 58\n",
"...\n"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I'll let you read Jinja manual for the exact syntax of the template."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Template that use cells metadata"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notebook fileformat support attaching arbitrary JSON metadata to each cell of a notebook. In this part we will use those metadata."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First you need to choose another notebook you want to convert to html, and tag some of the cell with metadata.\n",
"You can see the file `soln/celldiff.js` for a solution on how to tag, or follow the javascript tutorial to see how to do that. Use what we have written there to tag cells of some notebooks to `Easy`|`Medium`|`Hard`|`<None>`, and convert this notebook using your template."
"(process:26778): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"Setting Language: .UTF-8\n",
"\n",
"(process:26818): Gtk-WARNING **: Locale not supported by C library.\n",
"\tUsing the fallback 'C' locale.\n",
"[NbConvertApp] Loaded template latex_article.tplx\n",
"[NbConvertApp] Writing 41196 bytes to 04 - Custom Display Logic.tex\n",
"[NbConvertApp] Building PDF: ['pdflatex', '04 - Custom Display Logic.tex']\n"
]
},
}
],
"source": [
"%%bash\n",
"ipython nbconvert --to=latex '04 - Custom Display Logic.ipynb' --post=pdf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Have a look at `04 - Custom Display Logic.pdf`, toward the end, where we compared `display()` vs `display_html()` and returning the object.\n",
"See how the cell where we use `display_html` was not able to display the circle, whereas the two other ones were able to select one of the oher representation they know how to display."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Customizing template"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"let's look at the first 20 lines of the `python` exporter"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"you might need the following : \n",
"```\n",
"{% extends 'html_full.tpl'%}\n",
"{% block any_cell %}\n",
"{{ super() }}\n",
"<div style=\"background-color:red\">\n",
"<div style='background-color:orange'>\n",
"```\n",
"name": "stdout",
"output_type": "stream",
"text": [
"# 1. Implementing special display methods such as `_repr_html_`.\n",
"# 2. Registering a display function for a particular type.\n",
"# \n",
"# In this Notebook we show how both approaches work.\n",
"\n",
"# Before we get started, we will import the various display functions for displaying the different formats we will create.\n",
"\n",
"# In[54]:\n",
"\n",
"`metadata` might not exist, be sure to :\n",
"from IPython.display import display\n",
"from IPython.display import (\n",
" display_html, display_jpeg, display_png,\n",
" display_javascript, display_svg, display_latex\n",
")\n",
"\n",
"`cell['metadata'].get('example',{}).get('difficulty','')`\n",
"\n",
"tip: use `%%writefile` to edit the template in the notebook :-)"
"### Implementing special display methods\n",
"\n",
"# The main idea of the first approach is that you have to implement special display methods, one for each representation you want to use. Here is a list of the names of the special methods and the values they must return:\n",
"# \n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%bash\n",
"# ipython nbconvert --to html <your chosen notebook.ipynb> --template=<your template file>"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 8
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%loadpy soln/coloreddiff.tpl"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# ipython nbconvert --to html '04 - Custom Display Logic.ipynb' --template=soln/coloreddiff.tpl"
],
"language": "python",
"metadata": {},
"outputs": []
},
}
],
"source": [
"pyfile = !ipython nbconvert --to python '04 - Custom Display Logic.ipynb' --stdout\n",
"for l in pyfile[20:40]:\n",
" print l"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that the non-code cell are exported to the file. To have a cleaner script, we will export only the code contained in the code cells.\n",
"\n",
"To do so, we will inherit the python template, and overwrite the markdown blocks to be empty."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Get rid of all command line flags."
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting simplepython.tpl\n"
]
},
}
],
"source": [
"%%writefile simplepython.tpl\n",
"{% extends 'python.tpl'%}\n",
"\n",
"{% block markdowncell -%}\n",
"{% endblock markdowncell %}\n",
"\n",
"## we also want to get rig of header cell\n",
"{% block headingcell -%}\n",
"{% endblock headingcell %}\n",
"\n",
"## and let's change the appearance of input prompt\n",
"{% block in_prompt %}\n",
"# This was input cell with prompt number : {{ cell.prompt_number if cell.prompt_number else ' ' }}\n",
"{%- endblock in_prompt %}"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As of all of IPython nbconvert can be configured using profiles and passing the `--profile` flag. \n",
"Moreover if a `config.py` file exist in current working directory nbconvert will use that, or read the config file you give to it with the `--config=<file>` flag. \n",
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"# This was input cell with prompt number : 54\n",
"from IPython.display import display\n",
"from IPython.display import (\n",
" display_html, display_jpeg, display_png,\n",
" display_javascript, display_svg, display_latex\n",
")\n",
"\n",
"\n",
"# This was input cell with prompt number : 55\n",
"get_ipython().magic(u'load soln/mycircle.py')\n",
"\n",
"\n",
"# This was input cell with prompt number : 56\n",
"class MyCircle(object):\n",
" \n",
" def _repr_html_(self):\n",
" return \"&#x25CB; (<b>html</b>)\"\n",
"\n",
" def _repr_svg_(self):\n",
" return \"\"\"<svg width='100px' height='100px'>\n",
" <circle cx=\"50\" cy=\"50\" r=\"20\" stroke=\"black\" stroke-width=\"1\" fill=\"blue\"/>\n",
" </svg>\"\"\"\n",
" \n",
" def _repr_latex_(self):\n",
" return r\"$\\bigcirc \\LaTeX$\"\n",
"\n",
" def _repr_javascript_(self):\n",
" return \"alert('I am a circle!');\"\n",
"\n",
"\n",
"# This was input cell with prompt number : 57\n",
"c = MyCircle()\n",
"\n",
"In the end, if you are often running nbconvert on the sam project, `$ ipython nbconvert` should be enough to get you up and ready."
"\n",
"# This was input cell with prompt number : 58\n",
"...\n"
]
}
],
"metadata": {}
"source": [
"pyfile = !ipython nbconvert --to python '04 - Custom Display Logic.ipynb' --stdout --template=simplepython.tpl\n",
"\n",
"for l in pyfile[4:40]:\n",
" print l\n",
"print '...'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I'll let you read Jinja manual for the exact syntax of the template."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Template that use cells metadata"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notebook fileformat support attaching arbitrary JSON metadata to each cell of a notebook. In this part we will use those metadata."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First you need to choose another notebook you want to convert to html, and tag some of the cell with metadata.\n",
"You can see the file `soln/celldiff.js` for a solution on how to tag, or follow the javascript tutorial to see how to do that. Use what we have written there to tag cells of some notebooks to `Easy`|`Medium`|`Hard`|`<None>`, and convert this notebook using your template."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"you might need the following : \n",
"```\n",
"{% extends 'html_full.tpl'%}\n",
"{% block any_cell %}\n",
"{{ super() }}\n",
"<div style=\"background-color:red\">\n",
"<div style='background-color:orange'>\n",
"```\n",
"\n",
"`metadata` might not exist, be sure to :\n",
"\n",
"`cell['metadata'].get('example',{}).get('difficulty','')`\n",
"\n",
"tip: use `%%writefile` to edit the template in the notebook :-)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%%bash\n",
"# ipython nbconvert --to html <your chosen notebook.ipynb> --template=<your template file>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%loadpy soln/coloreddiff.tpl"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# ipython nbconvert --to html '04 - Custom Display Logic.ipynb' --template=soln/coloreddiff.tpl"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get rid of all command line flags."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As of all of IPython nbconvert can be configured using profiles and passing the `--profile` flag. \n",
"Moreover if a `config.py` file exist in current working directory nbconvert will use that, or read the config file you give to it with the `--config=<file>` flag. \n",
"\n",
"In the end, if you are often running nbconvert on the sam project, `$ ipython nbconvert` should be enough to get you up and ready."
]
}
]
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,149 +1,147 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Keyboard Shortcut Customization"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Starting with IPython 2.0 keyboard shortcuts in command and edit mode are fully customizable. These customizations are made using the IPython JavaScript API. Here is an example that makes the `r` key available for running a cell:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%javascript\n",
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', {\n",
" help : 'run cell',\n",
" help_index : 'zz',\n",
" handler : function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
" }}\n",
");"
],
"language": "python",
"metadata": {},
"outputs": [
{
"javascript": [
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', {\n",
" help : 'run cell',\n",
" help_index : 'zz',\n",
" handler : function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
" }}\n",
");"
],
"metadata": {},
"output_type": "display_data",
"text": [
"<IPython.core.display.Javascript at 0x10e8d1890>"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are a couple of points to mention about this API:\n",
"\n",
"* The `help_index` field is used to sort the shortcuts in the Keyboard Shortcuts help dialog. It defaults to `zz`.\n",
"* When a handler returns `false` it indicates that the event should stop propagating and the default action should not be performed. For further details about the `event` object or event handling, see the jQuery docs.\n",
"* If you don't need a `help` or `help_index` field, you can simply pass a function as the second argument to `add_shortcut`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%javascript\n",
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
"});"
],
"language": "python",
"metadata": {},
"outputs": [
{
"javascript": [
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
"});"
],
"metadata": {},
"output_type": "display_data",
"text": [
"<IPython.core.display.Javascript at 0x1019baf90>"
]
}
],
"prompt_number": 11
},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Keyboard Shortcut Customization"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Starting with IPython 2.0 keyboard shortcuts in command and edit mode are fully customizable. These customizations are made using the IPython JavaScript API. Here is an example that makes the `r` key available for running a cell:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"data": {
"application/javascript": [
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', {\n",
" help : 'run cell',\n",
" help_index : 'zz',\n",
" handler : function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
" }}\n",
");"
],
"text/plain": [
"<IPython.core.display.Javascript at 0x10e8d1890>"
]
},
"metadata": {},
"source": [
"Likewise, to remove a shortcut, use `remove_shortcut`:"
]
},
"output_type": "display_data"
}
],
"source": [
"%%javascript\n",
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', {\n",
" help : 'run cell',\n",
" help_index : 'zz',\n",
" handler : function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
" }}\n",
");"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are a couple of points to mention about this API:\n",
"\n",
"* The `help_index` field is used to sort the shortcuts in the Keyboard Shortcuts help dialog. It defaults to `zz`.\n",
"* When a handler returns `false` it indicates that the event should stop propagating and the default action should not be performed. For further details about the `event` object or event handling, see the jQuery docs.\n",
"* If you don't need a `help` or `help_index` field, you can simply pass a function as the second argument to `add_shortcut`."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%javascript\n",
"\n",
"IPython.keyboard_manager.command_shortcuts.remove_shortcut('r');"
],
"language": "python",
"data": {
"application/javascript": [
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
"});"
],
"text/plain": [
"<IPython.core.display.Javascript at 0x1019baf90>"
]
},
"metadata": {},
"outputs": [
{
"javascript": [
"\n",
"IPython.keyboard_manager.command_shortcuts.remove_shortcut('r');"
],
"metadata": {},
"output_type": "display_data",
"text": [
"<IPython.core.display.Javascript at 0x10e8d1950>"
]
}
],
"prompt_number": 8
},
"output_type": "display_data"
}
],
"source": [
"%%javascript\n",
"\n",
"IPython.keyboard_manager.command_shortcuts.add_shortcut('r', function (event) {\n",
" IPython.notebook.execute_cell();\n",
" return false;\n",
"});"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Likewise, to remove a shortcut, use `remove_shortcut`:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"data": {
"application/javascript": [
"\n",
"IPython.keyboard_manager.command_shortcuts.remove_shortcut('r');"
],
"text/plain": [
"<IPython.core.display.Javascript at 0x10e8d1950>"
]
},
"metadata": {},
"source": [
"If you want your keyboard shortcuts to be active for all of your notebooks, put the above API calls into your `<profile>/static/custom/custom.js` file."
]
"output_type": "display_data"
}
],
"metadata": {}
"source": [
"%%javascript\n",
"\n",
"IPython.keyboard_manager.command_shortcuts.remove_shortcut('r');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you want your keyboard shortcuts to be active for all of your notebooks, put the above API calls into your `<profile>/static/custom/custom.js` file."
]
}
]
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because it is too large Load Diff

@ -1,85 +1,76 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"../images/ipython_logo.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Back to the main [Index](../Index.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook is a web-based interactive computing system that enables users to author documents that include live code, narrative text, LaTeX equations, HTML, images and video. These documents contain a full record of a computation and its results and can be shared on email, [Dropbox](http://dropbox.com), version control systems (like git/[GitHub](http://github.com)) or [nbviewer.ipython.org](http://nbviewer.ipython.org)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tutorials"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [What is the IPython Notebook](What is the IPython Notebook.ipynb)\n",
"* [Running the Notebook Server](Running the Notebook Server.ipynb)\n",
"* [Notebook Basics](Notebook Basics.ipynb)\n",
"* [Running Code](Running Code.ipynb)\n",
"* [Working With Markdown Cells](Working With Markdown Cells.ipynb)\n",
"* [Custom Keyboard Shortcuts](Custom Keyboard Shortcuts.ipynb)\n",
"* [JavaScript Notebook Extensions](JavaScript Notebook Extensions.ipynb)\n",
"* [Notebook Security](Notebook Security.ipynb)\n",
"* [Converting Notebooks With nbconvert](Converting Notebooks With nbconvert.ipynb)\n",
"* [Using nbconvert as a Library](Using nbconvert as a Library.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Examples"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [Importing Notebooks](Importing Notebooks.ipynb)\n",
"* [Connecting with the Qt Console](Connecting with the Qt Console.ipynb)\n",
"* [Typesetting Equations](Typesetting Equations.ipynb)"
]
}
],
"metadata": {
"name": "",
"signature": "sha256:5a3c5ebae9154e13957e7c9d28bd3b7697c4b14f965482feb288d2cdf078983e"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"../images/ipython_logo.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Back to the main [Index](../Index.ipynb)"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook is a web-based interactive computing system that enables users to author documents that include live code, narrative text, LaTeX equations, HTML, images and video. These documents contain a full record of a computation and its results and can be shared on email, [Dropbox](http://dropbox.com), version control systems (like git/[GitHub](http://github.com)) or [nbviewer.ipython.org](http://nbviewer.ipython.org)."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Tutorials"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [What is the IPython Notebook](What is the IPython Notebook.ipynb)\n",
"* [Running the Notebook Server](Running the Notebook Server.ipynb)\n",
"* [Notebook Basics](Notebook Basics.ipynb)\n",
"* [Running Code](Running Code.ipynb)\n",
"* [Working With Markdown Cells](Working With Markdown Cells.ipynb)\n",
"* [Custom Keyboard Shortcuts](Custom Keyboard Shortcuts.ipynb)\n",
"* [JavaScript Notebook Extensions](JavaScript Notebook Extensions.ipynb)\n",
"* [Notebook Security](Notebook Security.ipynb)\n",
"* [Converting Notebooks With nbconvert](Converting Notebooks With nbconvert.ipynb)\n",
"* [Using nbconvert as a Library](Using nbconvert as a Library.ipynb)"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Examples"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [Importing Notebooks](Importing Notebooks.ipynb)\n",
"* [Connecting with the Qt Console](Connecting with the Qt Console.ipynb)\n",
"* [Typesetting Equations](Typesetting Equations.ipynb)"
]
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because it is too large Load Diff

@ -1,4 +1,237 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Notebook Basics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook assumes that you already have IPython [installed](http://ipython.org/install.html) and are able to start the notebook server by running:\n",
"\n",
" ipython notebook\n",
"\n",
"For more details on how to run the notebook server, see [Running the Notebook Server](Running the Notebook Server.ipynb)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Notebook dashboard"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you first start the notebook server, your browser will open to the notebook dashboard. The dashboard serves as a home page for the notebook. Its main purpose is to display the notebooks in the current directory. For example, here is a screenshot of the dashboard page for the `examples` directory in the IPython repository:\n",
"\n",
"<img src=\"images/dashboard_notebooks_tab.png\" />\n",
"\n",
"The top of the notebook list displays clickable breadcrumbs of the current directory. By clicking on these breadcrumbs or on sub-directories in the notebook list, you can navigate your file system.\n",
"\n",
"To create a new notebook, click on the \"New Notebook\" button at the top of the list.\n",
"\n",
"Notebooks can be uploaded to the current directory by dragging a notebook file onto the notebook list or by the \"click here\" text above the list.\n",
"\n",
"The notebook list shows a red \"Shutdown\" button for running notebooks and a \"Delete\" button for stopped notebooks. Notebook remain running until you explicitly click the \"Shutdown\" button; closing the notebook's page is not sufficient.\n",
"\n",
"To see all of your running notebooks along with their directories, click on the \"Running\" tab:\n",
"\n",
"<img src=\"images/dashboard_running_tab.png\" />\n",
"\n",
"This view provides a convenient way to track notebooks that you start as you navigate the file system in a long running notebook server."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Overview of the Notebook UI"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert\">\n",
"As of IPython 2.0, the user interface has changed significantly. Because of this we highly recommend existing users to review this information after upgrading to IPython 2.0. All new users of IPython should review this information as well.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you create a new notebook or open an existing one, you will be taken to the notebook user interface (UI). This UI allows you to run code and author notebook documents interactively. The notebook UI has the following main areas:\n",
"\n",
"* Menu\n",
"* Toolbar\n",
"* Notebook area and cells\n",
"\n",
"IPython 2.0 has an interactive tour of these elements that can be started in the \"Help:User Interface Tour\" menu item."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modal editor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Starting with IPython 2.0, the IPython Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Edit mode"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Edit mode is indicated by a green cell border and a prompt showing in the editor area:\n",
"\n",
"<img src=\"images/edit_mode.png\">\n",
"\n",
"When a cell is in edit mode, you can type into the cell, like a normal text editor."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"Enter edit mode by pressing `Enter` or using the mouse to click on a cell's editor area.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Command mode"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Command mode is indicated by a grey cell border:\n",
"\n",
"<img src=\"images/command_mode.png\">\n",
"\n",
"When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `c`, you will copy the current cell - no modifier is needed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-error\">\n",
"Don't try to type into a cell in command mode; unexpected things will happen!\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"Enter command mode by pressing `Esc` or using the mouse to click *outside* a cell's editor area.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mouse navigation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"All navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area:\n",
"\n",
"<img src=\"images/menubar_toolbar.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first idea of mouse based navigation is that **cells can be selected by clicking on them.** The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode.\n",
"\n",
"If you are running this notebook in a live session (not on http://nbviewer.ipython.org) try selecting different cells and going between edit and command mode. Try typing into a cell."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The second idea of mouse based navigation is that **cell actions usually apply to the currently selected cell**. Thus if you want to run the code in a cell, you would select it and click the <button class='btn btn-default btn-xs'><i class=\"fa fa-play icon-play\"></i></button> button in the toolbar or the \"Cell:Run\" menu item. Similarly, to copy a cell you would select it and click the <button class='btn btn-default btn-xs'><i class=\"fa fa-copy icon-copy\"></i></button> button in the toolbar or the \"Edit:Copy\" menu item. With this simple pattern, you should be able to do most everything you need with the mouse.\n",
"\n",
"Markdown and heading cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the <button class='btn btn-default btn-xs'><i class=\"fa fa-play icon-play\"></i></button> button in the toolbar or the \"Cell:Run\" menu item. To unrender the selected cell, double click on the cell."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Keyboard Navigation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The modal user interface of the IPython Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode.\n",
"\n",
"The most important keyboard shortcuts are `Enter`, which enters edit mode, and `Esc`, which enters command mode.\n",
"\n",
"In edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts:\n",
"\n",
"<img src=\"images/edit_shortcuts.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In command mode, the entire keyboard is available for shortcuts, so there are many more:\n",
"\n",
"<img src=\"images/command_shortcuts.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We recommend learning the command mode shortcuts in the following rough order:\n",
"\n",
"1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j`\n",
"2. Saving the notebook: `s`\n",
"2. Cell types: `y`, `m`, `1-6`, `t`\n",
"3. Cell creation and movement: `a`, `b`, `ctrl+k`, `ctrl+j`\n",
"4. Cell editing: `x`, `c`, `v`, `d`, `z`, `shift+=`\n",
"5. Kernel operations: `i`, `.`"
]
}
],
"metadata": {
"kernelspec": {
"codemirror_mode": {
@ -9,255 +242,8 @@
"language": "python",
"name": "python3"
},
"name": "",
"signature": "sha256:6e4f35a8bc2cb1408b995bc3c006369dd3c3e31a3e6212088f3d1e2abef36407"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Notebook Basics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook assumes that you already have IPython [installed](http://ipython.org/install.html) and are able to start the notebook server by running:\n",
"\n",
" ipython notebook\n",
"\n",
"For more details on how to run the notebook server, see [Running the Notebook Server](Running the Notebook Server.ipynb)."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"The Notebook dashboard"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you first start the notebook server, your browser will open to the notebook dashboard. The dashboard serves as a home page for the notebook. Its main purpose is to display the notebooks in the current directory. For example, here is a screenshot of the dashboard page for the `examples` directory in the IPython repository:\n",
"\n",
"<img src=\"images/dashboard_notebooks_tab.png\" />\n",
"\n",
"The top of the notebook list displays clickable breadcrumbs of the current directory. By clicking on these breadcrumbs or on sub-directories in the notebook list, you can navigate your file system.\n",
"\n",
"To create a new notebook, click on the \"New Notebook\" button at the top of the list.\n",
"\n",
"Notebooks can be uploaded to the current directory by dragging a notebook file onto the notebook list or by the \"click here\" text above the list.\n",
"\n",
"The notebook list shows a red \"Shutdown\" button for running notebooks and a \"Delete\" button for stopped notebooks. Notebook remain running until you explicitly click the \"Shutdown\" button; closing the notebook's page is not sufficient.\n",
"\n",
"To see all of your running notebooks along with their directories, click on the \"Running\" tab:\n",
"\n",
"<img src=\"images/dashboard_running_tab.png\" />\n",
"\n",
"This view provides a convenient way to track notebooks that you start as you navigate the file system in a long running notebook server."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Overview of the Notebook UI"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert\">\n",
"As of IPython 2.0, the user interface has changed significantly. Because of this we highly recommend existing users to review this information after upgrading to IPython 2.0. All new users of IPython should review this information as well.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you create a new notebook or open an existing one, you will be taken to the notebook user interface (UI). This UI allows you to run code and author notebook documents interactively. The notebook UI has the following main areas:\n",
"\n",
"* Menu\n",
"* Toolbar\n",
"* Notebook area and cells\n",
"\n",
"IPython 2.0 has an interactive tour of these elements that can be started in the \"Help:User Interface Tour\" menu item."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Modal editor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Starting with IPython 2.0, the IPython Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Edit mode"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Edit mode is indicated by a green cell border and a prompt showing in the editor area:\n",
"\n",
"<img src=\"images/edit_mode.png\">\n",
"\n",
"When a cell is in edit mode, you can type into the cell, like a normal text editor."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"Enter edit mode by pressing `Enter` or using the mouse to click on a cell's editor area.\n",
"</div>"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Command mode"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Command mode is indicated by a grey cell border:\n",
"\n",
"<img src=\"images/command_mode.png\">\n",
"\n",
"When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `c`, you will copy the current cell - no modifier is needed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-error\">\n",
"Don't try to type into a cell in command mode; unexpected things will happen!\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"Enter command mode by pressing `Esc` or using the mouse to click *outside* a cell's editor area.\n",
"</div>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Mouse navigation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"All navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area:\n",
"\n",
"<img src=\"images/menubar_toolbar.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first idea of mouse based navigation is that **cells can be selected by clicking on them.** The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode.\n",
"\n",
"If you are running this notebook in a live session (not on http://nbviewer.ipython.org) try selecting different cells and going between edit and command mode. Try typing into a cell."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The second idea of mouse based navigation is that **cell actions usually apply to the currently selected cell**. Thus if you want to run the code in a cell, you would select it and click the <button class='btn btn-default btn-xs'><i class=\"fa fa-play icon-play\"></i></button> button in the toolbar or the \"Cell:Run\" menu item. Similarly, to copy a cell you would select it and click the <button class='btn btn-default btn-xs'><i class=\"fa fa-copy icon-copy\"></i></button> button in the toolbar or the \"Edit:Copy\" menu item. With this simple pattern, you should be able to do most everything you need with the mouse.\n",
"\n",
"Markdown and heading cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the <button class='btn btn-default btn-xs'><i class=\"fa fa-play icon-play\"></i></button> button in the toolbar or the \"Cell:Run\" menu item. To unrender the selected cell, double click on the cell."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Keyboard Navigation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The modal user interface of the IPython Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode.\n",
"\n",
"The most important keyboard shortcuts are `Enter`, which enters edit mode, and `Esc`, which enters command mode.\n",
"\n",
"In edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts:\n",
"\n",
"<img src=\"images/edit_shortcuts.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In command mode, the entire keyboard is available for shortcuts, so there are many more:\n",
"\n",
"<img src=\"images/command_shortcuts.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We recommend learning the command mode shortcuts in the following rough order:\n",
"\n",
"1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j`\n",
"2. Saving the notebook: `s`\n",
"2. Cell types: `y`, `m`, `1-6`, `t`\n",
"3. Cell creation and movement: `a`, `b`, `ctrl+k`, `ctrl+j`\n",
"4. Cell editing: `x`, `c`, `v`, `d`, `z`, `shift+=`\n",
"5. Kernel operations: `i`, `.`"
]
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because it is too large Load Diff

@ -1,389 +1,363 @@
{
"metadata": {
"name": "",
"signature": "sha256:ee4b22b4c949fe21b3e5cda24f0916ba59d8c09443f4a897d98b96d4a73ac335"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Running the Notebook Server"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython notebook server is a custom web server that runs the notebook web application. Most of the time, users run the notebook server on their local computer using IPython's command line interface."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Starting the notebook server using the command line"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can start the notebook server from the command line (Terminal on Mac/Linux, CMD prompt on Windows) by running the following command: \n",
"\n",
" ipython notebook\n",
"\n",
"This will print some information about the notebook server in your terminal, including the URL of the web application (by default, `http://127.0.0.1:8888`). It will then open your default web browser to this URL.\n",
"\n",
"When the notebook opens, you will see the **notebook dashboard**, which will show a list of the notebooks and subdirectories in the directory where the notebook server was started. As of IPython 2.0, the dashboard allows you to navigate to different subdirectories. Because of this, it is no longer necessary to start a separate notebook server for each subdirectory. Most of the time, you will want to start a notebook server in the highest directory in your filesystem where notebooks can be found. Often this will be your home directory.\n",
"\n",
"You can start more than one notebook server at the same time. By default, the first notebook server starts on port 8888 and later notebook servers search for open ports near that one.\n",
"\n",
"You can also specify the port manually:\n",
"\n",
" ipython notebook --port 9999\n",
"\n",
"Or start notebook server without opening a web browser.\n",
"\n",
" ipython notebook --no-browser\n",
"\n",
"The notebook server has a number of other command line arguments that can be displayed with the `--help` flag: \n",
"\n",
" ipython notebook --help\n",
"\n",
"<div class=\"alert alert-failure\">\n",
"It used to be possible to specify kernel options, such as <code>--pylab inline</code> from the command line. This is deprecated in IPython 2.0 and will be removed in IPython 3.0. To enable matplotlib based plotting for the Python kernel use the <code>%matplotlib</code> magic command.\n",
"</div>\n",
"\n"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Configuring the IPython Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook web server can also be configured using IPython profiles and configuration files. The Notebook web server configuration options are set in a file named `ipython_notebook_config.py` in your IPython *profile directory*. The profile directory is a subfolder of your IPython directory, which itself is usually `.ipython` in your home directory.\n",
"\n",
"You can display the location of your default profile directory by running the command:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"!ipython profile locate default"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"/Users/bgranger/.ipython/profile_default\r\n"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The default version of `ipython_notebook_config.py` lists all of the options available along with documentation for each. Changes made to that file will affect all notebook servers run under that profile. Command line options always override those set in configuration files.\n",
"\n",
"You can create a new profile:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"!ipython profile create my_profile"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_config.py'\r\n"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_qtconsole_config.py'\r\n"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_notebook_config.py'\r\n",
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_nbconvert_config.py'\r\n"
]
}
],
"prompt_number": 3
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And then view its location:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"!ipython profile locate my_profile"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"/Users/bgranger/.ipython/profile_my_profile\r\n"
]
}
],
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To start the notebook server using a given profile, run the following:\n",
"\n",
" ipython notebook --profile=my_profile"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More details about IPython configuration files and profiles can be found [here](http://ipython.org/ipython-doc/dev/config/intro.html)."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Securing the notebook server"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook allows arbitrary code execution on the computer running it. Thus, the notebook web server should never be run on the open internet without first securing it. By default, the notebook server only listens on local network interface (`127.0.0.1`) There are two steps required to secure the notebook server:\n",
"\n",
"1. Setting a password\n",
"2. Encrypt network traffic using SSL"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Setting a password"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can protect your notebook server with a simple single password by setting the `NotebookApp.password` configurable. You can prepare a hashed password using the function `IPython.lib.passwd`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.lib import passwd\n",
"password = passwd(\"secret\")\n",
"password"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 1,
"text": [
"'sha1:6c2164fc2b22:ed55ecf07fc0f985ab46561483c0e888e8964ae6'"
]
}
],
"prompt_number": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can then add this to your `ipython_notebook_config.py`:\n",
"\n",
"```python\n",
"# Password to use for web authentication\n",
"c = get_config()\n",
"c.NotebookApp.password = \n",
"u'sha1:6c2164fc2b22:ed55ecf07fc0f985ab46561483c0e888e8964ae6'\n",
"```"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Using SSL/HTTPS"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When using a password, it is a good idea to also use SSL, so that your \n",
"password is not sent unencrypted by your browser to the web server. When running the notebook on the public internet this is absolutely required.\n",
"\n",
"The first step is to generate an SSL certificate. A self-signed certificate can be generated with ``openssl``. For example, the following command will create a certificate valid for 365 days with both the key and certificate data written to the same file:\n",
"\n",
" openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem\n",
"\n",
"In most cases, you should run this command in your profile directory, which will make it easy to use the generated key and certificate.\n",
"\n",
"When you connect to a notebook server over HTTPS using a self-signed certificate, your browser will warn you of a dangerous certificate because it is self-signed. If you want to have a fully compliant certificate that will not raise warnings, it is possible (but rather involved) to obtain one,\n",
"as explained in detail in [this tutorial](http://arstechnica.com/security/news/2009/12/how-to-get-set-with-a-secure-sertificate-for-free.ars)\n",
"\t\n",
"When you enable SSL support, you will need to access the notebook server over ``https://``, rather than plain ``http://``. The startup message from the notebook server prints the correct URL, but it is easy to overlook and think the server is for some reason non-responsive.\n",
"\n",
"Once you have generated the key and certificate, you can configure the notebook server to use them, by adding the following to `ipython_notebook_config.py`:\n",
"\n",
"```python\n",
"# The full path to an SSL/TLS certificate file.\n",
"c.NotebookApp.certfile = u'/Users/bgranger/.ipython/profile_my_profile/mycert.crt'\n",
"\n",
"# The full path to a private key file for usage with SSL/TLS.\n",
"c.NotebookApp.keyfile = u'/Users/bgranger/.ipython/profile_my_profile/mycert.key'\n",
"```"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Running a public notebook server"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-error\">\n",
"Don't run a public notebook server unless you first secure it with a password and SSL/HTTPS as described above\n",
"</div>\n",
"\n",
"By default the notebook server only listens on the `localhost/127.0.0.1` network interface. If you want to connect to the notebook from another computers, or over the internet, you need to configure the notebook server to listen on all network interfaces and not open the browser. You will often also want to disable the automatic launching of the web browser.\n",
"\n",
"This can be accomplished by passing a command line options.\n",
"\n",
" ipython notebook --ip=* --no-browser\n",
"\n",
"You can also add the following to your`ipython_notebook_config.py` file:\n",
"\n",
"```python\n",
"c.NotebookApp.ip = '*'\n",
"c.NotebookApp.open_browser = False\n",
"```"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Running with a different URL prefix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook dashboard typically lives at the URL `http://localhost:8888/tree`. If you prefer that it lives, together with the \n",
"rest of the notebook web application, under a base URL prefix, such as `http://localhost:8888/ipython/tree`, you can do so by adding the following lines to your `ipython_notebook_config.py` file.\n",
"\n",
"```python\n",
"c.NotebookApp.base_url = '/ipython/'\n",
"c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}\n",
"```"
]
},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Running the Notebook Server"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython notebook server is a custom web server that runs the notebook web application. Most of the time, users run the notebook server on their local computer using IPython's command line interface."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Starting the notebook server using the command line"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can start the notebook server from the command line (Terminal on Mac/Linux, CMD prompt on Windows) by running the following command: \n",
"\n",
" ipython notebook\n",
"\n",
"This will print some information about the notebook server in your terminal, including the URL of the web application (by default, `http://127.0.0.1:8888`). It will then open your default web browser to this URL.\n",
"\n",
"When the notebook opens, you will see the **notebook dashboard**, which will show a list of the notebooks and subdirectories in the directory where the notebook server was started. As of IPython 2.0, the dashboard allows you to navigate to different subdirectories. Because of this, it is no longer necessary to start a separate notebook server for each subdirectory. Most of the time, you will want to start a notebook server in the highest directory in your filesystem where notebooks can be found. Often this will be your home directory.\n",
"\n",
"You can start more than one notebook server at the same time. By default, the first notebook server starts on port 8888 and later notebook servers search for open ports near that one.\n",
"\n",
"You can also specify the port manually:\n",
"\n",
" ipython notebook --port 9999\n",
"\n",
"Or start notebook server without opening a web browser.\n",
"\n",
" ipython notebook --no-browser\n",
"\n",
"The notebook server has a number of other command line arguments that can be displayed with the `--help` flag: \n",
"\n",
" ipython notebook --help\n",
"\n",
"<div class=\"alert alert-failure\">\n",
"It used to be possible to specify kernel options, such as <code>--pylab inline</code> from the command line. This is deprecated in IPython 2.0 and will be removed in IPython 3.0. To enable matplotlib based plotting for the Python kernel use the <code>%matplotlib</code> magic command.\n",
"</div>\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Configuring the IPython Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook web server can also be configured using IPython profiles and configuration files. The Notebook web server configuration options are set in a file named `ipython_notebook_config.py` in your IPython *profile directory*. The profile directory is a subfolder of your IPython directory, which itself is usually `.ipython` in your home directory.\n",
"\n",
"You can display the location of your default profile directory by running the command:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Using a different notebook store"
"name": "stdout",
"output_type": "stream",
"text": [
"/Users/bgranger/.ipython/profile_default\r\n"
]
},
}
],
"source": [
"!ipython profile locate default"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The default version of `ipython_notebook_config.py` lists all of the options available along with documentation for each. Changes made to that file will affect all notebook servers run under that profile. Command line options always override those set in configuration files.\n",
"\n",
"You can create a new profile:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By default, the notebook server stores the notebook documents that it saves as files in the working directory of the notebook server, also known as the\n",
"`notebook_dir`. This logic is implemented in the `FileNotebookManager` class. However, the server can be configured to use a different notebook manager class, which can store the notebooks in a different format. \n",
"\n",
"The [bookstore](https://github.com/rgbkrk/bookstore) package currently allows users to store notebooks on Rackspace CloudFiles or OpenStack Swift based object stores.\n",
"\n",
"Writing a notebook manager is as simple as extending the base class `NotebookManager`. The [simple_notebook_manager](https://github.com/khinsen/simple_notebook_manager) provides a great example\n",
"of an in memory notebook manager, created solely for the purpose of\n",
"illustrating the notebook manager API."
"name": "stdout",
"output_type": "stream",
"text": [
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_config.py'\r\n",
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_qtconsole_config.py'\r\n",
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_notebook_config.py'\r\n",
"[ProfileCreate] Generating default config file: u'/Users/bgranger/.ipython/profile_my_profile/ipython_nbconvert_config.py'\r\n"
]
},
}
],
"source": [
"!ipython profile create my_profile"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And then view its location:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Known issues"
"name": "stdout",
"output_type": "stream",
"text": [
"/Users/bgranger/.ipython/profile_my_profile\r\n"
]
},
}
],
"source": [
"!ipython profile locate my_profile"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To start the notebook server using a given profile, run the following:\n",
"\n",
" ipython notebook --profile=my_profile"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More details about IPython configuration files and profiles can be found [here](http://ipython.org/ipython-doc/dev/config/intro.html)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Securing the notebook server"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook allows arbitrary code execution on the computer running it. Thus, the notebook web server should never be run on the open internet without first securing it. By default, the notebook server only listens on local network interface (`127.0.0.1`) There are two steps required to secure the notebook server:\n",
"\n",
"1. Setting a password\n",
"2. Encrypt network traffic using SSL"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Setting a password"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can protect your notebook server with a simple single password by setting the `NotebookApp.password` configurable. You can prepare a hashed password using the function `IPython.lib.passwd`:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"cell_type": "markdown",
"data": {
"text/plain": [
"'sha1:6c2164fc2b22:ed55ecf07fc0f985ab46561483c0e888e8964ae6'"
]
},
"execution_count": 1,
"metadata": {},
"source": [
"When behind a proxy, especially if your system or browser is set to autodetect the proxy, the notebook web application might fail to connect to the server's websockets, and present you with a warning at startup. In this case, you need to configure your system not to use the proxy for the server's address.\n",
"\n",
"For example, in Firefox, go to the Preferences panel, Advanced section,\n",
"Network tab, click 'Settings...', and add the address of the notebook server\n",
"to the 'No proxy for' field."
]
"output_type": "execute_result"
}
],
"metadata": {}
"source": [
"from IPython.lib import passwd\n",
"password = passwd(\"secret\")\n",
"password"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can then add this to your `ipython_notebook_config.py`:\n",
"\n",
"```python\n",
"# Password to use for web authentication\n",
"c = get_config()\n",
"c.NotebookApp.password = \n",
"u'sha1:6c2164fc2b22:ed55ecf07fc0f985ab46561483c0e888e8964ae6'\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Using SSL/HTTPS"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When using a password, it is a good idea to also use SSL, so that your \n",
"password is not sent unencrypted by your browser to the web server. When running the notebook on the public internet this is absolutely required.\n",
"\n",
"The first step is to generate an SSL certificate. A self-signed certificate can be generated with ``openssl``. For example, the following command will create a certificate valid for 365 days with both the key and certificate data written to the same file:\n",
"\n",
" openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem\n",
"\n",
"In most cases, you should run this command in your profile directory, which will make it easy to use the generated key and certificate.\n",
"\n",
"When you connect to a notebook server over HTTPS using a self-signed certificate, your browser will warn you of a dangerous certificate because it is self-signed. If you want to have a fully compliant certificate that will not raise warnings, it is possible (but rather involved) to obtain one,\n",
"as explained in detail in [this tutorial](http://arstechnica.com/security/news/2009/12/how-to-get-set-with-a-secure-sertificate-for-free.ars)\n",
"\t\n",
"When you enable SSL support, you will need to access the notebook server over ``https://``, rather than plain ``http://``. The startup message from the notebook server prints the correct URL, but it is easy to overlook and think the server is for some reason non-responsive.\n",
"\n",
"Once you have generated the key and certificate, you can configure the notebook server to use them, by adding the following to `ipython_notebook_config.py`:\n",
"\n",
"```python\n",
"# The full path to an SSL/TLS certificate file.\n",
"c.NotebookApp.certfile = u'/Users/bgranger/.ipython/profile_my_profile/mycert.crt'\n",
"\n",
"# The full path to a private key file for usage with SSL/TLS.\n",
"c.NotebookApp.keyfile = u'/Users/bgranger/.ipython/profile_my_profile/mycert.key'\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running a public notebook server"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-error\">\n",
"Don't run a public notebook server unless you first secure it with a password and SSL/HTTPS as described above\n",
"</div>\n",
"\n",
"By default the notebook server only listens on the `localhost/127.0.0.1` network interface. If you want to connect to the notebook from another computers, or over the internet, you need to configure the notebook server to listen on all network interfaces and not open the browser. You will often also want to disable the automatic launching of the web browser.\n",
"\n",
"This can be accomplished by passing a command line options.\n",
"\n",
" ipython notebook --ip=* --no-browser\n",
"\n",
"You can also add the following to your`ipython_notebook_config.py` file:\n",
"\n",
"```python\n",
"c.NotebookApp.ip = '*'\n",
"c.NotebookApp.open_browser = False\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running with a different URL prefix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook dashboard typically lives at the URL `http://localhost:8888/tree`. If you prefer that it lives, together with the \n",
"rest of the notebook web application, under a base URL prefix, such as `http://localhost:8888/ipython/tree`, you can do so by adding the following lines to your `ipython_notebook_config.py` file.\n",
"\n",
"```python\n",
"c.NotebookApp.base_url = '/ipython/'\n",
"c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using a different notebook store"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By default, the notebook server stores the notebook documents that it saves as files in the working directory of the notebook server, also known as the\n",
"`notebook_dir`. This logic is implemented in the `FileNotebookManager` class. However, the server can be configured to use a different notebook manager class, which can store the notebooks in a different format. \n",
"\n",
"The [bookstore](https://github.com/rgbkrk/bookstore) package currently allows users to store notebooks on Rackspace CloudFiles or OpenStack Swift based object stores.\n",
"\n",
"Writing a notebook manager is as simple as extending the base class `NotebookManager`. The [simple_notebook_manager](https://github.com/khinsen/simple_notebook_manager) provides a great example\n",
"of an in memory notebook manager, created solely for the purpose of\n",
"illustrating the notebook manager API."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Known issues"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When behind a proxy, especially if your system or browser is set to autodetect the proxy, the notebook web application might fail to connect to the server's websockets, and present you with a warning at startup. In this case, you need to configure your system not to use the proxy for the server's address.\n",
"\n",
"For example, in Firefox, go to the Preferences panel, Advanced section,\n",
"Network tab, click 'Settings...', and add the address of the notebook server\n",
"to the 'No proxy for' field."
]
}
]
],
"metadata": {
"signature": "sha256:ee4b22b4c949fe21b3e5cda24f0916ba59d8c09443f4a897d98b96d4a73ac335"
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,260 +1,253 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Markdown parser included in IPython is MathJax-aware. This means that you can freely mix in mathematical expressions using the [MathJax subset of Tex and LaTeX](http://docs.mathjax.org/en/latest/tex.html#tex-support). [Some examples from the MathJax site](http://www.mathjax.org/demos/tex-samples/) are reproduced below, as well as the Markdown+TeX source."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Motivating Examples\n",
"\n",
"---\n",
"\n",
"## The Lorenz Equations\n",
"### Source\n",
"```\\begin{align}\n",
"\\dot{x} & = \\sigma(y-x) \\\\\n",
"\\dot{y} & = \\rho x - y - xz \\\\\n",
"\\dot{z} & = -\\beta z + xy\n",
"\\end{align}\n",
"```\n",
"### Display\n",
"\\begin{align}\n",
"\\dot{x} & = \\sigma(y-x) \\\\\n",
"\\dot{y} & = \\rho x - y - xz \\\\\n",
"\\dot{z} & = -\\beta z + xy\n",
"\\end{align}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Cauchy-Schwarz Inequality\n",
"### Source\n",
"```\\begin{equation*}\n",
"\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A Cross Product Formula\n",
"### Source\n",
"```\\begin{equation*}\n",
"\\mathbf{V}_1 \\times \\mathbf{V}_2 = \\begin{vmatrix}\n",
"\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n",
"\\frac{\\partial X}{\\partial u} & \\frac{\\partial Y}{\\partial u} & 0 \\\\\n",
"\\frac{\\partial X}{\\partial v} & \\frac{\\partial Y}{\\partial v} & 0\n",
"\\end{vmatrix} \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"\\mathbf{V}_1 \\times \\mathbf{V}_2 = \\begin{vmatrix}\n",
"\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n",
"\\frac{\\partial X}{\\partial u} & \\frac{\\partial Y}{\\partial u} & 0 \\\\\n",
"\\frac{\\partial X}{\\partial v} & \\frac{\\partial Y}{\\partial v} & 0\n",
"\\end{vmatrix} \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The probability of getting \\(k\\) heads when flipping \\(n\\) coins is\n",
"### Source\n",
"```\\begin{equation*}\n",
"P(E) = {n \\choose k} p^k (1-p)^{ n-k} \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"P(E) = {n \\choose k} p^k (1-p)^{ n-k} \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## An Identity of Ramanujan\n",
"### Source\n",
"```\\begin{equation*}\n",
"\\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} =\n",
"1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}\n",
"{1+\\frac{e^{-8\\pi}} {1+\\ldots} } } } \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"\\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} =\n",
"1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}\n",
"{1+\\frac{e^{-8\\pi}} {1+\\ldots} } } } \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A Rogers-Ramanujan Identity\n",
"### Source\n",
"```\\begin{equation*}\n",
"1 + \\frac{q^2}{(1-q)}+\\frac{q^6}{(1-q)(1-q^2)}+\\cdots =\n",
"\\prod_{j=0}^{\\infty}\\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},\n",
"\\quad\\quad \\text{for $|q|<1$}. \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"1 + \\frac{q^2}{(1-q)}+\\frac{q^6}{(1-q)(1-q^2)}+\\cdots =\n",
"\\prod_{j=0}^{\\infty}\\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},\n",
"\\quad\\quad \\text{for $|q|<1$}. \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Maxwell's Equations\n",
"### Source\n",
"```\\begin{align}\n",
"\\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 \\\\\n",
"\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n",
"\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n",
"\\end{align}\n",
"```\n",
"### Display\n",
"\\begin{align}\n",
"\\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 \\\\\n",
"\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n",
"\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n",
"\\end{align}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Equation Numbering and References\n",
"\n",
"---\n",
"\n",
"Equation numbering and referencing will be available in a future version of IPython."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Inline Typesetting (Mixing Markdown and TeX)\n",
"\n",
"---\n",
"\n",
"While display equations look good for a page of samples, the ability to mix math and *formatted* **text** in a paragraph is also important.\n",
"\n",
"## Source\n",
"``` This expression $\\sqrt{3x-1}+(1+x)^2$ is an example of a TeX inline equation in a **[Markdown-formatted](http://daringfireball.net/projects/markdown/)** sentence. \n",
"```\n",
"## Display\n",
"This expression $\\sqrt{3x-1}+(1+x)^2$ is an example of a TeX inline equation in a **[Markdown-formatted](http://daringfireball.net/projects/markdown/)** sentence. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Other Syntax\n",
"\n",
"---\n",
"\n",
"You will notice in other places on the web that `$$` are needed explicitly to begin and end MathJax typesetting. This is **not** required if you will be using TeX environments, but the IPython notebook will accept this syntax on legacy notebooks. \n",
"\n",
"### Source\n",
"```\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\\\\\\n",
"y_2 \\mathtt{t}_i \\\\\\\n",
"z_{3,4}\n",
"\\end{array}\n",
"$$\n",
"```\n",
"\n",
"```\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\cr\n",
"y_2 \\mathtt{t}_i \\cr\n",
"y_{3}\n",
"\\end{array}\n",
"$$\n",
"```\n",
"\n",
"```\n",
"$$\\begin{eqnarray} \n",
"x' &=& &x \\sin\\phi &+& z \\cos\\phi \\\\\n",
"z' &=& - &x \\cos\\phi &+& z \\sin\\phi \\\\\n",
"\\end{eqnarray}$$\n",
"```\n",
"\n",
"```\n",
"$$\n",
"x=4\n",
"$$\n",
"```\n",
"\n",
"### Display\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\\\\\\n",
"y_2 \\mathtt{t}_i \\\\\\\n",
"z_{3,4}\n",
"\\end{array}\n",
"$$\n",
"\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\cr\n",
"y_2 \\mathtt{t}_i \\cr\n",
"y_{3}\n",
"\\end{array}\n",
"$$\n",
"\n",
"$$\\begin{eqnarray} \n",
"x' &=& &x \\sin\\phi &+& z \\cos\\phi \\\\\n",
"z' &=& - &x \\cos\\phi &+& z \\sin\\phi \\\\\n",
"\\end{eqnarray}$$\n",
"\n",
"$$\n",
"x=4\n",
"$$"
]
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"The Markdown parser included in IPython is MathJax-aware. This means that you can freely mix in mathematical expressions using the [MathJax subset of Tex and LaTeX](http://docs.mathjax.org/en/latest/tex.html#tex-support). [Some examples from the MathJax site](http://www.mathjax.org/demos/tex-samples/) are reproduced below, as well as the Markdown+TeX source."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Motivating Examples\n",
"\n",
"---\n",
"\n",
"## The Lorenz Equations\n",
"### Source\n",
"```\\begin{align}\n",
"\\dot{x} & = \\sigma(y-x) \\\\\n",
"\\dot{y} & = \\rho x - y - xz \\\\\n",
"\\dot{z} & = -\\beta z + xy\n",
"\\end{align}\n",
"```\n",
"### Display\n",
"\\begin{align}\n",
"\\dot{x} & = \\sigma(y-x) \\\\\n",
"\\dot{y} & = \\rho x - y - xz \\\\\n",
"\\dot{z} & = -\\beta z + xy\n",
"\\end{align}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Cauchy-Schwarz Inequality\n",
"### Source\n",
"```\\begin{equation*}\n",
"\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A Cross Product Formula\n",
"### Source\n",
"```\\begin{equation*}\n",
"\\mathbf{V}_1 \\times \\mathbf{V}_2 = \\begin{vmatrix}\n",
"\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n",
"\\frac{\\partial X}{\\partial u} & \\frac{\\partial Y}{\\partial u} & 0 \\\\\n",
"\\frac{\\partial X}{\\partial v} & \\frac{\\partial Y}{\\partial v} & 0\n",
"\\end{vmatrix} \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"\\mathbf{V}_1 \\times \\mathbf{V}_2 = \\begin{vmatrix}\n",
"\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n",
"\\frac{\\partial X}{\\partial u} & \\frac{\\partial Y}{\\partial u} & 0 \\\\\n",
"\\frac{\\partial X}{\\partial v} & \\frac{\\partial Y}{\\partial v} & 0\n",
"\\end{vmatrix} \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The probability of getting \\(k\\) heads when flipping \\(n\\) coins is\n",
"### Source\n",
"```\\begin{equation*}\n",
"P(E) = {n \\choose k} p^k (1-p)^{ n-k} \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"P(E) = {n \\choose k} p^k (1-p)^{ n-k} \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## An Identity of Ramanujan\n",
"### Source\n",
"```\\begin{equation*}\n",
"\\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} =\n",
"1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}\n",
"{1+\\frac{e^{-8\\pi}} {1+\\ldots} } } } \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"\\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} =\n",
"1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}\n",
"{1+\\frac{e^{-8\\pi}} {1+\\ldots} } } } \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A Rogers-Ramanujan Identity\n",
"### Source\n",
"```\\begin{equation*}\n",
"1 + \\frac{q^2}{(1-q)}+\\frac{q^6}{(1-q)(1-q^2)}+\\cdots =\n",
"\\prod_{j=0}^{\\infty}\\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},\n",
"\\quad\\quad \\text{for $|q|<1$}. \n",
"\\end{equation*}\n",
"```\n",
"### Display\n",
"\\begin{equation*}\n",
"1 + \\frac{q^2}{(1-q)}+\\frac{q^6}{(1-q)(1-q^2)}+\\cdots =\n",
"\\prod_{j=0}^{\\infty}\\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},\n",
"\\quad\\quad \\text{for $|q|<1$}. \n",
"\\end{equation*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Maxwell's Equations\n",
"### Source\n",
"```\\begin{align}\n",
"\\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 \\\\\n",
"\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n",
"\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n",
"\\end{align}\n",
"```\n",
"### Display\n",
"\\begin{align}\n",
"\\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 \\\\\n",
"\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n",
"\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n",
"\\end{align}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Equation Numbering and References\n",
"\n",
"---\n",
"\n",
"Equation numbering and referencing will be available in a future version of IPython."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Inline Typesetting (Mixing Markdown and TeX)\n",
"\n",
"---\n",
"\n",
"While display equations look good for a page of samples, the ability to mix math and *formatted* **text** in a paragraph is also important.\n",
"\n",
"## Source\n",
"``` This expression $\\sqrt{3x-1}+(1+x)^2$ is an example of a TeX inline equation in a **[Markdown-formatted](http://daringfireball.net/projects/markdown/)** sentence. \n",
"```\n",
"## Display\n",
"This expression $\\sqrt{3x-1}+(1+x)^2$ is an example of a TeX inline equation in a **[Markdown-formatted](http://daringfireball.net/projects/markdown/)** sentence. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Other Syntax\n",
"\n",
"---\n",
"\n",
"You will notice in other places on the web that `$$` are needed explicitly to begin and end MathJax typesetting. This is **not** required if you will be using TeX environments, but the IPython notebook will accept this syntax on legacy notebooks. \n",
"\n",
"### Source\n",
"```\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\\\\\\n",
"y_2 \\mathtt{t}_i \\\\\\\n",
"z_{3,4}\n",
"\\end{array}\n",
"$$\n",
"```\n",
"\n",
"```\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\cr\n",
"y_2 \\mathtt{t}_i \\cr\n",
"y_{3}\n",
"\\end{array}\n",
"$$\n",
"```\n",
"\n",
"```\n",
"$$\\begin{eqnarray} \n",
"x' &=& &x \\sin\\phi &+& z \\cos\\phi \\\\\n",
"z' &=& - &x \\cos\\phi &+& z \\sin\\phi \\\\\n",
"\\end{eqnarray}$$\n",
"```\n",
"\n",
"```\n",
"$$\n",
"x=4\n",
"$$\n",
"```\n",
"\n",
"### Display\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\\\\\\n",
"y_2 \\mathtt{t}_i \\\\\\\n",
"z_{3,4}\n",
"\\end{array}\n",
"$$\n",
"\n",
"$$\n",
"\\begin{array}{c}\n",
"y_1 \\cr\n",
"y_2 \\mathtt{t}_i \\cr\n",
"y_{3}\n",
"\\end{array}\n",
"$$\n",
"\n",
"$$\\begin{eqnarray} \n",
"x' &=& &x \\sin\\phi &+& z \\cos\\phi \\\\\n",
"z' &=& - &x \\cos\\phi &+& z \\sin\\phi \\\\\n",
"\\end{eqnarray}$$\n",
"\n",
"$$\n",
"x=4\n",
"$$"
]
}
]
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because one or more lines are too long

@ -1,180 +1,168 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# What is the IPython Notebook?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook is an **interactive computing environment** that enables users to author notebook documents that include: \n",
"- Live code\n",
"- Interactive widgets\n",
"- Plots\n",
"- Narrative text\n",
"- Equations\n",
"- Images\n",
"- Video\n",
"\n",
"These documents provide a **complete and self-contained record of a computation** that can be converted to various formats and shared with others using email, [Dropbox](http://dropbox.com), version control systems (like git/[GitHub](http://github.com)) or [nbviewer.ipython.org](http://nbviewer.ipython.org)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Components"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook combines three components:\n",
"\n",
"* **The notebook web application**: An interactive web application for writing and running code interactively and authoring notebook documents.\n",
"* **Kernels**: Separate processes started by the notebook web application that runs users' code in a given language and returns output back to the notebook web application. The kernel also handles things like computations for interactive widgets, tab completion and introspection. \n",
"* **Notebook documents**: Self-contained documents that contain a representation of all content visible in the notebook web application, including inputs and outputs of the computations, narrative\n",
"text, equations, images, and rich media representations of objects. Each notebook document has its own kernel."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Notebook web application"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook web application enables users to:\n",
"\n",
"* **Edit code in the browser**, with automatic syntax highlighting, indentation, and tab completion/introspection.\n",
"* **Run code from the browser**, with the results of computations attached to the code which generated them.\n",
"* See the results of computations with **rich media representations**, such as HTML, LaTeX, PNG, SVG, PDF, etc.\n",
"* Create and use **interactive JavaScript wigets**, which bind interactive user interface controls and visualizations to reactive kernel side computations.\n",
"* Author **narrative text** using the [Markdown](https://daringfireball.net/projects/markdown/) markup language.\n",
"* Build **hierarchical documents** that are organized into sections with different levels of headings.\n",
"* Include mathematical equations using **LaTeX syntax in Markdown**, which are rendered in-browser by [MathJax](http://www.mathjax.org/).\n",
"* Start **parallel computing** clusters that work with IPython's interactive parallel computing libraries `IPython.parallel`."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Kernels"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Through IPython's kernel and messaging architecture, the Notebook allows code to be run in a range of different programming languages. For each notebook document that a user opens, the web application starts a kernel that runs the code for that notebook. Each kernel is capable of running code in a single programming language and there are kernels available in the following languages:\n",
"\n",
"* Python(https://github.com/ipython/ipython)\n",
"* Julia (https://github.com/JuliaLang/IJulia.jl)\n",
"* R (https://github.com/takluyver/IRkernel)\n",
"* Ruby (https://github.com/minrk/iruby)\n",
"* Haskell (https://github.com/gibiansky/IHaskell)\n",
"* Scala (https://github.com/Bridgewater/scala-notebook)\n",
"* node.js (https://gist.github.com/Carreau/4279371)\n",
"* Go (https://github.com/takluyver/igo)\n",
"\n",
"The default kernel runs Python code. When it is released in the Summer/Fall of 2014, IPython 3.0 will provide a simple way for users to pick which of these kernels is used for a given notebook. \n",
"\n",
"Each of these kernels communicate with the notebook web application and web browser using a JSON over ZeroMQ/WebSockets message protocol that is described [here](http://ipython.org/ipython-doc/dev/development/messaging.html). Most users don't need to know about these details, but it helps to understand that \"kernels run code.\""
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Notebook documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notebook documents contain the **inputs and outputs** of an interactive session as well as **narrative text** that accompanies the code but is not meant for execution. **Rich output** generated by running code, including HTML, images, video, and plots, is embeddeed in the notebook, which makes it a complete and self-contained record of a computation. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you run the notebook web application on your computer, notebook documents are just **files on your local filesystem with a `.ipynb` extension**. This allows you to use familiar workflows for organizing your notebooks into folders and sharing them with others using email, Dropbox and version control systems."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notebooks consist of a **linear sequence of cells**. There are four basic cell types:\n",
"\n",
"* **Code cells:** Input and output of live code that is run in the kernel\n",
"* **Markdown cells:** Narrative text with embedded LaTeX equations\n",
"* **Heading cells:** 6 levels of hierarchical organization and formatting\n",
"* **Raw cells:** Unformatted text that is included, without modification, when notebooks are converted to different formats using nbconvert\n",
"\n",
"Internally, notebook documents are **[JSON](http://en.wikipedia.org/wiki/JSON) data** with **binary values [base64](http://en.wikipedia.org/wiki/Base64)** encoded. This allows them to be **read and manipulated programmatically** by any programming language. Because JSON is a text format, notebook documents are version control friendly.\n",
"\n",
"**Notebooks can be exported** to different static formats including HTML, reStructeredText, LaTeX, PDF, and slide shows ([reveal.js](http://lab.hakim.se/reveal-js/#/)) using IPython's `nbconvert` utility.\n",
"\n",
"Furthermore, any notebook document available from a **public URL on or GitHub can be shared** via [nbviewer](http://nbviewer.ipython.org). This service loads the notebook document from the URL and renders it as a static web page. The resulting web page may thus be shared with others **without their needing to install IPython**."
]
}
],
"metadata": {
"celltoolbar": "Slideshow",
"name": "",
"signature": "sha256:86e99da10fb4a123108149196f182861fa434fb59520b256405c6052601c2486"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"What is the IPython Notebook?"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Introduction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook is an **interactive computing environment** that enables users to author notebook documents that include: \n",
"- Live code\n",
"- Interactive widgets\n",
"- Plots\n",
"- Narrative text\n",
"- Equations\n",
"- Images\n",
"- Video\n",
"\n",
"These documents provide a **complete and self-contained record of a computation** that can be converted to various formats and shared with others using email, [Dropbox](http://dropbox.com), version control systems (like git/[GitHub](http://github.com)) or [nbviewer.ipython.org](http://nbviewer.ipython.org)."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Components"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The IPython Notebook combines three components:\n",
"\n",
"* **The notebook web application**: An interactive web application for writing and running code interactively and authoring notebook documents.\n",
"* **Kernels**: Separate processes started by the notebook web application that runs users' code in a given language and returns output back to the notebook web application. The kernel also handles things like computations for interactive widgets, tab completion and introspection. \n",
"* **Notebook documents**: Self-contained documents that contain a representation of all content visible in the notebook web application, including inputs and outputs of the computations, narrative\n",
"text, equations, images, and rich media representations of objects. Each notebook document has its own kernel."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Notebook web application"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook web application enables users to:\n",
"\n",
"* **Edit code in the browser**, with automatic syntax highlighting, indentation, and tab completion/introspection.\n",
"* **Run code from the browser**, with the results of computations attached to the code which generated them.\n",
"* See the results of computations with **rich media representations**, such as HTML, LaTeX, PNG, SVG, PDF, etc.\n",
"* Create and use **interactive JavaScript wigets**, which bind interactive user interface controls and visualizations to reactive kernel side computations.\n",
"* Author **narrative text** using the [Markdown](https://daringfireball.net/projects/markdown/) markup language.\n",
"* Build **hierarchical documents** that are organized into sections with different levels of headings.\n",
"* Include mathematical equations using **LaTeX syntax in Markdown**, which are rendered in-browser by [MathJax](http://www.mathjax.org/).\n",
"* Start **parallel computing** clusters that work with IPython's interactive parallel computing libraries `IPython.parallel`."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Kernels"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Through IPython's kernel and messaging architecture, the Notebook allows code to be run in a range of different programming languages. For each notebook document that a user opens, the web application starts a kernel that runs the code for that notebook. Each kernel is capable of running code in a single programming language and there are kernels available in the following languages:\n",
"\n",
"* Python(https://github.com/ipython/ipython)\n",
"* Julia (https://github.com/JuliaLang/IJulia.jl)\n",
"* R (https://github.com/takluyver/IRkernel)\n",
"* Ruby (https://github.com/minrk/iruby)\n",
"* Haskell (https://github.com/gibiansky/IHaskell)\n",
"* Scala (https://github.com/Bridgewater/scala-notebook)\n",
"* node.js (https://gist.github.com/Carreau/4279371)\n",
"* Go (https://github.com/takluyver/igo)\n",
"\n",
"The default kernel runs Python code. When it is released in the Summer/Fall of 2014, IPython 3.0 will provide a simple way for users to pick which of these kernels is used for a given notebook. \n",
"\n",
"Each of these kernels communicate with the notebook web application and web browser using a JSON over ZeroMQ/WebSockets message protocol that is described [here](http://ipython.org/ipython-doc/dev/development/messaging.html). Most users don't need to know about these details, but it helps to understand that \"kernels run code.\""
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Notebook documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notebook documents contain the **inputs and outputs** of an interactive session as well as **narrative text** that accompanies the code but is not meant for execution. **Rich output** generated by running code, including HTML, images, video, and plots, is embeddeed in the notebook, which makes it a complete and self-contained record of a computation. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you run the notebook web application on your computer, notebook documents are just **files on your local filesystem with a `.ipynb` extension**. This allows you to use familiar workflows for organizing your notebooks into folders and sharing them with others using email, Dropbox and version control systems."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notebooks consist of a **linear sequence of cells**. There are four basic cell types:\n",
"\n",
"* **Code cells:** Input and output of live code that is run in the kernel\n",
"* **Markdown cells:** Narrative text with embedded LaTeX equations\n",
"* **Heading cells:** 6 levels of hierarchical organization and formatting\n",
"* **Raw cells:** Unformatted text that is included, without modification, when notebooks are converted to different formats using nbconvert\n",
"\n",
"Internally, notebook documents are **[JSON](http://en.wikipedia.org/wiki/JSON) data** with **binary values [base64](http://en.wikipedia.org/wiki/Base64)** encoded. This allows them to be **read and manipulated programmatically** by any programming language. Because JSON is a text format, notebook documents are version control friendly.\n",
"\n",
"**Notebooks can be exported** to different static formats including HTML, reStructeredText, LaTeX, PDF, and slide shows ([reveal.js](http://lab.hakim.se/reveal-js/#/)) using IPython's `nbconvert` utility.\n",
"\n",
"Furthermore, any notebook document available from a **public URL on or GitHub can be shared** via [nbviewer](http://nbviewer.ipython.org). This service loads the notebook document from the URL and renders it as a static web page. The resulting web page may thus be shared with others **without their needing to install IPython**."
]
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,319 +1,304 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Markdown Cells"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Text can be added to IPython Notebooks using Markdown cells. Markdown is a popular markup language that is a superset of HTML. Its specification can be found here:\n",
"\n",
"<http://daringfireball.net/projects/markdown/>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Markdown basics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can make text *italic* or **bold**."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can build nested itemized or enumerated lists:\n",
"\n",
"* One\n",
" - Sublist\n",
" - This\n",
" - Sublist\n",
" - That\n",
" - The other thing\n",
"* Two\n",
" - Sublist\n",
"* Three\n",
" - Sublist\n",
"\n",
"Now another list:\n",
"\n",
"1. Here we go\n",
" 1. Sublist\n",
" 2. Sublist\n",
"2. There we go\n",
"3. Now this"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can add horizontal rules:\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a blockquote:\n",
"\n",
"> Beautiful is better than ugly.\n",
"> Explicit is better than implicit.\n",
"> Simple is better than complex.\n",
"> Complex is better than complicated.\n",
"> Flat is better than nested.\n",
"> Sparse is better than dense.\n",
"> Readability counts.\n",
"> Special cases aren't special enough to break the rules.\n",
"> Although practicality beats purity.\n",
"> Errors should never pass silently.\n",
"> Unless explicitly silenced.\n",
"> In the face of ambiguity, refuse the temptation to guess.\n",
"> There should be one-- and preferably only one --obvious way to do it.\n",
"> Although that way may not be obvious at first unless you're Dutch.\n",
"> Now is better than never.\n",
"> Although never is often better than *right* now.\n",
"> If the implementation is hard to explain, it's a bad idea.\n",
"> If the implementation is easy to explain, it may be a good idea.\n",
"> Namespaces are one honking great idea -- let's do more of those!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And shorthand for links:\n",
"\n",
"[IPython's website](http://ipython.org)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Headings"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you want, you can add headings using Markdown's syntax:\n",
"\n",
"# Heading 1\n",
"# Heading 2\n",
"## Heading 2.1\n",
"## Heading 2.2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**BUT most of the time you should use the Notebook's Heading Cells to organize your Notebook content**, as they provide meaningful structure that can be interpreted by other tools, not just large bold fonts."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Embedded code"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can embed code meant for illustration instead of execution in Python:\n",
"\n",
" def f(x):\n",
" \"\"\"a docstring\"\"\"\n",
" return x**2\n",
"\n",
"or other languages:\n",
"\n",
" if (i=0; i<n; i++) {\n",
" printf(\"hello %d\\n\", i);\n",
" x += 4;\n",
" }"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## LaTeX equations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Courtesy of MathJax, you can include mathematical expressions both inline: \n",
"$e^{i\\pi} + 1 = 0$ and displayed:\n",
"\n",
"$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Github flavored markdown (GFM)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Notebook webapp support Github flavored markdown meaning that you can use triple backticks for code blocks \n",
"<pre>\n",
"```python\n",
"print \"Hello World\"\n",
"```\n",
"\n",
"```javascript\n",
"console.log(\"Hello World\")\n",
"```\n",
"</pre>\n",
"\n",
"Gives \n",
"```python\n",
"print \"Hello World\"\n",
"```\n",
"\n",
"```javascript\n",
"console.log(\"Hello World\")\n",
"```\n",
"\n",
"And a table like this : \n",
"\n",
"<pre>\n",
"| This | is |\n",
"|------|------|\n",
"| a | table| \n",
"</pre>\n",
"\n",
"A nice Html Table\n",
"\n",
"| This | is |\n",
"|------|------|\n",
"| a | table| "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## General HTML"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Because Markdown is a superset of HTML you can even add things like HTML tables:\n",
"\n",
"<table>\n",
"<tr>\n",
"<th>Header 1</th>\n",
"<th>Header 2</th>\n",
"</tr>\n",
"<tr>\n",
"<td>row 1, cell 1</td>\n",
"<td>row 1, cell 2</td>\n",
"</tr>\n",
"<tr>\n",
"<td>row 2, cell 1</td>\n",
"<td>row 2, cell 2</td>\n",
"</tr>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Local files"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you have local files in your Notebook directory, you can refer to these files in Markdown cells directly:\n",
"\n",
" [subdirectory/]<filename>\n",
"\n",
"For example, in the images folder, we have the Python logo:\n",
"\n",
" <img src=\"images/python-logo.svg\" />\n",
"\n",
"<img src=\"images/python-logo.svg\" />\n",
"\n",
"and a video with the HTML5 video tag:\n",
"\n",
" <video controls src=\"images/animation.m4v\" />\n",
"\n",
"<video controls src=\"images/animation.m4v\" />\n",
"\n",
"These do not embed the data into the notebook file, and require that the files exist when you are viewing the notebook."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Security of local files"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that this means that the IPython notebook server also acts as a generic file server\n",
"for files inside the same tree as your notebooks. Access is not granted outside the\n",
"notebook folder so you have strict control over what files are visible, but for this\n",
"reason it is highly recommended that you do not run the notebook server with a notebook\n",
"directory at a high level in your filesystem (e.g. your home directory).\n",
"\n",
"When you run the notebook in a password-protected manner, local file access is restricted\n",
"to authenticated users unless read-only views are active."
]
}
],
"metadata": {
"name": "",
"signature": "sha256:3b7cae0c0936f25e6ccb7acafe310c08a4162a1a7fd66fa9874a52cffa0f64f9"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Markdown Cells"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Text can be added to IPython Notebooks using Markdown cells. Markdown is a popular markup language that is a superset of HTML. Its specification can be found here:\n",
"\n",
"<http://daringfireball.net/projects/markdown/>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Markdown basics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can make text *italic* or **bold**."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can build nested itemized or enumerated lists:\n",
"\n",
"* One\n",
" - Sublist\n",
" - This\n",
" - Sublist\n",
" - That\n",
" - The other thing\n",
"* Two\n",
" - Sublist\n",
"* Three\n",
" - Sublist\n",
"\n",
"Now another list:\n",
"\n",
"1. Here we go\n",
" 1. Sublist\n",
" 2. Sublist\n",
"2. There we go\n",
"3. Now this"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can add horizontal rules:\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a blockquote:\n",
"\n",
"> Beautiful is better than ugly.\n",
"> Explicit is better than implicit.\n",
"> Simple is better than complex.\n",
"> Complex is better than complicated.\n",
"> Flat is better than nested.\n",
"> Sparse is better than dense.\n",
"> Readability counts.\n",
"> Special cases aren't special enough to break the rules.\n",
"> Although practicality beats purity.\n",
"> Errors should never pass silently.\n",
"> Unless explicitly silenced.\n",
"> In the face of ambiguity, refuse the temptation to guess.\n",
"> There should be one-- and preferably only one --obvious way to do it.\n",
"> Although that way may not be obvious at first unless you're Dutch.\n",
"> Now is better than never.\n",
"> Although never is often better than *right* now.\n",
"> If the implementation is hard to explain, it's a bad idea.\n",
"> If the implementation is easy to explain, it may be a good idea.\n",
"> Namespaces are one honking great idea -- let's do more of those!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And shorthand for links:\n",
"\n",
"[IPython's website](http://ipython.org)"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Headings"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you want, you can add headings using Markdown's syntax:\n",
"\n",
"# Heading 1\n",
"# Heading 2\n",
"## Heading 2.1\n",
"## Heading 2.2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**BUT most of the time you should use the Notebook's Heading Cells to organize your Notebook content**, as they provide meaningful structure that can be interpreted by other tools, not just large bold fonts."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Embedded code"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can embed code meant for illustration instead of execution in Python:\n",
"\n",
" def f(x):\n",
" \"\"\"a docstring\"\"\"\n",
" return x**2\n",
"\n",
"or other languages:\n",
"\n",
" if (i=0; i<n; i++) {\n",
" printf(\"hello %d\\n\", i);\n",
" x += 4;\n",
" }"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"LaTeX equations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Courtesy of MathJax, you can include mathematical expressions both inline: \n",
"$e^{i\\pi} + 1 = 0$ and displayed:\n",
"\n",
"$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Github flavored markdown (GFM)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Notebook webapp support Github flavored markdown meaning that you can use triple backticks for code blocks \n",
"<pre>\n",
"```python\n",
"print \"Hello World\"\n",
"```\n",
"\n",
"```javascript\n",
"console.log(\"Hello World\")\n",
"```\n",
"</pre>\n",
"\n",
"Gives \n",
"```python\n",
"print \"Hello World\"\n",
"```\n",
"\n",
"```javascript\n",
"console.log(\"Hello World\")\n",
"```\n",
"\n",
"And a table like this : \n",
"\n",
"<pre>\n",
"| This | is |\n",
"|------|------|\n",
"| a | table| \n",
"</pre>\n",
"\n",
"A nice Html Table\n",
"\n",
"| This | is |\n",
"|------|------|\n",
"| a | table| "
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"General HTML"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Because Markdown is a superset of HTML you can even add things like HTML tables:\n",
"\n",
"<table>\n",
"<tr>\n",
"<th>Header 1</th>\n",
"<th>Header 2</th>\n",
"</tr>\n",
"<tr>\n",
"<td>row 1, cell 1</td>\n",
"<td>row 1, cell 2</td>\n",
"</tr>\n",
"<tr>\n",
"<td>row 2, cell 1</td>\n",
"<td>row 2, cell 2</td>\n",
"</tr>\n",
"</table>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Local files"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you have local files in your Notebook directory, you can refer to these files in Markdown cells directly:\n",
"\n",
" [subdirectory/]<filename>\n",
"\n",
"For example, in the images folder, we have the Python logo:\n",
"\n",
" <img src=\"images/python-logo.svg\" />\n",
"\n",
"<img src=\"images/python-logo.svg\" />\n",
"\n",
"and a video with the HTML5 video tag:\n",
"\n",
" <video controls src=\"images/animation.m4v\" />\n",
"\n",
"<video controls src=\"images/animation.m4v\" />\n",
"\n",
"These do not embed the data into the notebook file, and require that the files exist when you are viewing the notebook."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Security of local files"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that this means that the IPython notebook server also acts as a generic file server\n",
"for files inside the same tree as your notebooks. Access is not granted outside the\n",
"notebook folder so you have strict control over what files are visible, but for this\n",
"reason it is highly recommended that you do not run the notebook server with a notebook\n",
"directory at a high level in your filesystem (e.g. your home directory).\n",
"\n",
"When you run the notebook in a password-protected manner, local file access is restricted\n",
"to authenticated users unless read-only views are active."
]
}
],
"metadata": {}
}
]
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,59 +1,51 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"My Notebook"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def foo():\n",
" return \"foo\""
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def has_ip_syntax():\n",
" listing = !ls\n",
" return listing"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def whatsmyname():\n",
" return __name__"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 4
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"# My Notebook"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def foo():\n",
" return \"foo\""
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def has_ip_syntax():\n",
" listing = !ls\n",
" return listing"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def whatsmyname():\n",
" return __name__"
]
}
]
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 0
}

@ -1,33 +1,26 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook just defines `bar`"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def bar(x):\n",
" return \"bar\" * x"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook just defines `bar`"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def bar(x):\n",
" return \"bar\" * x"
]
}
]
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 0
}
Loading…
Cancel
Save