Tag Archives: python

AttributeError: ‘Settings’ object has no attribute ‘ROOT_URLCONF’

AttributeError: ‘Settings’ object has no attribute ‘ROOT_ URLCONF’

If you encounter this problem. There are the following prerequisites,
1. You deploy with uwsgi + Django
2. You have modified the settings configuration file path, for example, create a dev.py file in a new place for configuration

Then you have to look at the configuration in uwsgi.ini. Whether the settings in the WSGI file is the configuration file you want.

The anaconda-navigator interface cannot be started, loading application, report ERROR download_api._get_url error

Anaconda3, which was originally installed, suddenly couldn’t be started today. It got stuck in the loading application interface. It was forced to uninstall and reinstall. The situation is the same. Errors are reported as follows:

C:\Users\ljw>anaconda-navigator
2021-09-08 22:24:45,500 - ERROR download_api._get_url:417
Expecting value: line 1 column 1 (char 0)

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window.py", line 499, in setup
    self.post_setup(conda_data=conda_data)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window.py", line 536, in post_setup
    self.tab_home.setup(conda_data)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\tabs\home.py", line 169, in setup
    self.set_applications(applications, packages)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\tabs\home.py", line 204, in set_applications
    apps = self.api.process_apps(applications, prefix=self.current_prefix)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\api\anaconda_api.py", line 903, in process_apps
    versions=[vsdata.get('productVersion')],
AttributeError: 'str' object has no attribute 'get'
^C
C:\Users\ljw>anaconda-navigator
2021-09-08 22:45:03,049 - ERROR download_api._get_url:417
Expecting value: line 1 column 1 (char 0)

