Category Archives: Python

[Solved] RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation

source code

	def anim(i):
		# update SMBLD
		cur_beta_idx, cur_step = i // num_steps, i % num_steps
		val = shape_range[cur_step]
		mesh.multi_betas[0, cur_beta_idx] = val  # Update betas
		fig.suptitle(f"{name.title()}\nS{cur_beta_idx} : {val:+.2f}", fontsize=50)  # update text

		return dict(mesh=mesh.get_meshes(), equalize=False)


Modified code

Add with torch.no_grad(): will be OK!

	def anim(i):
		# update SMBLD
		cur_beta_idx, cur_step = i // num_steps, i % num_steps
		val = shape_range[cur_step]
		#print("\ncur_beta_idx:",cur_beta_idx,mesh.multi_betas[0, cur_beta_idx])
		with torch.no_grad():###添加
			mesh.multi_betas[0, cur_beta_idx] = val  # Update betas
		fig.suptitle(f"{name.title()}\nS{cur_beta_idx} : {val:+.2f}", fontsize=50)  # update text

		return dict(mesh=mesh.get_meshes(), equalize=False)

[Solved] AttributeError: ‘WebDriver‘ object has no attribute ‘find_element_by_id‘

1. Question:

When learning the selenium part of the crawler, AttributeError appears: ‘WebDriver’ object has no attribute ‘find_ element_ by_ Id ‘problem.

2. Reasons:

Because of version iteration, find_element_by_id method is not supported in the new version of selenium.

3. Solution:

Modify button = browser.find_element_by_id(‘su’) to the following codes:

button = browser.find_element(By.ID,'su')

Add the following code at the front of the code page,

from selenium.webdriver.common.by import By

[Solved] AttributeError: module ‘tensorboard.summary._tf.summary‘ has no attribute ‘merge‘

The environment is TensorFlow2.9

The code to be run on github The TensorFlow environment is 1.x

Many apis cannot be called

Original code

train_summary_op = tf.summary.merge([loss_summary])

Error reporting in method 1

train_summary_op = tf.compat.v1.summary.merge([loss_summary])

display

TypeError: Tensors in list passed to 'inputs' of 'MergeSummary' Op have types [bool] that do not match expected type string.

If it can’t be solved, I will try

import tensorflow as tf

Modified as

import tensorflow._api.v2.compat.v1 as tf
tf.disable_v2_behavior()

Finally, solve the problem successfully

[Solved] TUM associate.py Scripte Error: AttributeError: ‘dict_keys‘ object has no attribute ‘remove‘

Running the script file reports an error


Cause of error.
Version difference between python2 and python3
In Python 3, dict.keys() returns the dict_keys object without the remove method. Unlike Python 2, Python 2 dict.keys() returns the list object.
In Python 3, dict.keys() returns a dict_ keys object (a view of the dictionary) which does not have remove method; unlike Python 2, where dict.keys() returns a list object.

 

Solution:
(1) Directly run with Python 2 forcely:

python2 associate.py rgb.txt depth.txt > associate.txt

(2) Still run it in python 3. Make a small change to the original source code

	for diff, a, b in potential_matches:
        if a in first_keys and b in second_keys:
            first_keys.remove(a)
            second_keys.remove(b)
            matches.append((a, b))
    
    matches.sort()
    return matches

Add two sentences above to change dict into list

	# two new lines
	first_keys = list(first_keys)
    second_keys = list(second_keys)
    for diff, a, b in potential_matches:
        if a in first_keys and b in second_keys:
            first_keys.remove(a)
            second_keys.remove(b)
            matches.append((a, b))
    
    matches.sort()
    return matches

Run again (Python here points to python3 by default)

python associate.py rgb.txt depth.txt > associate.txt

[Solved] ERROR: URL ‘s3://‘ is supported but requires these missing dependencies: [‘s3fs‘]. To install dvc wi

0. Preface
dvc error log

1. Main text
1.1 Problems

ERROR: URL 's3://' is supported but requires these missing dependencies: ['s3fs']. To install dvc with those dependencies, run:

	pip install 'dvc[s3]'

See <https://dvc.org/doc/install> for more info.

Enter as prompted

pip install 'dvc[s3]'

It doesn’t work…

1.2 Solutions

conda install -c conda-forge mamba
mamba install -c conda-forge dvc-s3

reference resources

[1] https://blog.csdn.net/scgaliguodong123_/article/details/122781190

department

[Solved] Fatal Python error: initfsencoding: Unable to get the locale encoding

Error Message:

Fatal Python error: initfsencoding: Unable to get the locale encoding

