Ipywidget Gridbox no output displayed - PYTHON JUPYTER NOTEBOOK - python

I've been going over the Ipywidgets documentation, and found that when ever I use a GridBox, there isn't any output in Jupyter
notebook.
https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Styling.html#Shorthand-CSS-properties
Example with this snippet of code below.
from ipywidgets import Button, GridBox, Layout, ButtonStyle
header = Button(description='Header',
layout=Layout(width='auto', grid_area='header'),
style=ButtonStyle(button_color='lightblue'))
main = Button(description='Main',
layout=Layout(width='auto', grid_area='main'),
style=ButtonStyle(button_color='moccasin'))
sidebar = Button(description='Sidebar',
layout=Layout(width='auto', grid_area='sidebar'),
style=ButtonStyle(button_color='salmon'))
footer = Button(description='Footer',
layout=Layout(width='auto', grid_area='footer'),
style=ButtonStyle(button_color='olive'))
GridBox(children=[header, main, sidebar, footer],
layout=Layout(
width='50%',
grid_template_rows='auto auto auto',
grid_template_columns='25% 25% 25% 25%',
grid_template_areas='''
"header header header header"
"main main . sidebar "
"footer footer footer footer"
'''))
I don't get any output. Does anyone know why? Many thanks in advance :)

Related

Adding Folium Popup Information to table beside map

I am building a map website using Pandas, Django and Folium, with popups displaying information about servers in locations.
I am looking to include all the information that would display on a popup beside the map in a table.
Here is an example popup
I want it in a table like this table view
Currently the table is a for loop iterating over a pandas dataframe. But that displays each row in the dataframe, not information about the specific marker, like the popup does.
The code look like:
locations = Location.objects.values()
loc_data = pd.DataFrame(locations)
for index, location_info in loc_data.iterrows():
# Popup design through Iframe - html variable contains basic html to redesign the popup
html=f"""
<h1>{location_info['hostname']}</h1>
<p>Node Attributes:
<ul>
<li>Structure Name: {location_info["structurename"]}</li>
<li>Domain: {location_info["domain"]}</li>
<li>IP Address: {location_info["ip"]}</li>
<li>Persona: {location_info["personas"]}</li>
</ul>
{location_info["cube"]}
</p>
Login to cube
"""
# Initialise the iframe as a variable and set the popup to be the iframe
iframe = folium.IFrame(html=html, width=350, height=270)
popup = folium.Popup(iframe, max_width=2650)
# Add Markers to the map based on criteria
if location_info["cube"] == "Industrial Cube North":
folium.Marker([location_info["latitude"], location_info["longitude"]], popup=popup, icon=folium.Icon(color='darkred'), tooltip=f'''{location_info["hostname"]}''').add_to(m)
elif location_info["cube"] == "Industrial Cube South":
folium.Marker([location_info["latitude"], location_info["longitude"]], popup=popup, icon=folium.Icon(color='green'), tooltip=f'''{location_info["hostname"]}''').add_to(m)
m=m._repr_html_() #updated
context = {'map': m, 'loc_data': loc_data}
return render(request, 'maps/map.html', context)
This is my html Django template: template
I think it needs some sort of on click event listener to display? Is this possible? Does anyone have any pointers?
EDIT - I have tried passing popup to context but its not iterable.. I also tried iframe but it displays a connection error screen

Sphinx: button inside literalinclude blocks

I have a desktop application and a user guide written in Sphinx. The API is explained with the use of code blocks that are imported with literalinclude blocks.
What I would like to have is a button inside or close to each code block. The button is intended for opening the respective example in our application.
What I have achieved so far (see below) is a button above the code block, that I have to include manually every time I use a literalinclude statement.
How can I put the button inside the code block rather than above?
A particularly beautiful result would be a transparent button like Chris Holdgraf's Sphinx copybutton. But at the moment I would already be happy to have the button as it is located in the top right corner of the code block.
Minimal example of how things are right now
The button is rendered above the code block. But I want to have it inside (at the top right corner).
Folder structure:
conf.py
index.rst
source_file.py
load_source.py
Content of index.rst:
:load_example:`source_file.py`
.. literalinclude:: source_file.py
Content of source_file.py:
import numpy as np
print "hello extension"
for i in range(3):
print np.sin(i)
Content of load_souce.py extension file:
from docutils import nodes
# HTML code to generate button
button_raw = """
<script>
function openScriptFunction() {
callBackHandler.openScript("%s");
}
</script>
<button onclick="openScriptFunction()">Load %s</button>
"""
def setup(app):
app.add_role('load_example', load_example_script)
def load_example_script(name, rawtext, text, lineno, inliner, options={}, content=[]):
node = nodes.raw(rawsource = button_raw%(text, text), text = button_raw%(text, text), format="html")
return [node], []
This extension is included in the conf.py by extensions = ['load_source']

