Ipython widget Dropdown including NaN values - python-3.x

I have an ipython widget dropdown which includes NaN:
from ipywidgets import widgets
import numpy as np
widgets.Dropdown(description='Choose this:', options=[None, 'a', 'b', np.nan])
When I try to select NaN, I get the following error:
StopIteration Traceback (most recent call last)
...
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
...
ValueError: nan not in array
During handling of the above exception, another exception occurred:
TraitError Traceback (most recent call last)
...
TraitError: Invalid selection: value not found
I removed the Tracebacks because the bot is forcing me to add more details because my post is "mostly code".
At first I thought we can only have literals in the dropdown, but using objects generally works fine.
What is so peculiar about NaN?

Related

KeyError using format with python

I'm new in python and i'm getting this error while trying to run my code
KeyError Traceback (most recent call last)
<ipython-input-201-74e7a7ea82f3> in <module>
----> 1 SEARCH['profession']['call'].format('Jhon',23)
KeyError: '"sea'
This is my code, I am trying to use the format in a string that simulates a dictionary
SEARCH = {
'profession' : {"call":'{"sea:searchProfession":{"datasheet": {"name":{},"age": {}}}}'},
'id' : {"call":'{"sea:searchId":{"personId": {"id":{},"name": {},"age":"{}"}}}'},
}
SEARCH['profession']['call'].format('Jhon',23)
I know there are similar issues, but I have not found the solution

How can I use 'torch.utils.mobile_optimizer' in PyTorch 1.6.0?

According to https://pytorch.org/docs/stable/mobile_optimizer.html (currently for 1.6.0)
Torch mobile supports torch.mobile_optimizer.optimize_for_mobile utility to run a list of optimization pass with modules in eval mode. The method takes the following parameters: a torch.jit.ScriptModule object, a blacklisting optimization set and a preserved method list
The page title and
torch.utils.mobile_optimizer.optimize_for_mobile(script_module, optimization_blacklist: Set[torch._C.MobileOptimizerType] = None)
at the end suggest it should be torch.utils.mobile_optimizer instead. However, neither work for me:
In [25]: module1 = torch.utils.mobile_optimizer.optimize_for_mobile(module)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-25-79e42fe53cdf> in <module>
----> 1 module1 = torch.utils.mobile_optimizer.optimize_for_mobile(module)
AttributeError: module 'torch.utils' has no attribute 'mobile_optimizer'
In [26]: module1 = torch.mobile_optimizer.optimize_for_mobile(module)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-26-469dd450df3d> in <module>
----> 1 module1 = torch.mobile_optimizer.optimize_for_mobile(module)
AttributeError: module 'torch' has no attribute 'mobile_optimizer'
In [27]: print(torch.__version__)
1.6.0
Am I missing anything? E.g. do I have to install some package other than torch itself?
import torch.utils.mobile_optimizer as mobile_optimizer
scripted_model = torch.jit.script(model, pt_inputs)
opt_model = mobile_optimizer.optimize_for_mobile(scripted_model)
torch.jit.save(opt_model, "model.pt")
It works for me

Catching an exception caused by 'finally' while raising a preceeding exception

Let's say I have the following code:
def do(i):
try:
1/i
except:
raise
finally:
raise NotImplementedError
It will try to divide 1 by a certain number, and will then in its finally clause, raise an Exception. What if I wanted to handle the exception in finally, but still want exceptions from try to be raised? (Note that I can't change how do works. I need to wrap dowithin my own exception handling logic).
To illustrate, let's try a few things:
do(1)
>>>
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-16-bf2a92c9df1e> in <module>
----> 1 do(1)
<ipython-input-14-17793ae783da> in do(i)
5 raise
6 finally:
----> 7 raise NotImplementedError
NotImplementedError:
,
do(0)
>>>
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-14-17793ae783da> in do(i)
2 try:
----> 3 1/i
4 except:
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
NotImplementedError Traceback (most recent call last)
<ipython-input-17-dcdf66fecd31> in <module>
----> 1 do(0)
<ipython-input-14-17793ae783da> in do(i)
5 raise
6 finally:
----> 7 raise NotImplementedError
NotImplementedError:
,
try:
do(0)
except NotImplementedError:
print("passed")
except:
raise
>>>
passed
So, it is catching the NotImplementedError, which happens while handling the ZeroDivisionError and is therefore not raising ZeroDivisionError .
From the documentation, emphasis is mine:
If finally is present, it specifies a ‘cleanup’ handler. The try
clause is executed, including any except and else clauses. If an
exception occurs in any of the clauses and is not handled, the
exception is temporarily saved. The finally clause is executed. If
there is a saved exception it is re-raised at the end of the finally
clause. If the finally clause raises another exception, the saved
exception is set as the context of the new exception. If the finally
clause executes a return, break or continue statement, the saved
exception is discarded.
My addition to the emphasised part: otherwise the context is set to None.
In other words, the code that calls do(0) can't directly catch ZeroDevisionError since it is being masked by the NotImplementedError raised by the finally block. It will have to explicitly check the context of the NotImplemented exception.
try:
do(0)
except NotImplementedError as e:
print(e.__context__)
print(type(e.__context__))
Outputs
division by zero
<class 'ZeroDivisionError'>
To raise the full error stack only if the catched exception has a context, one could construct something like:
try:
do(0)
except NotImplementedError as e:
if e.__context__:
raise e
As the internal structure of the do() function is outside of your purview, then I would recommend pre-validation in the form of:
if number != 0:
do(number)
else:
raise ZeroDivisionError
It's hard to say for sure without more bits of the puzzle, but hope that helps.

global variables inside function python 3.x

guys i am new in python and for some reason the word global not working for me
ex
def location():
global place
place = "Cape Town"
return
and when i am trying to print place
print(place)
i am facing that error
NameError Traceback (most recent call last)
<ipython-input-2-34a3a4594339> in <module>()
----> 1 print(place)
NameError: name 'place' is not defined

Appending a column to large csv file

I have uploaded a large csv into python using the following code:
ddgqa = pd.read_table("/Users/xxxx/Documents/globalqa-pageurls-Report.csv", chunksize= 10**6, iterator=True)
I am now extract a column into a dataframe using this code:
for chunk in ddgqa:
links_adobe_ddgqa = pd.DataFrame(ddga['Page URL'])
When I try to links_adobe_ddgqa
I get the following error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-95-1ab6eaf23d5f> in <module>()
----> 1 links_adobe_ddgqa
NameError: name 'links_adobe_ddgqa' is not defined
What am I missing? Is there a better way to accomplish this?

Resources