ModuleNotFoundError: No module named 'encodings'

 

Solution:

#1.unset
unset PYTHONHOME
unset PYTHONPATH
#2.update pip
python -m pip install --upgrade pip

Then it can be solved.

pip install decord failed. The reason is that pip has a problem. After the update, it is installed normally

[Solved] YOLOv5 Error: SyntaxError: EOL while scanning string literal

1. Error details

When running the detect.py file of YOLOv5 module, the following error occurs:

Complete error reporting code:

  File "C:\Projects\pythonProject\yolov5-5.0\detect.py", line 110
    with open(txt_path + '.txt', 'a') as f:
                                           ^
SyntaxError: EOL while scanning string literal

This problem occurs because detect.py encoding error

2.Solution

Delete the two lines of code at the top of the file, and the problem can be solved and detected.

# -*- coding : utf-8-*-
# coding:unicode_escape

[Solved] cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function ‘circle‘

Here, I operate on the image

import cv2
import numpy as np
img=cv2.imread('a.jpg',cv2.IMREAD_GRAYSCALE)
row,col=img.shape[:2]
print(row,col)
circle=np.zeros((row,col),dtype='uint8')
cv2.circle(circle,(row/2,col/2),100,255,-1)
result=cv2.bitwise_and(img,circle)
cv2.imshow('a',img)
cv2.imshow('circle',circle)
cv2.imshow('result',result)
cv2.waitKey(0)
cv2.destroyAllWindows()

An error is found during operation, as shown in the following figure

The error reported is a type error, which makes it impossible to analyze the coordinates of the center of the circle. This is mainly because our center coordinate is obtained by dividing the width and height of the picture by two. It is of float type, and the others are of int type. We can convert the center coordinate type to int type

cv2.circle(circle,(row//2,col//2),50,255,-1)

The results after operation are shown in the following figure:

 

[Solved] Django Configurate celery error: django.db.utils.DatabaseError

Error on execution of asynchronous task: 

django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias ‘default’ was created in thread id 3047101641304 and this is thread id 3047208084584.

 

Solution:

Original start command (under Windows):
celery -A xxx worker -l info -P eventlet (xxx is the project name)
Modified start command, celery version 4x:
celery -A xxx worker -l info -P solo

[>]

1. Questions 

[<twisted.python.failure.Failure < class  ' OpenSSL.SSL.Error ' >>]

solution:

If it is under Windows, the corresponding version of pyOpenSSL needs to be additionally installed. For example, pyOpenSSL- 0.13 .winxp32-py2. 7 .msi; if it prompts that there are no compiled files, you may also need to install mingwg. 
If it is under Linux, it is very simple, just pip install scrapy directly, it will automatically install the dependent package twisted. Using the same command under windows will cause the above problem, so additionally install the corresponding software.

 

[Solved] gym.error.NameNotFound: Environment PongNoFrameskip doesn’t exist.

Solution

The main reason for this error is that the gym installed is not complete enough.
When I first downloaded the gym library, I typed in

pip install gym

Later I learned that this download is the basic library

Error: gym.error.NameNotFound: Environment PongNoFrameskip doesn’t exist. Enter the following code

pip install ale-py
pip install gym[accept-rom-license]

[Solved] pyhive error: Could not start SASL: b’Error in sasl_client_start (-4) SASL(-4)

I have this problem when using pyhive, I am using anaconda3. I have checked many posts but I can’t solve it.

At first I found out that sasl needs to use some dll files in the E:\YingYongRJ\Anaconda\Lib\site-packages\sasl\sasl2 directory.

Finally found that anaconda3 moved this folder sasl2 at the end of the address to E:\YingYongRJ\Anaconda\Library\bin, resulting in the program not reading the location.

Use the following code: administrator console paste code.

FOR /F "usebackq delims=" %A IN (`python -c "from importlib import util;import os;print(os.path.join(os.path.dirname(util.find_spec('sasl'). origin),'sasl2'))"`) DO (
REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Carnegie Mellon\Project Cyrus\SASL Library" /v SearchPath /t REG_SZ /d "%A"
)

 

The above code is creating a search path for lib in the registry. But it still doesn’t work, we need to change it a bit more.

win+R and type regedit

regedit and click on the path: HKEY_LOCAL_MACHINE\SOFTWARE\Carnegie Mellon\Project Cyrus\SASL Library

Change the value of SearchPath to E:\YingYongRJ\Anaconda\Library\bin\sasl2 on it (pay attention to change to the address of their anaconda)

Then it’s fine