I'm working with a Jupyter notebook. I'm trying to import a file called main.py which contains 2 lines:
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root
My code:
import os
%load main.py
from main import ROOT_DIR
I'm getting
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
....\site-packages\IPython\core\interactiveshell.py in find_user_code(self, target, raw, py_only, skip_encoding_cookie, search_ns)
3282 try: # User namespace
-> 3283 codeobj = eval(target, self.user_ns)
3284 except Exception:
<string> in <module>()
NameError: name 'main' is not defined
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-3-1f13faed25b1> in <module>()
1 import os
----> 2 get_ipython().run_line_magic('load', 'main.py')
3 from main import ROOT_DIR
....\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2129 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2130 with self.builtin_trap:
-> 2131 result = fn(*args,**kwargs)
2132 return result
2133
<decorator-gen-48> in load(self, arg_s)
....\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
....\site-packages\IPython\core\magics\code.py in load(self, arg_s)
342 search_ns = 'n' in opts
343
--> 344 contents = self.shell.find_user_code(args, search_ns=search_ns)
345
346 if 's' in opts:
....\site-packages\IPython\core\interactiveshell.py in find_user_code(self, target, raw, py_only, skip_encoding_cookie, search_ns)
3284 except Exception:
3285 raise ValueError(("'%s' was not found in history, as a file, url, "
-> 3286 "nor in the user namespace.") % target)
3287
3288 if isinstance(codeobj, str):
ValueError: 'main.py' was not found in history, as a file, url, nor in the user namespace.
What am I doing wrong?
Related
Hi i am having issues with loading the .s2p file
when i ran the following code
import skrf as rf
from skrf import Network, Frequency
data1 = rf.Network('/Users/pradeeps/Desktop/Project/meas2018_07_06/300MHzNLOSX1DPS.s2p')
It showed the following error as shown below
---------------------------------------------------------------------------
UnpicklingError Traceback (most recent call last)
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:450, in Network.__init__(self, file, name, params, comments, f_unit, s_def, **kwargs)
449 try:
--> 450 self.read(fid)
451 except UnicodeDecodeError: # Support for pickles created in Python2 and loaded in Python3
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:2357, in Network.read(self, *args, **kwargs)
2356 from .io.general import read
-> 2357 self.copy_from(read(*args, **kwargs))
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/io/general.py:140, in read(file, *args, **kwargs)
139 try:
--> 140 obj = pickle.load(fid, *args, **kwargs)
141 except (UnpicklingError, UnicodeDecodeError) as e:
142 # if fid is seekable then reset to beginning of file
UnpicklingError: invalid load key, '3'.
During handling of the above exception, another exception occurred:
NotImplementedError Traceback (most recent call last)
Untitled-1.ipynb Cell 2' in <cell line: 1>()
----> 1 data1 = rf.Network('/Users/pradeeps/Desktop/Project/meas2018_07_06/300MHzNLOSX1DPS.s2p')
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:458, in Network.__init__(self, file, name, params, comments, f_unit, s_def, **kwargs)
456 filename = fid.name
457 fid.close()
--> 458 self.read_touchstone(filename, self.encoding)
460 if name is None and isinstance(file, str):
461 name = os.path.splitext(os.path.basename(file))[0]
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:1956, in Network.read_touchstone(self, filename, encoding)
1953 touchstoneFile = touchstone.Touchstone(filename, encoding=encoding)
1955 if touchstoneFile.get_format().split()[1] != 's':
-> 1956 raise NotImplementedError('only s-parameters supported for now.')
1958 self.comments = touchstoneFile.get_comments()
1960 try:
NotImplementedError: only s-parameters supported for now.
As shown in this particular code i used scikit-rf is there any other package that i should use in this particular instance or am i doing anything wrong.
Thank you
I am executing the following piece of code in Jupyter Notebook
import os
import shlex
files = os.listdir("./data/")
for file in files:
%run -timeout=5 -i solver.py ./data/$file
I get the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~/Desktop/GitHub/coursera/discrete-optimization/week2/knapsack/solver.py in <module>
1 for file in files:
----> 2 get_ipython().run_line_magic('run', '-timeout=5 -i solver.py ./data/$file')
~/opt/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2324 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2325 with self.builtin_trap:
-> 2326 result = fn(*args, **kwargs)
2327 return result
2328
<decorator-gen-59> in run(self, parameter_s, runner, file_finder)
~/opt/anaconda3/lib/python3.8/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/opt/anaconda3/lib/python3.8/site-packages/IPython/core/magics/execution.py in run(self, parameter_s, runner, file_finder)
687 if "m" in opts:
688 modulename = opts["m"][0]
--> 689 modpath = find_mod(modulename)
690 if modpath is None:
691 msg = '%r is not a valid modulename on sys.path'%modulename
~/opt/anaconda3/lib/python3.8/site-packages/IPython/utils/module_paths.py in find_mod(module_name)
60 """
61 loader = importlib.util.find_spec(module_name)
---> 62 module_path = loader.origin
63 if module_path is None:
64 return None
AttributeError: 'NoneType' object has no attribute 'origin'
Clearly, the timeout option is not working.
What is the correct way to set a timeout option for my code? I want to stop execution for a test case if it reaches beyond a specific time, for example, 5 sec.
You can do
import os
import shlex
files = os.listdir("./data/")
for file in files:
! timeout 5 python solver.py ./data/$file
I have set up ad manager credentials. I'm trying to access the Admanager API, im getting the following error.
from googleads import ad_manager
client = ad_manager.AdManagerClient.LoadFromStorage()
network_service = client.GetService('NetworkService', version='v201902')
current_network = network_service.getCurrentNetwork()
the error im facing is:
Fault Traceback (most recent call last)
~\Anaconda3\lib\site-packages\googleads\common.py in MakeSoapRequest(*args)
1381 return soap_service_method(
-> 1382 *packed_args, _soapheaders=soap_headers)['body']['rval']
1383 except zeep.exceptions.Fault as e:
~\Anaconda3\lib\site-packages\zeep\proxy.py in __call__(self, *args, **kwargs)
41 self._proxy._client, self._proxy._binding_options,
---> 42 self._op_name, args, kwargs)
43
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in send(self, client, options, operation, args, kwargs)
131
--> 132 return self.process_reply(client, operation_obj, response)
133
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in process_reply(self, client, operation, response)
193 if response.status_code != 200 or fault_node is not None:
--> 194 return self.process_error(doc, operation)
195
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in process_error(self, doc, operation)
287 actor=None,
--> 288 detail=etree_to_string(doc))
289
Fault: Unknown fault occured
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-16-991c0839fc99> in <module>()
----> 1 current_network = network_service.getCurrentNetwork()
~\Anaconda3\lib\site-packages\googleads\common.py in MakeSoapRequest(*args)
1385 if e.detail is not None:
1386 underlying_exception = e.detail.find(
-> 1387 '{%s}ApiExceptionFault' % self._GetBindingNamespace())
1388 fault_type = self.zeep_client.get_element(
1389 '{%s}ApiExceptionFault' % self._GetBindingNamespace())
TypeError: a bytes-like object is required, not 'str'
You are probably missing permissions with your configured service account. Make sure the account has access to ad-manager and scopes are configured properly.
I suggest to do it this way:
class Adx:
def __init__(self):
self.GOOGLEADS_YAML = 'googleads.yaml'
self.GOOGLEADS_VERSION = 'v202111'
self.google_keys = self.GOOGLEADS_YAML
def activate(self):
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage(self.google_keys)
I'm trying to use this github repo to do some birdsong analysis. I've come across a problem in the stage where I collect all the sample's into one array('Collect Samples'). I'm getting an error that looks to be something to do with my system. Not sure where to start on fixing the error. (have a look at my link to the github repo to get more in depth.) Thanks for having a look!
def job(fn):
return load_sample(fn, sr=sr,
max_length=max_length, fixed_length=fixed_length)
pool = Pool()
%time results = pool.map(job, files[:limit])
print 'Processed', len(results), 'samples'
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-8-5d12f8de2a12> in <module>()
3 max_length=max_length, fixed_length=fixed_length)
4 pool = Pool()
----> 5 get_ipython().magic(u'time results = pool.map(job, files[:limit])')
6 print 'Processed', len(results), 'samples'
/home/notebook/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
2156 magic_name, _, magic_arg_s = arg_s.partition(' ')
2157 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158 return self.run_line_magic(magic_name, magic_arg_s)
2159
2160 #-------------------------------------------------------------------------
/home/notebook/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
2077 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2078 with self.builtin_trap:
-> 2079 result = fn(*args,**kwargs)
2080 return result
2081
<decorator-gen-59> in time(self, line, cell, local_ns)
/home/notebook/anaconda2/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
186 # but it's overkill for just that one bit of state.
187 def magic_deco(arg):
--> 188 call = lambda f, *a, **k: f(*a, **k)
189
190 if callable(arg):
/home/notebook/anaconda2/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in time(self, line, cell, local_ns)
1183 else:
1184 st = clock2()
-> 1185 exec(code, glob, local_ns)
1186 end = clock2()
1187 out = None
<timed exec> in <module>()
/home/notebook/anaconda2/lib/python2.7/multiprocessing/pool.pyc in map(self, func, iterable, chunksize)
249 '''
250 assert self._state == RUN
--> 251 return self.map_async(func, iterable, chunksize).get()
252
253 def imap(self, func, iterable, chunksize=1):
/home/notebook/anaconda2/lib/python2.7/multiprocessing/pool.pyc in get(self, timeout)
565 return self._value
566 else:
--> 567 raise self._value
568
569 def _set(self, i, obj):
OSError: [Errno 2] No such file or directory
Also in case it helps, I'm running Python 2.7.13 |Anaconda 4.4.0.
Oh and the line that causes the error is results = pool.map(job, files[:limit])
Thanks a lot in advance.
After following my comment i posted I tried installing ffmpeg using
sudo apt-get install libav-tools
from this link.
Not sure how that installs ffmpeg but it fixed the problem!
If I should delete this post please tell me, but I think it is useful for other people with a similar problem. ie. no need to learn about mappers and pools if you have a similar problem.
I was trying to plot a graphic with matplotlib in Jupyter and then with only the 'pylab inline' the following error shows up. I'm working with python 3.x and anaconda in a macbook. I found similar trends (for example this) with some potential solutions but they didn't work. I have tried everything but nothing works. I would really appreciate any help.
My code:
%pylab inline
which produces the following error:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in <module>()
1429 try:
-> 1430 fontManager = pickle_load(_fmcache)
1431 if (not hasattr(fontManager, '_version') or
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in pickle_load(filename)
965 """
--> 966 with open(filename, 'rb') as fh:
967 data = pickle.load(fh)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/sebasg167/.matplotlib/fontList.py3k.cache'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-2-d4543581fa9d> in <module>()
----> 1 get_ipython().magic('pylab inline')
//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2156 magic_name, _, magic_arg_s = arg_s.partition(' ')
2157 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158 return self.run_line_magic(magic_name, magic_arg_s)
2159
2160 #-------------------------------------------------------------------------
//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2077 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2078 with self.builtin_trap:
-> 2079 result = fn(*args,**kwargs)
2080 return result
2081
<decorator-gen-105> in pylab(self, line)
//anaconda/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
186 # but it's overkill for just that one bit of state.
187 def magic_deco(arg):
--> 188 call = lambda f, *a, **k: f(*a, **k)
189
190 if callable(arg):
//anaconda/lib/python3.6/site-packages/IPython/core/magics/pylab.py in pylab(self, line)
154 import_all = not args.no_import_all
155
--> 156 gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
157 self._show_matplotlib_backend(args.gui, backend)
158 print ("Populating the interactive namespace from numpy and matplotlib")
//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in enable_pylab(self, gui, import_all, welcome_message)
2984 from IPython.core.pylabtools import import_pylab
2985
-> 2986 gui, backend = self.enable_matplotlib(gui)
2987
2988 # We want to prevent the loading of pylab to pollute the user's
//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui)
2945 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2946
-> 2947 pt.activate_matplotlib(backend)
2948 pt.configure_inline_support(self, backend)
2949
//anaconda/lib/python3.6/site-packages/IPython/core/pylabtools.py in activate_matplotlib(backend)
292 matplotlib.rcParams['backend'] = backend
293
--> 294 import matplotlib.pyplot
295 matplotlib.pyplot.switch_backend(backend)
296
//anaconda/lib/python3.6/site-packages/matplotlib/pyplot.py in <module>()
27 from cycler import cycler
28 import matplotlib
---> 29 import matplotlib.colorbar
30 from matplotlib import style
31 from matplotlib import _pylab_helpers, interactive
//anaconda/lib/python3.6/site-packages/matplotlib/colorbar.py in <module>()
34 import matplotlib.collections as collections
35 import matplotlib.colors as colors
---> 36 import matplotlib.contour as contour
37 import matplotlib.cm as cm
38 import matplotlib.gridspec as gridspec
//anaconda/lib/python3.6/site-packages/matplotlib/contour.py in <module>()
20 import matplotlib.colors as colors
21 import matplotlib.collections as mcoll
---> 22 import matplotlib.font_manager as font_manager
23 import matplotlib.text as text
24 import matplotlib.cbook as cbook
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in <module>()
1438 raise
1439 except:
-> 1440 _rebuild()
1441 else:
1442 _rebuild()
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in _rebuild()
1417 global fontManager
1418
-> 1419 fontManager = FontManager()
1420
1421 if _fmcache:
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in __init__(self, size, weight)
1071 self.afmfiles = findSystemFonts(paths, fontext='afm') + \
1072 findSystemFonts(fontext='afm')
-> 1073 self.afmlist = createFontList(self.afmfiles, fontext='afm')
1074 if len(self.afmfiles):
1075 self.defaultFont['afm'] = self.afmfiles[0]
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in createFontList(fontfiles, fontext)
589 continue
590 try:
--> 591 prop = afmFontProperty(fpath, font)
592 except KeyError:
593 continue
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in afmFontProperty(fontpath, font)
498 """
499
--> 500 name = font.get_familyname()
501 fontname = font.get_fontname().lower()
502
//anaconda/lib/python3.6/site-packages/matplotlib/afm.py in get_familyname(self)
523 extras = (br'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
524 br'light|ultralight|extra|condensed))+$')
--> 525 return re.sub(extras, '', name)
526
527 #property
//anaconda/lib/python3.6/re.py in sub(pattern, repl, string, count, flags)
189 a callable, it's passed the match object and must return
190 a replacement string to be used."""
--> 191 return _compile(pattern, flags).sub(repl, string, count)
192
193 def subn(pattern, repl, string, count=0, flags=0):
TypeError: cannot use a bytes pattern on a string-like object
You must find this file :
font_manager.py
in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font_manager.py
and FIND def win32InstalledFonts(directory=None, fontext='ttf')
and replace
by :
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font directory, or use the
system directories if none given. A list of TrueType font
filenames are returned by default, or AFM fonts if fontext ==
'afm'.
"""
from six.moves import winreg
if directory is None:
directory = win32FontDirectory()
fontext = get_fontext_synonyms(fontext)
key, items = None, {}
for fontdir in MSFontDirectories:
try:
local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
except OSError:
continue
if not local:
return list_fonts(directory, fontext)
try:
for j in range(winreg.QueryInfoKey(local)[1]):
try:
key, direc, any = winreg.EnumValue(local, j)
if not is_string_like(direc):
continue
if not os.path.dirname(direc):
direc = os.path.join(directory, direc)
direc = direc.split('\0', 1)[0]
if os.path.splitext(direc)[1][1:] in fontext:
items[direc] = 1
except EnvironmentError:
continue
except WindowsError:
continue
except MemoryError:
continue
return list(six.iterkeys(items))
finally:
winreg.CloseKey(local)
return None