How can I hide code and rerun all cells in a jupyter notebook?

I'd like to add some sort of functionality at the beginning of a Jupyter Notebook that hides / shows all cells and reruns all cells. What I'd like to end up with is a set of charts that are refreshed when all cells are re-run.
The details and what I've tried:
The post IPython - Run all cells below from a widget shows how you can add a button to rerun all cells below. And the post How to hide code from cells in ipython notebook visualized with nbviewer?. With this setup in two different cells I end up with this:
When the cells are collapsed it looks like this:
And this works pretty well, but I'm just really curious if it's possible to format the buttons so that they look the same. And maybe it's possible to align them as output from the same cell? I've tried to do just that by having the two snippets in the same cell, but now it seems that the Hide button is overwritten by the Refresh button:
Snippet 1:
from IPython.display import HTML
HTML('''<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');
$('#toggleButton').val('Show code')
} else {
$('div.input').show('500');
$('#toggleButton').val('Hide code')
}
code_shown = !code_shown
}
$( document ).ready(function(){
code_shown=false;
$('div.input').hide()
});
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show code"></form>''')
from IPython.display import Javascript, display
from ipywidgets import widgets
def run_all(ev):
display(Javascript('IPython.notebook.execute_cells_below()'))
button = widgets.Button(description="Refresh")
button.on_click(run_all)
display(button)
And now I end up with this:
Output 1:
Does anyone know how to make this a bit more elegant?
I really hope someone is able to provide a better answer, but having tried and failed for a couple of hours, I've found this:
By simply mixing a few parts of the two snippets in the question, I'm able to set up a Refresh button in the same format as the Hide Code buttion:
Ouptput / Notebook View:
But this still requiers two code snippets in two different cells, as well as some test code in a third cell:
Cell / snippet 1:
from IPython.display import HTML
HTML('''<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');
$('#toggleButton').val('Display code')
} else {
$('div.input').show('500');
$('#toggleButton').val('Hide Code')
}
code_shown = !code_shown
}
$( document ).ready(function(){
code_shown=false;
$('div.input').hide()
});
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Display code"></form>''')
Cell / snippet 2:
HTML('''<script>
</script>
<form action="javascript:IPython.notebook.execute_cells_below()"><input type="submit" id="toggleButton" value="Refresh"></form>''')
Cell / snippet 3:
try: x
except NameError: x = None
if x is None:
x = 0
print(x)
else:
x = x + 1
print(x)
However, I'm still not able to display the two buttons beautifully side by side, and the display flickers when I hit Refresh.

Issue with Bokeh AutocompleteInput in jupyter notebook cell

I'm using an AutocompleteInput widget in a jupyter notebook. The autocompletion itself is working fine but I have an issue with the output.
Issue circled in red
Is it possible somehow to be able to see the ouput of the autocompletion without having to scroll (which is really not user friendly) ? (resizing the output cell of the notebook, autofiting the cell, option of the AutocompleteInput widet)
this is what i've done at the moment:
input_widget = AutocompleteInput(completions=list(df_competences['libelleCompetence']), title='Chercher une compétence', placeholder='Chercher une compétence', sizing_mode='scale_height', css_classes=['my_autocomplete_class'])
show(input_widget)
I've been looking a lot of possibilities but not founding a way to do this...
In case someone fall on the same issue as me, here is how I manged to fix it:
I'm getting the HTML code generated by bokeh, remove the class used by bokeh and replacing it with my own one. Then, you just need to create your own css class to make the autocompletion output suitable.
Here is the code:
from IPython.display import HTML
input_widget = AutocompleteInput(completions=list(df_competences['libelleCompetence']), title='Chercher une compétence: ', placeholder='Chercher une compétence', sizing_mode='scale_both', css_classes=['my_autocomplete_class'])
script, div = components(input_widget)
div = div.replace('bk-root', 'my_class')
div = div.replace('<div class="my_class"', '<div class="my_class" style="width: 100%; max_height: 500;"')
HTML(script + div)
Add a display HTML command, where you specify the min-height of the displayed suggestion box:
from IPython.core.display import display, HTML
input_widget = AutocompleteInput(completions=list(df_competences['libelleCompetence']), title='Chercher une compétence', placeholder='Chercher une compétence', sizing_mode='scale_height', css_classes=['my_autocomplete_class'])
display(HTML('<style> .bk-root[id] { min-height:100pt } </style>'))
show(input_widget)