The reason is the same as the connection analysis above, mainly because the vscode address obtained by self._VSCODE_ENDPOINT in vscode_application_data() is wrong ( https://vscode-update.azurewebsites.net/api/update/win32-x64/stable/version ). As a result of the visit, the correct address is: https://update.code.visualstudio.com/api/update/win32-x64/stable/version

Solution: in Anaconda_ Search in api.py

        VSCODE_ENDPOINT = (
            'https://vscode-update.azurewebsites.net/api/update'
            '/{}/stable/version'.format(VSCODE_SUBDIR)
        )

Change the link to:

        VSCODE_ENDPOINT = (
            'https://update.code.visualstudio.com/api/update'
            '/{}/stable/version'.format(VSCODE_SUBDIR)
        )

Save the file and restart Anaconda navigator to solve the problem

RuntimeError: CUDA error: device-side assert triggered

reason

The reason for the error is that when calculating the loss function in pytorch, the tag is (batch, height, width). If the category is 10, the value should be 0 ~ 9, that is:
0 & lt= value<= C-1, where C is the number of channels or categories

terms of settlement

My category is 10, and the value is 1 ~ 10, so you only need to subtract 1, as shown below.

c_loss = nn.CrossEntropyLoss()
labels_v = labels_v-1 
loss0 = c_loss(d0, labels_v.long())

Summary

This is mainly because the tag data of your training data may exceed the number of tags set in the configuration file. Or the number of tags in the validation set exceeds the number of tags in the training set.

Cv2.dnn read model error [How to Solve]

cv2.dnn read model error:

D:\ProgramData\Miniconda3\python.exe D:/project/detect/face/yolov5-face-landmarks-opencv/main_new.py
[ERROR:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\dnn\src\onnx\onnx_importer.cpp (1878) cv::dnn::dnn4_v20201117::ONNXImporter::handleNode DNN/ONNX: ERROR during processing node with 2 inputs and 1 outputs: [Add]:(430)
Traceback (most recent call last):
  File "D:/project/detect/face/yolov5-face-landmarks-opencv/main_new.py", line 126, in <module>
    yolonet = yolov5(confThreshold=args.confThreshold, nmsThreshold=args.nmsThreshold, objThreshold=args.objThreshold)
  File "D:/project/detect/face/yolov5-face-landmarks-opencv/main_new.py", line 23, in __init__
    self.net = cv2.dnn.readNet(r'D:\project\detect\face\yolov5-face-master\yolov5n-face.onnx')
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\dnn\src\onnx\onnx_importer.cpp:1887: error: (-2:Unspecified error) in function 'cv::dnn::dnn4_v20201117::ONNXImporter::handleNode'
> Node [Add]:(430) parse error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\dnn\src\onnx\onnx_importer.cpp:780: error: (-215:Assertion failed) blob_0.size == blob_1.size in function 'cv::dnn::dnn4_v20201117::ONNXImporter::handleNode'
>
Process finished with exit code 1

Reason:
opencv4.5.1 torch 1.9.0
torch1.9.0 export onnx,opencv4.5.1not supported

Solution:
torch change to version 1.7.1, torchvision 0.8.2 version  —–the other version wil report an error.

MAC: Clion configure C compiler Error: The C compiler identification is unknown

1 click let cmake detect

View error message:
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - Unix Makefiles" /Users/apple/CLionProjects/untitled16
-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc - broken
CMake Error at /Applications/CLion.app/Contents/bin/cmake/mac/share/cmake-3.17/Modules/CMakeTestCCompiler.cmake:60 (message):
  The C compiler
 
    "/usr/bin/cc"
 
  is not able to compile a simple test program.
 
  It fails with the following output:
 
    Change Dir: /Users/apple/CLionProjects/untitled16/cmake-build-debug/CMakeFiles/CMakeTmp
    
    Run Build Command(s):xxxx(can not find /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/core/include:)

2 view environment variables

cd ~
vim .bash_profile

It is found that the error path is cflags (I wonder why I set cflags to be a python library?) Solution: comment out this line of code. Result: Although there is no error message in red in this interface, the program still cannot be compiled

Replace c compiler [key to solving the problem]

View all gcc compiler paths

brew list gcc
/usr/local/Cellar/gcc/11.2.0/bin/c++-11
/usr/local/Cellar/gcc/11.2.0/bin/cpp-11
/usr/local/Cellar/gcc/11.2.0/bin/g++-11
/usr/local/Cellar/gcc/11.2.0/bin/gcc-11
/usr/local/Cellar/gcc/11.2.0/bin/gcc-ar-11
/usr/local/Cellar/gcc/11.2.0/bin/gcc-nm-11
/usr/local/Cellar/gcc/11.2.0/bin/gcc-ranlib-11
/usr/local/Cellar/gcc/11.2.0/bin/gcov-11
/usr/local/Cellar/gcc/11.2.0/bin/gcov-dump-11
/usr/local/Cellar/gcc/11.2.0/bin/gcov-tool-11
/usr/local/Cellar/gcc/11.2.0/bin/gdc
/usr/local/Cellar/gcc/11.2.0/bin/gdc-11
/usr/local/Cellar/gcc/11.2.0/bin/gfortran
/usr/local/Cellar/gcc/11.2.0/bin/gfortran-11
/usr/local/Cellar/gcc/11.2.0/bin/lto-dump-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-c++-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-g++-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-gcc-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-gcc-11.2.0
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-gcc-ar-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-gcc-nm-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-gcc-ranlib-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-gdc-11
/usr/local/Cellar/gcc/11.2.0/bin/x86_64-apple-darwin20-gfortran-11
/usr/local/Cellar/gcc/11.2.0/include/c++/ (796 files)
/usr/local/Cellar/gcc/11.2.0/lib/gcc/ (1304 files)
/usr/local/Cellar/gcc/11.2.0/libexec/gcc/ (15 files)
/usr/local/Cellar/gcc/11.2.0/share/gcc-11.2.0/ (4 files)
/usr/local/Cellar/gcc/11.2.0/share/man/ (12 files)

C compiler and C + + compiler use respectively:

/usr/local/Cellar/gcc/11.2.0/bin/gcc-11
/usr/local/Cellar/gcc/11.2.0/bin/g++-11

After selection, Clion automatically compiles and succeeds.

[Solved] Error when vscode activates Python virtual environment

After executing Python – M venv myvenv to create a python virtual environment, the following error is reported when executing the script

The file D:\Tools\Python37\Scripts\Activate.ps1 could not be loaded, because running scripts is disabled on this system.

The reason is that windows prohibits unsigned scripts from running. You can solve this problem by executing the command set executionpolicy remotesigned in PowerShell.

[Solved] D2lzh_Pytorch Import error: importerror: DLL load failed while importing

Import d2lzh_Pytorch reports an error, importerror: DLL load failed while importing_ Torchtext: the specified program cannot be found.!! OMG

Guide Package

import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import sys
sys.path.append("..") 
import d2lzh_pytorch as d2l

The error is as follows:

ImportError: DLL load failed while importing _torchtext: The specified program could not be found.

The solution is as follows:

#check torch version
import torch
print(torch.__version__) #1.7.0

#Download the torchtext that corresponds to your own torch version
pip install torchtext==0.6

Perfect solution to the problem

Pytorch directly creates a tensor on the GPU error [How to Solve]

Pytoch directly creates tensors on the GPU and reports an error: Legacy constructor expectations device type: cpubut device type: CUDA was passed

General tensor creation method:

torch.Tensor(x)	

However, by default, the tensor is placed in the CPU (memory). If we want to use the GPU to train the model, we must also copy the tensor to the GPU, which will obviously save time
I’ve seen other articles before saying that tensors can be created directly on the GPU, so I’ve also made a try:

MyDevice=torch.device('cuda:0')
x = torch.LongTensor(x, device=MyDevice)

An error is reported when running the program:

legacy constructor expects device type: cpu but device type: cuda was passed

According to the error report analysis, the problem is that the device parameter cannot be passed ‘CUDA’?After checking, I found that the official answer given by pytorch is that tensor class is a subclass of tensor and cannot pass parameters to its device. There is no problem using the tensor class to build
⭐ Therefore, the code is changed as follows:

MyDevice = torch.device('cuda:0')
x = torch.tensor(x, device=MyDevice)
x = x.long()

Now, there will be no more errors.

SSL error of urllib3 when Python uploads files using Minio

Problems arise

Minio’s server always uses HTTP for access, but recently, due to business requirements, all requests have been replaced with HTTPS requests. After changing to HTTPS, this error will be reported when uploading the file: urlib3. Exceptions. Maxretryerror: httpsconnectionpool (host = ‘10.10.30.241’, port = 9000): Max retries exceeded with URL:/Facebook?Location = (caused by sslerror (sslcertverificationerror (1, ‘[SSL: Certificate_ VERIFY_ FAILED] certificate verify failed: self signed certificate (_ ssl.c:1124)’)))

Solution 1

Because I saw that the error was reported by urlib, I directly searched the urlib source code and directly modified the urlib 3 source code to solve the problem.
the modified file is: connectionpool.py

modify line 775 of connectionpool.py file:

self.cert_reqs = 'CERT_NONE'

Solution 2

The first method is solved, but it is extremely inconvenient
because you need to modify the source code every time you need to change the deployment script or reinstall it
then I went through the Minio source code and found the problem

the urliib in Minio did not turn off SSL verification. I wanted to change it here, but I thought of changing the source code here. I looked carefully and found the next parameter: http_ client

We only need to customize this parameter when creating Minio objects

    minioClient = Minio(
        '1.1.1.1:9000',
        access_key='mxxxxxxx',
        secret_key='mxxxxxxx',
        http_client=urllib3.PoolManager(
            timeout=urllib3.util.Timeout(connect=10, read=10),
            maxsize=10,
            cert_reqs='CERT_NONE',
            ca_certs= os.environ.get('SSL_CERT_FILE') or certifi.where(),
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504]
            )
        )
        # secure=False
    )

