How can I overcome this key word error? - python-3.4

enter code here
# -*- coding: utf-8 -*-
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig1=plt.figure()
ax=plt.axes(xlim=(-10,10), ylim=(-10,10))
line,=ax.plot([],[],lw=1)
"""def init ():
line.set_data([],[])
return line,"""
dt=0.001
X=[]
Y=[]
r=float(input("Enter the radius :: "))
w=float(input("Enter angular frequency :: "))
def run(data):
t=0
while w*t<=2*math.pi:
x=r*math.cos(w*t)
y=r*math.sin(w*t)
X.append(x)
Y.append(y)
t=t+dt
line.set_data(X,Y)
return line,
line,=ax.plot(X,Y,lw=2)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
anim=animation.FuncAnimation(fig1,run,frames=200,interval=20,blit=True)
anim.save('amim.mp4',writer=writer)
The error message shown is ::
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "/home/tathagata/Documents/Python scripts/circleamim.py", line 35, in <module>
FFMpegWriter = animation.writers['ffmpeg']
File "/home/tathagata/anaconda3/lib/python3.4/site-packages/matplotlib/animation.py", line 81, in __getitem__
return self.avail[name]
KeyError: 'ffmpeg'
I use anacoda distribution and SPYDER as my IDE. I have seen the many solutions related to key errors. But the movie wont run. How can I make the movie to run? I hope there are no other logical errors.

First install ffmpeg and add path to ffmpeg
# on windows
plt.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe'
# on linux
plt.rcParams['animation.ffmpeg_path'] = u'/home/username/anaconda/envs/env_name/bin/ffmpeg'
Note for linux users: The path for ffmpeg can be found by simply using which: which ffmpeg
Also instead of
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
I just used writer = animation.FFMpegWriter()

It seems that ffmpegis not installed on your system. Try the following code:
import matplotlib.animation as animation
print(animation.writers.list())
It will print out a list of all available MovieWriters. If ffmpegis not among it, you need to install it first from the ffmpeg homepage.

If you have Homebrew, literally just run the command
brew install ffmpeg
And Homebrew will take care of the rest (dependencies, etc). If you don't, I would recommend getting Homebrew or something like it (apt-get on Linux is built in, or an alternative on OS X would be Macports)

I have also posed with same problem(keyError: 'ffmpeg') but instead of using anakonda, I used IDLE3. So, first i checked for 'ffmpeg' in terminal it wasn't installed so installed it.
Using: sudo apt install ffmpeg
and when I run my save_animation program, it worked generating animation files in '.mpeg' format.

Related

error when starting spyder on ubuntu 22.04