Modifying a clipboard content to be treated as HTML

When I “copy an image” on the web (by highlighting the image and ctrl+C) and then passed it into the text view of the HTML WYSIWYG editor (not the source code editor) the picture is displayed. Even though I paste in the text editor ( source code editor), the content of the clipboard is understood by the editor as an html code.
For example, if I simply paste “<img src="someURL" />in the text editor, it will be added in the source code as “<p><img src="someURL" /></p>” so this clipboard isn’t understood by the editor as an html code.
So how should I modify the content of my clipboard so that an HTML WYSIWYG editor understand it as an html code even though I am pasting it in the text view (not source code editor)?
What I want to do in more details:
when I have the URL of an image stored in my clipboard, I want to be able to add the image to the HTML WYSIWYG editor without having to switch to the source code editor. So I would like to transform the content of my clipboard (by adding some code before and after the URL) so it is understood as HTML code (just like the example mentioned above) by my HTML WYSIWYG editor.
Edit: to better target the answer here is what I try to achieve. When I use shareX to upload a picture, ShareX store automatically this (private) shareable URL in the clipboard. https://drive.google.com/open?id=XXXX
This code convert it in an embedded format. But I'm still looking for a way to store that as html format.
#URL_to_Picture.py
#
#(xxx=FileID)
#
#You need that kind of URL to be able to embed the picture in an editor: https://drive.google.com/uc?export=view&id=XXXX
#
#This script does a part of the job by converting Google drive URL into an embedded (and permanent) link:
from jaraco import clipboard
UrlShareX = clipboard.paste_text()
UrlShareX=UrlShareX.replace("https://drive.google.com/file/d/", "")
UrlShareX=UrlShareX.replace("/view?usp=drivesdk", "")
UrlShareX=UrlShareX.replace("/view?usp=sharing", "")
UrlShareX=UrlShareX.replace("https://drive.google.com/open?id=", "")
URL= '<img src="https://drive.google.com/uc?export=view&id={}" />'.format(UrlShareX)
clipboard.copy_html(URL)
To try on ShareX:
You must set the access to Google drive in ShareX menu:
destination/destination settings/google drive.
You must set the ShareX menu: “after upload task” to “copy URL to
clipboard”
I want to be able to add the image to the HTML WYSIWYG editor without having to switch to the source code editor
AHK solution: use a hotkey like ctrl+shift+v
you have plain text in clipboard: https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e
go in WYSIWYG editor and press ctrl+shift+v, it will be pasted in HTML format
HTML format is a clipboard format, so an image will be shown.
what you need is here: WinClipv2\imgSrc to HTML Format\src in clip.ah2
I put the code in a repo because there's a library to include:
https://github.com/FuPeiJiang/WinClipv2
READ the README.md
You can do this:
Install HtmlClipboard : copy the script, save it as HtmlClipboard.py in C:\Python##\Lib\site-packages\
Save the script below as image_link_as_html.py(I used some of your code in your question):
Create a shorcut for the script in step to (right click on the file image_link_as_html.py, and select create a shorcut)
Right click on the shorcut, select Properties, and and add a keyboard shorcut in Shorcut key.
That's it. When you have an image url in our clipboard, you can just press your keyboard shorcut and you can paste your image directly in the html mode of you editor.
image_link_as_html.py (Python34):
from tkinter import Tk
root = Tk()
root.withdraw()
image_url = root.clipboard_get()
# send <img src="https://image_url" alt="" /> to an "HTML format clipboard"
import HtmlClipboard
HtmlClipboard.PutHtml("<img src=\"http://"+image_url+" \" alt=\"\"/>")
To address the part about ShareX, you could use this scrip instead:
from tkinter import Tk
root = Tk()
root.withdraw()
UrlShareX = root.clipboard_get()
# remove everything except the file google ID: this part is not needed
UrlShareX=UrlShareX.replace("https://drive.google.com/file/d/", "")
UrlShareX=UrlShareX.replace("/view?usp=drivesdk", "")
UrlShareX=UrlShareX.replace("/view?usp=sharing", "")
UrlShareX=UrlShareX.replace("https://drive.google.com/open?id=", "")
UrlShareX=UrlShareX.replace("/view", "")
# send <img src="https://drive.google.com/uc?export=view&id=xxx " alt="" /> to an "HTML format clipboard"
import HtmlClipboard
HtmlClipboard.PutHtml("<img src=\"https://drive.google.com/uc?export=view&id="+UrlShareX+" \" alt=\"\"/>")

Categories