Does anyone know how to make a shortcut that would paste a certain code to the selected cell or expand a snippet into a chunk of code?
For example I would like to fill a cell with a list of useful imports when pressing something like Ctrl+Shift+M. This would expand the cell content to:
import numpy as np
import pandas as pd
(...) .
Optionally this could work also like text completion tools available in some IDEs. For example when I write something like:
;imp + TAB .
it would expand into the same list as above.
Any ideas how this could be defined in JupyterLab?
I saw this answer, but it does not work for me (returning javascript error)
In JupyterLab 2.1+ you can add a shortcut to insert a snippet using the following settings:
{
"shortcuts": [
{
"command": "apputils:run-first-enabled",
"selector": "body",
"keys": ["Accel Shift M"],
"args": {
"commands": [
"console:replace-selection",
"fileeditor:replace-selection",
"notebook:replace-selection",
],
"args": {"text": "import numpy as np\nimport pandas as pd\n"}
}
}
]
}
For more detailed instruction see my new answer to the question you linked.
Another option is to use one of the code snippet extensions for JupyterLab:
jupyterlab-code-snippets from CalPoly
jupyterlab-snippets from QuantStack
elyra-code-snippet-extension from Elyra IBM team (with multiple contributions from the CalPoly team)
For emmet-style expansion of snippets in IPython, you can use:
from IPython import get_ipython
def import_completer(ipython, event):
return [
'import numpy as np\nimport pandas as pd\n',
'import tensorflow as tf\nimport autokeras as ak\n'
]
ipython = get_ipython()
ipython.set_hook('complete_command', import_completer, re_key='.*imp')
Related
Question: Why does TypeScript/Nx add dist/packages to my path mappings?
I'm converting my polyrepo project to nx monorepo. In my polyrepo, I have a repo mpg-common with src folder, and all other repos import from it: import { Bla } from 'mpg-common/lib/services/.... I want to preserve this import syntax when moving to monorepo, so in tsconfig.base.json I put compilerOptions: { "paths": { "mpg-common/lib/*": ["packages/mpg-common/src/*"]
However, these imports fail. To debug I set "traceResolution": true, and then I see:
Module name 'mpg-common/lib/inversify.config', matched pattern 'mpg-common/lib/*'.
Trying substitution 'dist/packages/mpg-common/lib/*', candidate module location: 'dist/packages/mpg-common/lib/inversify.config'.
So, question: Why does TypeScript/Nx add these dist/packages to my path mappings?
Turns out my package.json had "name": "mpg-common", which caused nx to auto-map mpg-common => dist/packages/mpg-common, which is taken from packages/mpg-common/project.json => targets/build/options/outputPath.
So, solution: change in package.json to "name": "#myworkspace/mpg-common"
I'm wondering if jupyter_client is able to return code sent in to the execute function as HTML somehow?
I'm also wondering if I can do the same with stdout and stderr, as well as markdown?
If jupyter_client cannot do this, is there a jupyter library that does?
Adapting the solution from here might help. This adaptation takes the request of 1+1 or msg_id=c.execute('1+1') and returns the result formatted in html as bold red text with this display(HTML('<div style="color:Red;"><b>' + res + '</b></div>')) using IPython's display module. The kernel info status has been commented out but left for reference.
from subprocess import PIPE
from jupyter_client import KernelManager
from IPython.display import display, HTML
from queue import Empty
km = KernelManager(kernel_name='python3')
km.start_kernel()
# print(km.is_alive())
try:
c = km.client()
msg_id=c.execute('1+1')
state='busy'
data={}
while state!='idle' and c.is_alive():
try:
msg=c.get_iopub_msg(timeout=1)
if not 'content' in msg: continue
content = msg['content']
if 'data' in content:
data=content['data']
if 'execution_state' in content:
state=content['execution_state']
except Empty:
pass
res = data['text/plain']
# print(data)
display(HTML('<div style="color:Red;"><b>' + res + '</b></div>'))
except KeyboardInterrupt:
pass
finally:
km.shutdown_kernel()
# print(km.is_alive())
Also see here for more info.
I have some difficulties to apply a css file to my dash app when using cx_freeze. If I run python app.py the layout is properly applied, however not if I am executing the .exe generated by cx_freeze. Then the default html layout is displayed. The css and the image appear in the same directory where the .exe is located.
This is how my setup.py looks like.
from setuptools import find_packages
from cx_Freeze import setup, Executable
options = {
'build_exe': {
'includes': [
'cx_Logging', 'idna', 'idna.idnadata'
],
'packages': [
'asyncio', 'flask', 'jinja2', 'dash', 'plotly', 'waitress'
],
'excludes': ['tkinter'],
'include_files': [
'assets/logo.jpg', 'assets/style.css'
],
}
}
executables = [
Executable('server.py',
base='console',
targetName='dash_app.exe')
]
setup(
name='BI_Report',
packages=find_packages(),
version='0.0.1',
description='rig',
executables=executables,
options=options
)
To load the external files I use a helper function as suggested here:
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
app = dash.Dash(__name__,
assets_folder=find_data_file('assets/'))
I am using:
Python 3.7.6
dash 1.9.1
cx-freeze 6.1
Any help much appreciated!
Hello this is my first question (iam noob in everything) and iam kind of nervous not to get on your nervouse.
My overall goal is to create a 30 min lesson (part) where pupils can see:
interactive graphics and the super-fency CODE.
get attracted to become software engineers_innen or at least start to read the code. (me Measure the impact)
For this i think Jupyter notebook is the best weapon. For usability reason and different levels of interactivity i started to think about creating html-files to have remote access (my admins will kill me before letting me install sth. more on the school enviroment)
So i saw this:
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import file_html
plot = figure()
plot.circle([1,2], [3,4])
html = file_html(plot, CDN, "my plot")
to create a html out of a bokeh figure.
But how to get nice interact sliders to this standalone html-file.
So how to (even if its non-sense) convert this example:
from ipywidgets import interact
import numpy as np
from bokeh.io import push_notebook, show, output_notebook
from bokeh.plotting import figure
output_notebook()
In [ ]:
x = np.linspace(0, 2*np.pi, 2000)
y = np.sin(x)
In [ ]:
p = figure(title="simple line example", plot_height=300, plot_width=600, y_range=(-5,5))
r = p.line(x, y, color="#2222aa", line_width=3)
In [ ]:
def update(f, w=1, A=1, phi=0):
if f == "sin": func = np.sin
elif f == "cos": func = np.cos
elif f == "tan": func = np.tan
r.data_source.data['y'] = A * func(w * x + phi)
push_notebook()
In [ ]:
show(p, notebook_handle=True)
In [ ]:
interact(update, f=["sin", "cos", "tan"], w=(0,100), A=(1,5), phi=(0, 20, 0.1))
Into sth. like this: https://demo.bokeh.org/sliders
Thanks for every comment. sry my english is not as good as look like, but iam not as smart as i look like
There's not any straightforward way that I know of to make this work in standalone HTML with Jupyter interactors. However, you can make standalone output that accomplishes this with Bokeh's own widgets:
https://docs.bokeh.org/en/latest/docs/gallery/slider.html
There is some ongoing work that should be out with Bokeh 2.0 that will allow Jupyter interactors to work with Bokeh server apps (not standalone output).
I tried to follow the instructions given in the README file of the extension.
Im using Windows and to open my notebooks I use the jupyter-notebook.exe stored in the directory
..\Anaconda3\Scripts
Within the Anaconda3 directory I go to the subdirectory
Anaconda3\Lib\site-packages\jupyter_contrib_nbextensions\nbextensions\snippets
and there change the code of the file "snippets.json" from
{
"snippets" : [
{
"name" : "example",
"code" : [
"# This is an example snippet!",
"# To create your own, add a new snippet block to the",
"# snippets.json file in your jupyter data directory under nbextensions:",
"# $(jupyter --data-dir)/nbextensions/snippets/snippets.json",
"import this"
]
}
]
}
to
{
"snippets" : [
{
"name" : "example",
"code" : [
"# This is a test if something changed",
]
]
}
Then I restart my notebook and insert the example snippet. But my changes weren't adopted, I still get the original example snipped.
What I am doing wrong?
If you are using Anaconda, you don't necessarily need to go searching for directories. There is a template embedded in the "Nbextensions" tab.
Check "Snippets Menu" box
Scroll down to 'Parameters' and check the "Include custom menu...JSON string below" box
Insert whatever sample snippet you want
Refresh your notebook
Check out one of my snippets:
{
"name" : "My favorites",
"sub-menu" : [
{
"name" : "import packages",
"snippet" : ["# import various packages"
"import os"
"import scipy"
"import pandas as pd"
"import numpy as np"
"import seaborn as sns"
"import matplotlib.pyplot as plt"
"%matplotlib inline"
"# plot settings"
"from pandas.plotting import register_matplotlib_converters"
"register_matplotlib_converters()"
"plt.rcParams['agg.path.chunksize'] = 10000"]
},
{
"name" : "TeX can be written in menu labels $\\alpha_W e\\int_0 \\mu \\epsilon$",
"snippet" : ["another_new_command(2.78)"]
}
]
}
Also, be careful with the quotations and commas. Additional help on that can be found here.
In windows(os) jupyter notebook extension are hidden in programData folder (C:\ProgramData\jupyter\nbextensions\snippets)
To make changes in snippet just edit the snippets.JSON file accordingly:
I think you are searching in the wrong directory.
In windows, run command jupyter --paths in anaconda prompt
this will return the locations of config: data: & runtime:
search for the file snippets.json in the data: locations
in my case it is C:\ProgramData\jupyter\nbextensions\snippets
change and save the content in snippets.json and then restart your jupyter notebook
it will work!