Category Archives: Python

NameError: global name ‘***‘ is not defined [How to Solve]

Error demonstration

class Solution(object):
    def fib(self,n):
        """
        :type n: int
        :rtype: int
        """
        while(n>0):
            if(n==1 or n==2):
                return 1
            else:
                return fib(n-1)+fib(n-2)#error
        return 
'''
NameError: global name 'fib' is not defined
    return fib(n-1)+fib(n-2)
Line 11 in fib (Solution.py)
    ret = Solution().fib(param_1)
Line 36 in _driver (Solution.py)
    _driver()
Line 48 in <module> (Solution.py)
'''        

Solution:

class Solution(object):
    def fib(self,n):
        """
        :type n: int
        :rtype: int
        """
        while(n>0):
            if(n==1 or n==2):
                return 1
            else:
                return self.fib(n-1)+self.fib(n-2)#Modified
        return 0

[Solved] Failed environment install leads to “unable to create process using“ error

Failed environment install leads to “unable to create process using” error

Maybe it’s because there are too many environments installed in CONDA, and you copy them yourself. Suddenly, CONDA fails.

As long as you enter CONDA activate, it will report

Fatal error in launcher: Unable to create process using '"d:\project\gae_gan\ddgk\venv\scripts\python.exe" "D:\Programs\Anaconda3\Scripts\conda.exe" '

Error.

Finally found a very simple solution

Enter directly in the console

***\Anaconda3\Scripts\activate

Then restart console to be fine!
Referenec:
https://stackoverflow.com/questions/59721699/anaconda-is-unable-to-create-process-on-windows10

[Solved] bushi RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/s

Error Messages:

RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/serialize/inline_container.cc:132, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but the maximum supported version for reading is 2. Your PyTorch installation may be too old. (init at /pytorch/caffe2/serialize/inline_container.cc:132)
frame #0: c10::Error::Error(c10::SourceLocation, std::string const&) + 0x33 (0x7fdcd0189193 in /home/a430/intel/intelpython3/envs/zayn/lib/python3.6/site-packages/torch/lib/libc10.so)
frame #1: caffe2::serialize::PyTorchStreamReader::init() + 0x1f5b (0x7fdcd33119eb in /home/a430/intel/intelpython3/envs/zayn/lib/python3.6/site-packages/torch/lib/libtorch.so)
frame #2: caffe2::serialize::PyTorchStreamReader::PyTorchStreamReader(std::string const&) + 0x64 (0x7fdcd3312c04 in /home/a430/intel/intelpython3/envs/zayn/lib/python3.6/site-packages/torch/lib/libtorch.so)
frame #3: <unknown function> + 0x6c53a6 (0x7fdd1b2423a6 in /home/a430/intel/intelpython3/envs/zayn/lib/python3.6/site-packages/torch/lib/libtorch_python.so)
frame #4: <unknown function> + 0x2961c4 (0x7fdd1ae131c4 in /home/a430/intel/intelpython3/envs/zayn/lib/python3.6/site-packages/torch/lib/libtorch_python.so)
<omitting python frames>

Some people say there is a problem with the torch version. My torch version is 1.4.0, try upgrading to 1.6.0, torchvision was upgraded to 0.7.0, this problem will be reported:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU.

Just follow the hint and add map_location=torch.device(‘cpu’) when loading the model, as follows:
best_model = torch.load("../weights/September01-Unet-se_resnext50_32x4d/checkpoint.pth.tar", map_location=torch.device('cpu'))

[Solved] Pytorch error: RuntimeError: one of the variables needed for gradient computation

Error:
runtimeerror: one of the variables needed for gradient computation has been modified by an inplace operation

Analysis: the new version of pytorch integrates variable and tensor into one tensor, and the inplace operation can be used for variable before, but errors will occur when using tensor

Check whether there is the following expression

x += res #error

Change to

x  = x + res

No error is reported

[Solved] AttributeError: ‘module‘ object has no attribute ‘CALIB_HAND_EYE_PARK‘

ubuntu18.04 ROS:melodic python2.7

 File "/home/bionic/yuxiangROS_handeye/catkin_ws/src/handeye-calib-master/src/handeye-calib/src/handeye/handeye_calibration_backend_opencv.py", line 29, in HandeyeCalibrationBackendOpenCV
    'Park': cv2.CALIB_HAND_EYE_PARK,
AttributeError: 'module' object has no attribute 'CALIB_HAND_EYE_PARK'
[base_hand_on_eye_calib-1] process has died [pid 15724, exit code 1, cmd /home/bionic/yuxiangROS_handeye/catkin_ws/src/handeye-calib-master/src/handeye-calib/src/handeye/base_hand_on_eye_calib.py __name:=base_hand_on_eye_calib __log:=/home/bionic/.ros/log/600b94f2-660e-11ec-93c4-94c691a2c1c1/base_hand_on_eye_calib-1.log].
log file: /home/bionic/.ros/log/600b94f2-660e-11ec-93c4-94c691a2c1c1/base_hand_on_eye_calib-1*.log
all processes on machine have died, roslaunch will exit
shutting down processing monitor...
... shutting down processing monitor complete

It should be the opencv version

I used the Q2 command and succeeded

Q1.pip install transforms3d
Q2.python -m pip install opencv-contrib-python, and then follow @yangbenbo 's advice, this problem is done(thank you).
Q3.after the two qusetion, Q3 is normal automaticaly.I just want to test the single node to debug(rqt_easy_handeye), thanks for your advice, it works.