I have just upgrade my ubuntu. I have this error on spyder:
Warning: Ignoring XDG_SESSION_TYPE=wayland on Gnome. Use QT_QPA_PLATFORM=wayland to run on Wayland anyway.
Traceback (most recent call last):
File "/usr/bin/spyder", line 33, in <module>
sys.exit(load_entry_point('spyder==4.2.1', 'gui_scripts', 'spyder')())
File "/usr/lib/python3/dist-packages/spyder/app/start.py", line 213, in main
mainwindow.main(options, args)
File "/usr/lib/python3/dist-packages/spyder/app/mainwindow.py", line 3624, in main
mainwindow = create_window(app, splash, options, args)
File "/usr/lib/python3/dist-packages/spyder/app/mainwindow.py", line 3482, in create_window
main.setup()
File "/usr/lib/python3/dist-packages/spyder/app/mainwindow.py", line 803, in setup
self.completions = CompletionManager(self)
File "/usr/lib/python3/dist-packages/spyder/plugins/completion/plugin.py", line 97, in __init__
plugin_client = Plugin(self.main)
File "/usr/lib/python3/dist-packages/spyder/plugins/completion/kite/plugin.py", line 50, in __init__
self.installer = KiteInstallerDialog(
File "/usr/lib/python3/dist-packages/spyder/plugins/completion/kite/widgets/install.py", line 287, in __init__
self._integration_widget = KiteIntegrationInfo(self)
File "/usr/lib/python3/dist-packages/spyder/plugins/completion/kite/widgets/install.py", line 58, in __init__
image = image.scaled(image_width, image_height, Qt.KeepAspectRatio,
TypeError: arguments did not match any overloaded call:
scaled(self, int, int, aspectRatioMode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode = Qt.FastTransformation): argument 1 has unexpected type 'float'
scaled(self, QSize, aspectRatioMode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode = Qt.FastTransformation): argument 1 has unexpected type 'float'
All the solution that I have found deal with specific application developed my different user and not for probel related to upgrade or ubuntu.
As a quick workaround just comment out the lines in File:
/usr/lib/python3/dist-packages/spyder/plugins/completion/kite/widgets/install.py
58
#image = image.scaled(image_width, image_height, Qt.KeepAspectRatio, Qt.SmoothTransformation)
143
#install_gif.setScaledSize(QSize(image_width, image_height))
244-247
#copilot_label.setPixmap(
# copilot_image.scaled(image_width, image_height,
# Qt.KeepAspectRatio,
# Qt.SmoothTransformation))
(Spyder maintainer here) The Spyder package provided by Ubuntu 22.04 (4.2.1, released in December 2020) is broken with the Python version that comes with it (3.10).
However, this error was fixed in any Spyder version released after 5.3.0, released in March 2022. So, to solve this problem please uninstall the Spyder that comes with Ubuntu and install it with pip in a virtualenv, as explained in our documentation.
I had the exact same problem, did a search with the following two items :
"spyder" + "mainwindow.py, line 3624" # aka a piece of the error message
I found the bug report #16571 on spyder's github : "TypeError in Tour with Python 3.10", which identified python 3.10 as the culprit.
In Debian + aptitude I downgraded python 3 from 3.10 to the 3.9 version, launched Spyder again and...problem solved !

"No Backend Error" while reading files in Python

I am trying to perform STFT on a bunch of sound files and I get this error.
The path of the files which I am trying to perform STFT is correct but still, I get this error.
import librosa
import io
import numpy as np
import tensorflow as tf
import os
import glob
path_te = "C:\Users\aanum\OneDrive\Documents\Deep Learning\timit-homework\te"
files = os.listdir(path_te)
for file in sorted(files):
if file.startswith("tex"):
file_path = path_te2 + "/" + file
#file_path = 'r' + "'" + str(file_path) + "'"
print(file_path)
st, sr=librosa.load(file_path, sr=None)
Output:
C:/Users/aanum/OneDrive/Documents/Deep Learning/timit-homework/te/tex0000.wav
---------------------------------------------------------------------------
NoBackendError Traceback (most recent call last)
<ipython-input-54-4df25548d204> in <module>
7 #file_path = 'r' + "'" + str(file_path) + "'"
8 print(file_path)
----> 9 st, sr=librosa.load(file_path, sr=None)
10 X=librosa.stft(st, n_fft=1024, hop_length=512)
11 X_abs = abs(X)
~\Anaconda3\envs\DeepLearning\lib\site-packages\librosa\core\audio.py in load(path, sr, mono, offset, duration, dtype, res_type)
117
118 y = []
--> 119 with audioread.audio_open(os.path.realpath(path)) as input_file:
120 sr_native = input_file.samplerate
121 n_channels = input_file.channels
~\Anaconda3\envs\DeepLearning\lib\site-packages\audioread\__init__.py in audio_open(path, backends)
114
115 # All backends failed!
--> 116 raise NoBackendError()
NoBackendError
Can anyone tell me why I have this error?
Make sure that your .wav file is not corrupted. Can you open the file with an audio file reader (which can read wav files)? If not, your file is corrupted. If you downloaded the audio files from an opensource dataset, it is possible that they are corrupted while you are manually unzipping the folder. I'd recommend you download the dataset again and unzip it with a command-line tool.
This error can occur when Librosa cannot load the file, mainly because librosa cannot read the file format (for example mp3 format) and it tries to look for other backends like ffmpeg. So, installing ffmpeg may help in resolving this problem. Also, depending on the OS you use, you may have to add ffmpeg to the OS path in some cases. If the issue is in fact due to the file format, proper installation of ffmpeg may resolve the issue.
Right after you write the line:
import usb.core
you need to write
import usb.backend.libusb1
I hope this helped you, tell me if it doesn't work!

Steps to load a .txt file and convert the strings in it to usable data in a Sage notebook

I am on a Mac with OS 10.11.6, and I'm learning the notebook interface for Sage 7.2. As a start, in a Sage worksheet I created a .txt file containing the string [1, 2, 3] and saved it. I can open the text file directly and verify its contents just by clicking on it, but I can't yet do this in Sage.
I'd like to be able to open it and convert the string to a usable Sage object. I'd appreciate explicit instructions, assuming nothing at all about my Sage background. Thank you.
Note: The procedure to do what I just asked in the Sage documentation under "Saving and Loading Individual Objects" doesn't work in my environment (specs above.) I do A = [1, 2, 3]. Then I do save(A, 'A') and Sage returns a hot link for A.sobj. Then I hit the save-and-quit button. Then I hit "sign out." Then I sign back in and go to the worksheet where I did the steps I just described. I do A = load('A'). This is what Sage says:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_3.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("QSA9IGxvYWQoJ0EnKQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
File "", line 1, in <module>
File "/private/var/folders/7n/t9k4hfyn44s2qp7wxt479kn80000gn/T/tmpEa1OkK/___code___.py", line 2, in <module>
exec compile(u"A = load('A')" + '\n', '', 'single')
File "", line 1, in <module>
File "sage/structure/sage_object.pyx", line 1032, in sage.structure.sage_object.load (build/cythonized/sage/structure/sage_object.c:11594)
IOError: [Errno 2] No such file or directory: 'A.sobj'`
I found an answer in Finch's book. First a quote:
“We used a module called os from the Python standard library module to help us write code that can run on multiple platforms. A text file must have a special character to denote the end of each line in the file. Unfortunately, for historical reasons, each family of operating systems (Mac, Windows, and UNIX) uses a different end-of-line character. The os module has a constant called linesep that contains the correct character for the platform that the code is run on. We used the statement import os to make the module available, and accessed the constant using the syntax os.linesep. We also used the function os.path.join to join the path to the file name with the correct character for the current operating system.”
Excerpt From: Craig Finch. “Sage Beginner's Guide.”
Example using a file named "File2.txt" containing a single text character, '1':
import os path='/Users/barrybrent/.sage/sage_notebook.sagenb/home/store/2/21/212/2123/admin/19/data/' fileName='File2.txt' times = [] text_file = open(os.path.join(path, fileName), 'r') line = text_file.readline()
(Comment: is just a character string. To convert it a Sage object useful in computations:)
elements=line.split(',') times.append(float(elements[0].strip()))
(Comment: evaluate:)
times[0]
(Comment: Sage says"1.0". Now can we do arithmetic with times[0]?)
times[0]+1
Sage says "2.0"

zopeskel fails (can't import urllib.parse)

I fail to install a usable version of zopeskel in my Plone site, both in my Debian-based Linux box and on the CentOS-based server.
In my buildout.cfg I have, following this how-to:
[zopeskel]
recipe = zc.recipe.egg
unzip = true
eggs =
ZopeSkel <= 3.0dev
Paste
PasteDeploy
PasteScript
# ${buildout:eggs}
(I don't have Dexterity contents nor diazothemes for now, so I tried without the zopeskel.dexterity and zopeskel.diazotheme, but it doesn't seem to make a difference; same result when I add them). My [buildout] section doesn't contain eggs, so I needed to comment out this as well.
After building I tried
$ bin/zopeskel --list
Traceback (most recent call last):
File "bin/zopeskel", line 15, in <module>
import zopeskel.zopeskel_script
File ".../eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/__init__.py", line 2, in <module>
from zopeskel.basic_namespace import BasicNamespace
File ".../eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/basic_namespace.py", line 2, in <module>
from zopeskel.vars import var, DottedVar, StringVar, BooleanVar, TextVar
File ".../eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/vars.py", line 2, in <module>
from paste.script.templates import var as base_var
File ".../eggs/PasteScript-2.0.2-py2.7.egg/paste/script/templates.py", line 7, in <module>
from . import copydir
File ".../eggs/PasteScript-2.0.2-py2.7.egg/paste/script/copydir.py", line 6, in <module>
from six.moves.urllib.parse import quote
ImportError: No module named urllib.parse
$ grep six bin/zopeskel
'.../eggs/six-1.2.0-py2.7.egg',
This is a quite old version (pip install six gave me 1.9.0), and it doesn't contain anything like quote or urllib.parse.
I assume some involved package fails to specify a needed version; but adding something like six >= 1.3 didn't even build.
How can I fix this? Thank you!
I guess the 1.2.0 version of the six package is specified by one of the extends of your buildout.
You could use buildout annotate to find which one it is.
You need to add a versions section:
[versions]
six = 1.9.0
Let it fail!
Seriously, ditch zopeskel for mrbob and this template....
zopeskel/paster are now seen as unmaintainable in the long run (due to dependencies that are not been worked on at all. mrbob has no major dependencies and is the approach that Plone 5 universal installer is taking instead of zopeskel.
But to make it more practical: zopeskel & it's plugins give issues like your one pretty regularly, mrbob does not in my experience. Because it is maintained it will also produce more up to date "model code" than zopeskel will.
Admittedly, mrbob doesn't (yet) have the number of plugins that zopeskel does, but since archetypes has been overtaken by dexterity, there is less heavy "boilerplate code" to generate. It's your choice, but if you are starting Plone now - then just learn one of mrbob or zopeskel (There's enough other stuff to learn).
Install it like this (obviously you have to add mrbob to your parts list too)
[mrbob]
recipe = zc.recipe.egg:scripts
eggs =
mr.bob
bobtemplates.plone

IPython notebook and rmagic/rpy2: cannot find module ri2py (OSX 10.8.5, python 2.7, R 3.1)

I'm trying to use the rmagic extension for the IPython notebook, using Python 2.7.6 via Enthought Canopy.
When I try the following example:
import numpy as np
import pylab
X = np.array([0,1,2,3,4])
Y = np.array([3,5,4,6,7])
pylab.scatter(X, Y)
%Rpush X Y
%R lm(Y~X)$coef
I get an error:
AttributeError Traceback (most recent call last)
<ipython-input-7-96dff2c70ba0> in <module>()
1 get_ipython().magic(u'Rpush X Y')
----> 2 get_ipython().magic(u'R lm(Y~X)$coef')
…
/Users/hrob/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/extensions/rmagic.pyc in eval(self, line)
212 res = ro.r("withVisible({%s})" % line)
213 value = res[0] #value (R object)
--> 214 visible = ro.conversion.ri2py(res[1])[0] #visible (boolean)
215 except (ri.RRuntimeError, ValueError) as exception:
216 warning_or_other_msg = self.flush() # otherwise next return seems to have copy of error
AttributeError: 'module' object has no attribute 'ri2py'
I can't find anyone else who's had the same problem and don't know enough to solve it myself. There is no definition for ri2py in conversion.py though.
I initially had installed Anaconda and was running python notebook through that, with exactly the same results.
rpy2 (version 2.4.0) installed successfully but when I test it I get 1 expected failure as follows:
python -m 'rpy2.robjects.tests.__init__'
…
testNewWithTranslation (testFunction.SignatureTranslatedFunctionTestCase) ... expected failure
I don't know if that's related.
Can anyone suggest what the problem might be and how I might fix it? Are the versions of python, R, etc. that I'm using compatible or do I need to re-install/update something?
Are you using %load_ext rmagic?
If so, try using %load_ext rpy2.ipython instead.
This is one of the new features in version 2.4.0.

Resources