Надо было подобрать и настроить ява скрипты для сайта. Если делать это в NOtebook, то можно сразу и отладить и записать варианты настройки. Заманчиво... но как это сделать? Как загружать на страницу jypyter кастомные js скрипты и стили? Оказывается, что вариантов несколько, в зависимости от того, что нам надо. Для глобальных задач есть специальная папка .ipython\profile_default\static\custom\custom.js, файл custom.js автоматически вставляется в тег head страницы. Для тетирования фрагментов кода предусмотрены объекты в IPython.display (Display, HTML, Javascript, IFrame ...), а еще есть магики %%html %%javascript В сочетании с возможностью загрузки внешних скриптов $.getScript('/static/custom/util.js'); и обращения к element.append(myvar) (Use the element variable for printing in the cell output area) все это надо осваивать. Здесь примеры и ссылки.
IPython's Rich Display System
ipython-contrib/IPython-notebook-extensions
IPython: Adding Javascript scripts to IPython notebook -
How do (can) I use a custom.js file under Jupyter notebook?
Can I create an iPython notebook using JavaScript as the language in the cells?
In-browser javascript kernel for Jupyter
IPython Notebook with in-browser Javascript Kernel With this profile, kernel.js is replaced by a simple object that executes javascript in the browser rather than remotely via websockets. This is more of a toy / proof of concept than anything.
Writing a Node.js kernel for IPyton in half an hour This will show you how to write a native kernel for the IPython notebook server using node.js.
Сначала посмотрим на файл custom.js¶
from IPython.display import HTML, Javascript, display
# %load C:\\Users\\alter_000\\.ipython\\profile_default\\static\\custom\\custom.js
// leave at least 2 line with only a star on it below, or doc generation fails
/**
*
*
* Placeholder for custom user javascript
* mainly to be overridden in profile/static/custom/custom.js
* This will always be an empty file in IPython
*
* User could add any javascript in the `profile/static/custom/custom.js` file.
* It will be executed by the ipython notebook at load time.
*
* Same thing with `profile/static/custom/custom.css` to inject custom css into the notebook.
*
*
* The object available at load time depend on the version of IPython in use.
* there is no guaranties of API stability.
*
* The example below explain the principle, and might not be valid.
*
* Instances are created after the loading of this file and might need to be accessed using events:
* define([
* 'base/js/namespace',
* 'base/js/events'
* ], function(IPython, events) {
* events.on("app_initialized.NotebookApp", function () {
* IPython.keyboard_manager....
* });
* });
*
* __Example 1:__
*
* Create a custom button in toolbar that execute `%qtconsole` in kernel
* and hence open a qtconsole attached to the same kernel as the current notebook
*
* define([
* 'base/js/namespace',
* 'base/js/events'
* ], function(IPython, events) {
* events.on('app_initialized.NotebookApp', function(){
* IPython.toolbar.add_buttons_group([
* {
* 'label' : 'run qtconsole',
* 'icon' : 'icon-terminal', // select your icon from http://fortawesome.github.io/Font-Awesome/icons
* 'callback': function () {
* IPython.notebook.kernel.execute('%qtconsole')
* }
* }
* // add more button here if needed.
* ]);
* });
* });
*
* __Example 2:__
*
* At the completion of the dashboard loading, load an unofficial javascript extension
* that is installed in profile/static/custom/
*
* define([
* 'base/js/events'
* ], function(events) {
* events.on('app_initialized.DashboardApp', function(){
* require(['custom/unofficial_extension.js'])
* });
* });
*
* __Example 3:__
*
* Use `jQuery.getScript(url [, success(script, textStatus, jqXHR)] );`
* to load custom script into the notebook.
*
* // to load the metadata ui extension example.
* $.getScript('/static/notebook/js/celltoolbarpresets/example.js');
* // or
* // to load the metadata ui extension to control slideshow mode / reveal js for nbconvert
* $.getScript('/static/notebook/js/celltoolbarpresets/slideshow.js');
*
*
* @module IPython
* @namespace IPython
* @class customjs
* @static
*/
Я понадеялся было, что все файлы из папки Custom вставляются в хидер страницы, быстренько добавил туда custom_se.js и создал новую страницу... Не тут то было, в коде страницы среди прочего красовались custom.css custom.js, а моего файла не было.
First, in .ipython/profile/static/custom/myScript.js, we do some require.js magic:¶
define(function(){
var foo = function(){
console.log('bar');
}
return {
foo : foo
}
});
Copy this pattern for as many functions as you like. Then, in .ipython/profile/static/custom/custom.js, drag those out into something persistent:
$([IPython.events]).on('notebook_loaded.Notebook', function(){
require(['custom/myScript'], function(custom){
window.foo = custom.foo;
} );
});
Yes, I am a horrible person for throwing stuff on the window object, namespace things as you deem appropriate. But now in the notebook, a cell like
%%javascript
foo();
should do exactly what it looks like it should, without the user having to explicitly import your JS. I would love to see a simpler solution for this
$.getScript('/static/custom/util.js');
in custom.js to load up a bunch of global JS functions) - but this is the best I've got for now. This singing and dancing aside, HUGE ups to the IPython notebook team, this is an awesome platform!
As a very short-term solution, you can make use of the IPython display() and HTML() functions to inject some JavaScript into the page.
from IPython.display import display, HTML
js = "<script>alert('Hello World!');</script>"
display(HTML(js))
Although I do not recommend this over the official custom.js method, I do sometimes find it useful to quickly test something or to dynamically generate a small JavaScript snippet.
Exact path and instruction depends on what version of IPython you are running. And that would be
$.getScript("static/Gl.js")
#and
~/.ipython/profile_default/static/[custom]/GI.js.
I would suggest doing a search for IPython custom.js, ask/search on ml/hipchat, because I'm afraid stackoverflow will be a little too limiting to give you all the explanation necessary
!chcp 65001
!dir
You can use the %%javascript magic function for running javascript in IPython notebook. For example Paste the following code in a IPython cell and run it. You should see the output in your browser's javascript console.
%%javascript
console.log("Hello World!")
#For global variables, you can add an attribute to the windows object
#for example, in a cell run the following code:
%%javascript
window.myvar = 12;
#In another cell, run the following code and check browser's javascript console.
#The variable's value should be printed.
%%javascript
console.log(myvar)
#Use the element variable for printing in the cell output area as shown below:
%%javascript
element.append(myvar)
%%javascript
console.log("hi")
#Use the element variable for printing in the cell output area as shown below:
%%javascript
element.append(myvar)
Приложение пример-подсказка¶
display(HTML("""
<p id="demo">A Paragraph.</p>
<button id="something">Try it</button>
"""))
js = """
$(document).ready(
function() {
$("#something").click(function() {
$('#demo').text("Changed text");
$('#something').text('Change button');
});
});
"""
js = Javascript(js)
display(js)
HTML(filename='myhtml.html')
Посты чуть ниже также могут вас заинтересовать
Комментариев нет:
Отправить комментарий