So far, the problem is solved

Attach Minio file to upload all codes

import logging
from minio import Minio
from minio.error import S3Error
import urllib3
import certifi
import os
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logging.basicConfig(
    level=logging.INFO,
    filename='../mysqlbackup_up.log',
    filemode='a',
    format='%(asctime)s %(name)s %(levelname)s--%(message)s'
)



def upload_file(file_name, file_path):

    minioClient = Minio(
        '1.1.3.1:9000',
        access_key='mxxxxx',
        secret_key='mxxxxxx',
        http_client=urllib3.PoolManager(
            timeout=urllib3.util.Timeout(connect=10, read=10),
            maxsize=10,
            cert_reqs='CERT_NONE',
            ca_certs= os.environ.get('SSL_CERT_FILE') or certifi.where(),
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504]
            )
        )
        # secure=False
    )

    check_bucket = minioClient.bucket_exists("test")

    if not check_bucket:
        minioClient.make_bucket("test")
    try:
        logging.info("start upload file")
        minioClient.fput_object(bucket_name="test", object_name=file_name, file_path=file_path)
        logging.info("file {0} is successfully uploaded".format(file_name))
        print('success')
    except FileNotFoundError as err:
        print(err)
        logging.error('upload_failed: ' + str(err))
    except S3Error as err:
        print(err)
        logging.error("upload_failed:", err)

