I've been trying to embed an animation into an iPython notebook but without success. I'm using the latest version of Enthought Canopy (python 2.7.3) on a Mac running 10.8.5 using Safari as my default browser.
After much failed experimentation, I tried using this code
%pylab inline
from tempfile import NamedTemporaryFile
VIDEO_TAG = """<video controls>
<source src="data:video/x-m4v;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>"""
def anim_to_html(anim):
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.mp4') as f:
anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
video = open(f.name, "rb").read()
anim._encoded_video = video.encode("base64")
return VIDEO_TAG.format(anim._encoded_video)
from IPython.display import HTML
def display_animation(anim):
plt.close(anim._fig)
return HTML(anim_to_html(anim))
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
# call our new function to display the animation
display_animation(anim)
from jake Vanderplas on the web. I installed ffmpeg.
On running the code I get the video progress bar, but no graph, just an empty space above the video progress bar.
After a couple of days of working on this I've not found a solution (the above is the closest I've come to). Can anyone see what's going wrong or suggestions to try?
Many thanks.
This problem is solved in Jessica Hamrick's comment on Jake Vanderplas's blog at https://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
She added added two additional items to the extra_args argument:
extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p']
Related
I have several buttons which generate images. All work perfectly in Jupyter Notebook, but when I click Voila, and click the buttons, nothing happens. The first button works, but the code is very similar to run other models, yet the other buttons do not work. Is there a work around for this issue?
Edit:
My code which does not show the output when the button is clicked:
compare = {}
button9 = widgets.Button(description = "Report All")
output = widgets.Output()
display(button9, output)
dt = DecisionTreeClassifier(random_state=42)
dt = dt.fit(X_train, y_train)
y_pred = dt.predict(X_test)
compare['Decision Trees'] = [accuracy_score(y_test, y_pred), precision_score(y_test, y_pred), recall_score(y_test, y_pred), f1_score(y_test, y_pred)]
def report_button(b):
compare = pd.DataFrame.from_dict(compare).T
compare.columns = ['Accuracy', 'Precision', 'Recall', 'F1 Score']
compare = com.sort_values('Accuracy', ascending=False)
sns.heatmap(compare, center = True, fmt='.4f', cmap='Blues', annot=True)
button9.on_click(report_button)
However this code displays the output when clicked:
button3 = widgets.Button(description="Decision Trees")
output3 = widgets.Output()
display(button3, output3)
def dt_button(b):
# Decision Trees Classifier
dt = DecisionTreeClassifier(random_state=42)
dt = dt.fit(X_train, y_train)
y_pred = dt.predict(X_test)
compare['Decision Trees'] = [accuracy_score(y_test, y_pred), precision_score(y_test, y_pred_dt), recall_score(y_test, y_pred), f1_score(y_test, y_pred)]
CM = confusion_matrix(y_test, y_pred_dt)
sns.heatmap(CM, center = True, fmt='', cmap='Blues', annot=True)
plt.title('Decision Trees Confusion Matrix')
plt.show()
button3.on_click(dt_button)
Additionally, I am having the issue of MyBinder rendering my file with Voila, but after a few minutes, the MyBinder link shows Error 404.
I'm answering your last question here (about the download button) because I need to add code blocks and comments don't allow that.
You are using Panel in your notebook to do the download and so it works. For Voila you need to stick with ipywidgets-compatible solutions as I discussed earlier. You cannot just add another dashboard extension, Panel, and expect it to work in Voila
Here makes it seem this isn't as easy as it seems.
Suggested Option:
Based on https://stackoverflow.com/a/60013735/8508004 , using SVM_Confusion_Matrix.jpg as the example.
%%html
Click to Download SVM image
Options along that line can even be coded to show up dynamically after an event in VOila, see example code use.
Not suggested but could be useful for similar:
Based on https://github.com/jupyter-widgets/ipywidgets/issues/2471#issuecomment-580965788 (this just opens the image as separate and you have to right-click and save image as)
from IPython.display import display, FileLink
local_file = FileLink('./SVM_Confusion_Matrix.jpg', result_html_prefix="Click here to download: ")
display(local_file)
I would like to add label for edges in networkx graph using bokeh. How can I do this?
This question is similar to How to add permanent name labels (not interactive ones) on nodes for a networkx graph in bokeh? but different enough to warrant its own reply. As discussed in the other issue, this is currently a task that is probably harder than it should be to accomplish. I'd really encourage you to open a GitHub Issue to start a discussion of how this can be improved for users.
Here is complete example.
import networkx as nx
from bokeh.io import output_file, show
from bokeh.models import CustomJSTransform, LabelSet
from bokeh.models.graphs import from_networkx
from bokeh.plotting import figure
G=nx.barbell_graph(3,2)
p = figure(x_range=(-3,3), y_range=(-3,3))
p.grid.grid_line_color = None
r = from_networkx(G, nx.spring_layout, scale=3, center=(0,0))
r.node_renderer.glyph.size=15
r.edge_renderer.glyph.line_alpha=0.2
p.renderers.append(r)
This part is all fairly standard. To put labels on edges we must define transforms to extract the start and end coordinates from the layout provider. This code just averages the coordinates to put a label in the center of each edge (labelled by the start-end node numbers):
from bokeh.transform import transform
# add the labels to the edge renderer data source
source = r.edge_renderer.data_source
source.data['names'] = ["%d-%d" % (x, y) for (x,y) in zip(source.data['start'], source.data['end'])]
# create a transform that can extract and average the actual x,y positions
code = """
const result = new Float64Array(xs.length)
const coords = provider.get_edge_coordinates(source)[%s]
for (let i = 0; i < xs.length; i++) {
result[i] = (coords[i][0] + coords[i][1])/2
}
return result
"""
xcoord = CustomJSTransform(v_func=code % "0", args=dict(provider=r.layout_provider, source=source))
ycoord = CustomJSTransform(v_func=code % "1", args=dict(provider=r.layout_provider, source=source))
# Use the transforms to supply coords to a LabelSet
labels = LabelSet(x=transform('start', xcoord),
y=transform('start', ycoord),
text='names', text_font_size="12px",
x_offset=5, y_offset=5,
source=source, render_mode='canvas')
p.add_layout(labels)
show(p)
Edit 07/2022: Added missing var keyword to JavaScript part, would not show labels otherwise in current bokeh version.
I faced the same problem, I did check https://docs.bokeh.org/en/latest/docs/user_guide/styling.html and found it seems bokeh does not support well for the knowledge graph, including edge labels.
I've tried using the bokeh image_rgba method but found it to be very slow, I'm just displaying a 1000*500 px image and the html takes ~5 seconds to load (nothing is web based here, I have everything running/stored locally)
Again the code itself runs fast, itùs just displaying the image thqt is slow. I've been trying exqmples from the bokeh gallery and the speed is fine.
I'm thus wondering if there is anything I could do for the html to load faster? Is image_rgba the best way to go to display an image with bokeh?
This is the code I use:
pic = PIL.Image.open('/Users/blabla/eiffelTower.jpg')
self.imgArray = np.array(pic)
N1 = imgArray.shape[0]
N2 = imgArray.shape[1]
img = np.zeros((N1,prolongatedN2), dtype=np.uint32)
view = img.view(dtype=np.uint8).reshape((N1, N2, 4))
view[:N1,:N2,0] = self.imgArray[range(N1-1,-1,-1),:N2,0]
view[:N1,:N2,1] = self.imgArray[range(N1-1,-1,-1),:N2,1]
view[:N1,:N2,2] = self.imgArray[range(N1-1,-1,-1),:N2,2]
fig = bokeh.plotting.figure(plot_width = plot_width, plot_height=plot_height)
fig.image_rgba(image=[img], x=[0], y=[0],
dw=[plot_width], dh=[plot_height])
script, div = bokeh.embed.components(p.fig, INLINE)
output_file('testBokeh.html')
show(fig)
Again I'm quite surprised that displaying a locally stored 1000*500 pixels would be so slow.
FWIW, I do this, and it's very fast.
from __future__ import division
import numpy as np
from PIL import Image
from bokeh.plotting import figure, show, output_file
# Open image, and make sure it's RGB*A*
lena_img = Image.open('Lenna_rect.png').convert('RGBA')
xdim, ydim = lena_img.size
print("Dimensions: ({xdim}, {ydim})".format(**locals()))
# Create an array representation for the image `img`, and an 8-bit "4
# layer/RGBA" version of it `view`.
img = np.empty((ydim, xdim), dtype=np.uint32)
view = img.view(dtype=np.uint8).reshape((ydim, xdim, 4))
# Copy the RGBA image into view, flipping it so it comes right-side up
# with a lower-left origin
view[:,:,:] = np.flipud(np.asarray(lena_img))
# Display the 32-bit RGBA image
dim = max(xdim, ydim)
fig = figure(title="Lena",
x_range=(0,dim), y_range=(0,dim),
# Specifying xdim/ydim isn't quire right :-(
# width=xdim, height=ydim,
)
fig.image_rgba(image=[img], x=0, y=0, dw=xdim, dh=ydim)
output_file("lena.html", title="image example")
show(fig) # open a browser
I pretty new in this whole Python thing and my question is how to make, that a button runs the command, when clicking it and not before.
I searched much in the Internet but i didnt find anything.
I dont understand the classes at all. Is there no other way to do this?
Here is my work, i did on the programm.
Thanks for your help
from tkinter import *
import os
t = ""
def ordner(x):
print ("def")
if os.path.exists(os.path.join("/Kunden/",x)) == True:
pass
else:
os.mkdir(os.path.join("/Kunden/",x))
def E1holen():
x = E1.get()
ordner(x)
#Hauptfenster
main=Tk(className='Kundendatenbank')
main.iconbitmap('icon.ico')
#Inhalt Hauptfenster
L1 = Label(main, text="Kundenname:")
L1.pack(side = LEFT)
E1 = Entry(main, bd =5, textvariable=t)
E1.pack(side = RIGHT)
a = Button (main, text=("erstellen/bearbeiten"), command=E1holen()).pack()
main.mainloop()
It runs immediately ecause you tell it to.
What is the syntax for calling a function in Python? It's foo(), right? So, when you do command=E1holen(), what should python do? It should call E1holen(), and then pass the result to the command attribute.
Put another way, the command attribute takes a reference to a function, but because of the () you were calling the function and giving the command attribute whatever that function returned. The solution? Remove the ():
a = Button(..., command=E1holen)
I have been using WebDriver for past 6 months.
There are couple of issues am facing right now [Version 2.3.1]:
a) when i try to get the element for the override link on the security certificate [https] page in IE through webdriver findElement, its not able to find that element but the selenium RC works fine.
Then i got a fix for tht by using:
webDriver.navigate().to(javascript:document.getElementById('overridelink').click());
Note :
I tried using the below code to fetch the element on security certificate page , but it returns
the body element
WebElement activeElement() [WebElement with focus, or the body element if no element with focus can be detected.], why its not able to pick the element by using findelement ?
b) i connected the remote network through SSL for running the webdriver test, am not able to click the override link on secure certificate [https] page?
c) is it better approach implementing webdriver [currently am using this] directly instead of using any framework like jbehave ?
Please provide your suggestions
Thanks,
Jayaraj A
Thank you for workaround!
For Java, your solution will look just a bit different and it helped me:
//driver is initialised somewhere before, for example, as RemoteWebDriver
driver.navigate().to("javascript:document.getElementById('overridelink').click()");
Yeah, I had similar problems. Webdriver doesn't seem to have complete information on
the Certificate error page for some reason.
I'm on Windows XP SP3, running IE 7 with Python/Webdriver
I'm using this hack to get around the certificate error page:
(Help, I still can't get freeeking Markdown to format a code block...)
#!/c/Python27/python
import win32con
import win32gui
def certificate_continue():
"""
Find the IE Window that has a Certificate Error and try to continue anyway.
We'll use the win32 modules to find the right window & child window,
then write some Javascript into the address bar and execute to continue.
"""
def _enumWindowsCallback(hwnd, windows):
"""
Cannibalized from Gigi Sayfan (WindowMover)
http://www.devx.com/opensource/Article/37773/1954
This appends window information as a 3-tuple to the list
passed into win32gui.EnumWindows()
"""
class_name = win32gui.GetClassName(hwnd)
# apparently win32gui.GetWindowText() only works to get the text
# on a button or a label not really for edit windows.
text = win32gui.GetWindowText(hwnd)
windows.append((hwnd, class_name, text))
def _get_certificate_error_window():
"""
all_windows[] gets filled up with a list of tuples, then loop through
it filtering on class and the window text (title bar text).
Assumes only one 'Certificate Error' window.
"""
all_windows = []
win32gui.EnumWindows(_enumWindowsCallback, all_windows)
for win in all_windows:
class_name = win[1]
title_bar_text = win[2]
if class_name == 'IEFrame' and \
'Certificate Error: Navigation Blocked' in title_bar_text:
return win
def _get_edit_text(hwnd):
"""
This function courtesy of Omar Raviv with huge help from Simon Brunning.
http://www.brunningonline.net/simon/blog/archives/000664.html
"""
buf_size = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf_size += 1 # don't forget that null character boys...
buffer = win32gui.PyMakeBuffer(buf_size)
# odd, we're telling them how big the text is that they're giving
# back to us
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buffer)
# don't need the null character now for Python
return buffer[:buf_size]
def _get_address_bar(parent_handle):
"""
There appears to be several 'Edit' windows within each browser window.
From Microsoft: If a child window has created child windows of its own,
EnumChildWindows enumerates those windows as well.
"""
childwins = []
win32gui.EnumChildWindows(parent_handle, _enumWindowsCallback,
childwins)
for win in childwins:
child_handle = win[0]
class_name = win[1]
if 'Edit' in class_name:
edit_text = _get_edit_text(child_handle)
if 'http://' in edit_text or 'https://' in edit_text:
return child_handle # then this must be it...
# begin certificate_continue
target_win = _get_certificate_error_window()
try:
cert_err_handle = target_win[0]
except TypeError:
print "OK, no Certificate Error window available"
return(1)
address_bar_handle = _get_address_bar(cert_err_handle)
# any better way to check the handle ?
if not win32gui.IsWindow( address_bar_handle):
print "Choked getting IE edit window"
return(1)
# now, need to send this JavaScript text to the browser Address Bar
javascript_continue = 'javascript: var continue_element = document.getElementById("overridelink"); continue_element.click();'
win32gui.SendMessage(address_bar_handle, win32con.WM_SETTEXT, 0,
javascript_continue)
# OK, and finally, send a carriage return to the address bar
# This last abomination, courtesy of Claudiu
# http://stackoverflow.com/#questions/5080777/
# what-sendmessage-to-use-to-send-keys-directly-to-another-window
win32gui.SendMessage(address_bar_handle, win32con.WM_KEYDOWN,
win32con.VK_RETURN, 0)
return(0)
if __name__ == '__main__':
status = certificate_continue()
exit(status)