Category Archives: Python

[2021-10-05] Python Error: AttributeError: ‘NoneType‘ object has no attribute ‘append‘

Traceback (most recent call last):
File “D:\C world\py\实验03.py”, line 36, in <module>
APPEND=APPEND.append(random.randint(1,100000))
AttributeError: ‘NoneType’ object has no attribute ‘append’

Change APPEND=APPEND.append(random.randint(1,100000)) to

APPEND=APPEND.append(random.randint(1,100000))
#Wrong
    
APPEND.append(random.randint(1,100000))
#Right

alike

print(a.reverse)
#Wrong
a=a.reverse
#Wrong

a.reverse
print(a)
#Right

[Solved] Add-apt-repository Command Error: AttributeError: ‘Thread‘ object has no attribute ‘isAlive‘

Question:

Today, when installing the software package, I found that an error occurred when executing the add apt repository command, and the software source could not be added

Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 191, in <module>
    if not sp.add_source_from_shortcut(shortcut, options.enable_source):
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 777, in add_source_from_shortcut
    if worker.isAlive():
AttributeError: 'Thread' object has no attribute 'isAlive'

reason:

The file softwareproperties.py refers to “isalive”. The python version installed on the computer is 3.9.2. This method is no longer supported in 3.9.

Solution:

Modify the “/ usr/lib/python3/dist packages/softwareproperties/softwareproperties. Py” file, and change the “isalive” in line 777 to “is_live”.

SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3: truncated \UX

Error:

When specifying the file path with Python, the error ‘syntax error: (Unicode error)’ Unicode escape ‘codec can’t decode bytes in position 2-3: truncated \ uxxxxxxxx escape’ may occur.

The reason for the error is that “\” is used in a string such as a path, which is treated as an escape sequence. In the windows environment, the combination of ‘\’ and characters represents an escape sequence. Python provides escape sequences including \\(backslash) and \n (line spacing).

Generally speaking, the path is as follows:

C:\Users\Desktop\myproject

 

Solution:

Windows:

Use the escape sequence “\\” representing the backslash (on windows\), as follows:

C:\\Users\\Desktop\\myproject

Unix:

Use “/” to separate directories

C:/Users/Desktop/myproject

Jsondecodeerror error: json.decoder.JSONDecodeError: Expecting value: line 1 column 26 (char 25)

json.decoder.JSONDecodeError: Expecting value: line 1 column 26 (char 25)

Cause: JSON format conversion error, not standard JSON format


Note:
(1) the parentheses indicate the object. The object must be composed of attributes, which are composed of key value pairs

(2) Use double quotation marks for attribute values in JSON

(3) If the attribute value in JSON is a logical value or null value, it must be lowercase, false, true and null
① true in JSON, true in Python
② false in JSON, false in Python
③ null in JSON and none in Python

(4) Conversion between JSON data type and Dictionary (pre operation pilot library → import JSON):
① convert JSON to dictionary → JSON. Loads()
② convert dictionary to JSON → JSON. Dumps()

Raspberry pie compilation and installation opencv error: fatal error: bootdesc_bgm.i: No such file or directory

~/opencv_contrib/modules/xfeatures2d/src/boostdesc.cpp:673:20: fatal error: boostdesc_bgm.i: No such file or directory

Solution:
Check the /home/pi/Downloads/opencv-3.4.0/build/CMakeDownloadLog.txt log file, search for boostdesc_bgm.i keyword in the log file CMakeDownloadLog.txt, and find that the download of this file has failed.
A total of 11 files were found to be missing as follows:
boostdesc_bgm.i
boostdesc_bgm_bi.i
boostdesc_bgm_hd.i
boostdesc_lbgm.i
boostdesc_binboost_064.i
boostdesc_binboost_128.i
boostdesc_binboost_256.i
vgg_generated_120.i
vgg_generated_64.i
vgg_generated_80.i
vgg_generated_48.i

Download and upzip. put them in the path of /home/pi/Downloads/opencv_contrib3.4.0/modules/xfeatures2d/src/ is OK.
Then re-compile:

make clean
make

[Solved] AttributeError: module ‘tensorflow._api.v2.train‘ has no attribute ‘AdampOptimizer‘

Error Message: AttributeError: module ‘tensorflow._api.v2.train’ has no attribute ‘AdampOptimizer’
Tensorflow 2.6.0:

>>> import tensorflow as tf
>>> tf.__version__
'2.6.0'

Error code snippet:

model.compile(optimizer=tf.train.AdampOptimizer(0.001),
              loss='mse',
              metrics=['accuracy'])

Replace with:

from tensorflow.keras.optimizers import Adam
model.compile(optimizer=Adam(learning_rate=0.001), loss='mse', metrics=['accuracy'])