Decode PUP data Error when reading radar data [How to Solve]

Example of reading pup radar data official website:

Run the sample code

from cinrad.io import PUP
pup_file='Z_RADR_I_Z9591_20210901004700_P_DOR_SA_V_10_230_60.591.bin'
f = PUP(path+pup_file)
data = f.get_data()

Error 1 connection timeout: (‘connection aborted.’, timeouterror (10060, ‘because the connection party is not correct after a period of time

Solution:

Add code to the program of the path to extend the connection time threshold timeout = 100, as shown in the figure

Error reporting matrix out of range

HTTPSConnectionPool(host=‘github.com’, port=443): Max retries exceeded with url: /Unidata/MetPy/raw/v1.0.1/staticdata/airport-codes.csv (Caused by ConnectTimeoutError(< urllib3.connection.HTTPSConnection object at 0x000001EA124FA370>, ‘ Connection to github.com timed out. (connect timeout=3)’))

resolvent:

Still in the program just now, add code

            s = requests.session()
            s.keep_alive = False
            # InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised.
            # HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url
            requests.packages.urllib3.disable_warnings()
            
            response = requests.get(url, **kwargs,timeout=100,verify=False,)  ####

Error report: three library package import error

Solution:

Change relative path to absolute path


Run successfully

VsCode+Anaconda+jupyter Error: Kernel died with exit code

The problem is solved later!!!!

Installation
vscade and Anaconda are installed on their own in Baidu. Python plug-ins are installed in vscade. The file operation of creating . Ipynb suffix is similar to the web version of Jupiter notebook
Error content:

Kernel died with exit code 1. D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\traitlets\traitlets.py:2196: FutureWarning: Supporting extra quotes around Unicode is deprecated in traitlets 5.0. Use 'hmac-sha256' instead of '"hmac-sha256"' – or use CUnicode. warn( D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\traitlets\traitlets.py:2151: FutureWarning: Supporting extra quotes around Bytes is deprecated in traitlets 5.0. Use '70f91ecb-d1b9-4e6f-bab4-f4eb00d14e8c' instead of 'b"70f91ecb-d1b9-4e6f-bab4-f4eb00d14e8c"'. warn( Traceback (most recent call last): File "D:\IDE\Anaconda3\envs\pytorch\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "D:\IDE\Anaconda3\envs\pytorch\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\ipykernel_launcher.py", line 16, in <module> app.launch_new_instance() File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\traitlets\config\application.py", line 844, in launch_instance app.initialize(argv) File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\traitlets\config\application.py", line 87, in inner return method(app, *args, **kwargs) File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\ipykernel\kernelapp.py", line 570, in initialize self.write_connection_file() File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\ipykernel\kernelapp.py", line 230, in write_connection_file write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport, File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file with secure_write(fname) as f: File "D:\IDE\Anaconda3\envs\pytorch\lib\contextlib.py", line 113, in __enter__ return next(self.gen) File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\jupyter_client\connect.py", line 100, in secure_write win32_restrict_file_to_user(fname) File "D:\IDE\Anaconda3\envs\pytorch\lib\site-packages\jupyter_client\connect.py", line 53, in win32_restrict_file_to_user import win32api ImportError: DLL load failed while importing win32api: 找不到指定的程序。

The solution is:

pip install pywin32==228