[Solved] Paramiko error: AttributeError: ‘NoneType’ object has no attribute ‘time’

Error message:


Exception ignored in: <function BufferedFile.__del__ at 0x1104b7d30>
Traceback (most recent call last):
  File "/Users/jerrylin/.conda/envs/pythonProject/lib/python3.8/site-packages/paramiko/file.py", line 66, in __del__
  File "/Users/jerrylin/.conda/envs/pythonProject/lib/python3.8/site-packages/paramiko/channel.py", line 1392, in close
  File "/Users/jerrylin/.conda/envs/pythonProject/lib/python3.8/site-packages/paramiko/channel.py", line 991, in shutdown_write
  File "/Users/jerrylin/.conda/envs/pythonProject/lib/python3.8/site-packages/paramiko/channel.py", line 967, in shutdown
  File "/Users/jerrylin/.conda/envs/pythonProject/lib/python3.8/site-packages/paramiko/transport.py", line 1846, in _send_user_message
AttributeError: 'NoneType' object has no attribute 'time'

Program code:

import paramiko
import sys
import time
# Instantiate SSHClient
client = paramiko.SSHClient()

# Auto add policy to save server's host name and key information, if not added, then hosts no longer recorded in local know_hosts file will not be able to connect
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the SSH server and authenticate with username and password
client.connect()

# Open a Channel and execute commands
stdin, stdout, stderr = client.exec_command('ls data/data_target') # stdout is the correct output, stderr is the error output, and there is one variable with a value

# Print the execution result
print(stdout.read().decode('utf-8'))

# Close SSHClient

client.close()

Solution:

The reason for the error is that the output print conflicts with the close executed by the program. You only need to add a time before the close Sleep (1) is OK

Python Connect database error: command listdatabases requires authentication

Python reports an error when connecting to the database. Command listdatabases requires authentication, full error: {OK ‘: 0.0,’ errmsg ‘:’ command listdatabases requires authentication ‘,’ code ‘: 13,’ codename ‘:’ unauthorized ‘}

The reason for the error is that authentication is required, indicating that user name and password authentication are required to connect to mongodb database.

Connect mongodb without password. The code is as follows:

from pymongo import MongoClient
class MongoDBConn:
    def __init__(self, host, port, db_name, user, password):
        """
        Establishing database connections
        """
        self.conn = MongoClient(host, port)
        self.mydb = self.conn[db_name]

With password authentication, connect to Mongo database, and the code is as follows:

from pymongo import MongoClient

class MongoDBConn:

    def __init__(self, host, port, db_name, user, password):
        """
        Establishing database connections
        """
        self.conn = MongoClient(host, port)
        self.db = self.conn.admin 
        self.db.authenticate(user, password)
        self.mydb = self.conn[db_name]

Pit record

In fact, an error was reported in the middle:

Authentication failed., full error: {‘ok’: 0.0, ‘errmsg’: ‘Authentication failed.’, ‘code’: 18, ‘codeName’: ‘AuthenticationFailed’}

Originally used directly in the code:

self.db = self.conn[db_name]
self.db.authenticate(user, password)

If you directly use the target database for link authentication, you will report the above error. Instead, first connect to the system default database admin, use admin for authentication, and you will succeed, and then do the corresponding operation for the target database.

pytorch model.load_state_dict Error [How to Solve]

When pytorch loads the model, if some judgment is used in the model, the judgment is used as the selection execution condition, but it is also saved in the model. However, when calling, the network in the judgment condition is not selected and load_state_Dict is used will report an error. Some operators cannot find the name. For example:

if backbone == "mobilenet":
    self.backbone = mobilenet()
    flat_shape = 1024
    elif backbone == "inception_resnetv1":
    self.backbone = inception_resnet()
else:
    raise ValueError('Unsupported backbone - `{}`, Use mobilenet, inception_resnetv1.'.format(backbone))
    self.avg = nn.AdaptiveAvgPool2d((1,1))
    self.Bottleneck = nn.Linear(flat_shape, embedding_size,bias=False)
    self.last_bn = nn.BatchNorm1d(embedding_size, eps=0.001, momentum=0.1, affine=True)
    if mode == "train": # Judgment condition, test without loading full connection
        self.classifier = nn.Linear(embedding_size, num_classes)

The strict = false option can be added to avoid operators not called in the network:

model2.load_state_dict(state_dict2, strict=False)

[Solved] ufunc ‘add‘ did not contain a loop with signature matching types (dtype(‘<U32‘), dtype(‘<U32‘))

Error type:
UFUNC 'Add' did not contain a loop with signature matching types (dtype ('& lt; U32'), dtype ('& lt; U32') - & gt; dtype('<U32')

The ‘Add’ function is a self-defined addition function. The error type is translated as: UFUNC ‘Add’ does not contain a loop with signature matching type. Check the error causes of others. Most of them are due to data type mismatch. The following add function will report this error when x is of type int and y is of type str.

def add(x,y):
    print(type(x))
    print(type(y))
    return x+y

Therefore, I added a function to view the data type in the add function, and found that the data type is:

<class 'numpy.float64'>
<class 'list'>

This confused me. I rechecked my function again

df1["property_grid"]=df1[["wgs84_lon","wgs84_lat"]].apply(lambda x: add( x["wgs84_lon"], ["wgs84_lat"]),axis=1)

It is found that an X is missing. The correct is as follows:

df1["property_grid"]=df1[["wgs84_lon","wgs84_lat"]].apply(lambda x: add( x["wgs84_lon"], x["wgs84_lat"]),axis=1)

Perfect solution~