It can also be changed as follows:

model.compile(optimizer='adam',
              loss='mse',
              metrics=['accuracy'])

Both are operational.

Pytorch: error message with chunks of 0 [How to Solve]

File "D:/Codes/code/Python Project/group_reid-master/group_reid-master/main_group_gcn_siamese_part_half_fulltest_sink.py", line 348, in train_gcn
    loss.backward()
  File "D:\Codes\Anaconda3\envs\pytorch_gpu\lib\site-packages\torch\tensor.py", line 185, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph)
  File "D:\Codes\Anaconda3\envs\pytorch_gpu\lib\site-packages\torch\autograd\__init__.py", line 127, in backward
    allow_unreachable=True)  # allow_unreachable flag
RuntimeError: chunk expects `chunks` to be greater than 0, got: 0
Exception raised from chunk at ..\aten\src\ATen\native\TensorShape.cpp:496 (most recent call first):

As shown in the figure, I always reported an error chunk of 0. At first, I was puzzled. There was no similar situation with me when looking for information on the Internet. I typed the error and found that an error was reported in the derivation of loss (the figure below). I thought that loss is a function called, and it is impossible to report such an error. So throw it directly on the server to debug. Due to different versions of pytorch, the error content is also different. We finally found the error in pytorch version 1.1.

            loss.backward()

It was caused by dimension mismatch during cutting:

env11_junk1 = env11.squeeze().unsqueeze(0).unsqueeze(0).repeat((5-x1_valid.shape[0]), parts, 1)
env22_junk2 = env22.squeeze().unsqueeze(0).unsqueeze(0).repeat((5-x2_valid.shape[0]), parts, 1)
env11 = env11.squeeze().unsqueeze(0).unsqueeze(0).repeat(x1_valid.shape[0], parts, 1)
env22 = env22.squeeze().unsqueeze(0).unsqueeze(0).repeat(x2_valid.shape[0], parts, 1)

  # calculate within graph and inter graph message
h_k1 = torch.cat((self.W_x(x1[i, :sample_size1, :]), self.W_neib(x_neib1), self.W_relative(mu1), self.W_env(env11)), 2).unsqueeze(0)  
h_k_junk1 = torch.cat((self.W_x(x1[i, sample_size1:, :]), self.W_x(x1[i, sample_size1:, :]), self.W_x(x1[i, sample_size1:, :]),self.W_env(env11_junk1)), 2).unsqueeze(0)

h_k2 = torch.cat((self.W_x(x2[i, :sample_size2, :]), self.W_neib(x_neib2), self.W_relative(mu2), self.W_env(env22)), 2).unsqueeze(0)
h_k_junk2 = torch.cat((self.W_x(x2[i, sample_size2:, :]), self.W_x(x2[i, sample_size2:, :]), self.W_x(x2[i, sample_size2:, :]),self.W_env(env22_junk2)), 2).unsqueeze(0)                       

In my code (square and unsqueeze are redundant, just premute directly). I intended to copy the same first dimension as X1 in the first dimension, but in the actual data set, the first dimension of X1 may be 0. Therefore, if the parameter of repeat is 0, an error will be reported, which cannot be less than the original dim. Since the error reported is not obvious, I wasted half a day thinking about this problem. I hereby record it.

[Solved] Demjson error: ERROR: Command errored out with exit status 1

    ERROR: Command errored out with exit status 1:
     command: /data/wangzy-p/soft/anaconda3/envs/tf_1.14/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-lkidxq7i/demjson_1adc3de9a48e4e169cf993fa26319b82/setup.py'"'"'; __file__='"'"'/tmp/pip-install-lkidxq7i/demjson_1adc3de9a48e4e169cf993fa26319b82/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-ldwnwp11
         cwd: /tmp/pip-install-lkidxq7i/demjson_1adc3de9a48e4e169cf993fa26319b82/
    Complete output (1 lines):
    error in demjson setup command: use_2to3 is invalid.

Solution

When setuptools > 58.0.0 , the dependency installation of demjson failed, demjson has been published demjon3 to solve this problem, use reference https://pypi.org/project/demjson3

Using postman Test Django Interface error: RuntimeError:You called this URL via POST,but the URL doesn‘t end in a slash

1. Access interface

Using the postman provider

2. Error reporting:

RuntimeError:You called this URL via POST,but the URL doesn’t end in a slash and you have APPEND_ SLASH set. Django can’t redirect to the slash URL while maintaining POST data.

3. Solution:

In fact, two methods have been suggested in the error report

Method 1: add a at the end of the URL/

http:10.192.171.128:8000/ops/rbac/group/distribute

Method 2: set append in settings_ SLASH=False