Tag Archives: python

seaborn.load_ Data set error urlerror: < urlopen error [winerror 10060] the connection attempt failed because the connecting party did not reply correctly after a period of time or the connected host did not respond

In case of urlerror: & lt; Urlopen error [winerror 10060] the connection attempt failed because the connecting party did not reply correctly after a period of time or the connected host did not respond& gt; Before this problem, you may encounter this error: urllib. Error. Urlerror: & lt; urlopen error [Errno 11004] getaddrinfo failed>, The solutions are as follows:

 
one   urllib.error.URLError: < urlopen error [Errno 11004] getaddrinfo failed>

Method 1: modify the DNS address https://blog.csdn.net/qq_ 43474959/article/details/107902588

Method 2: if you still can’t get it, you can directly download the data set to the Seaborn data file directory. Generally, the address of Seaborn data is in the C: (users) directory, and the download address of Seaborn data set is: https://codechina.csdn.net/mirrors/mwaskom/seaborn-data?utm_ source=csdn_ github_ accelerator

 
2. URLError: < Urlopen error [winerror 10060] the connection attempt failed because the connecting party did not reply correctly after a period of time or the connected host did not respond& gt;

After solving the first problem, continue to run. You may encounter new errors. The solutions are as follows:

Step 1: make sure that the downloaded data set is stored in the Seaborn data folder. Note that this folder is generated automatically and should be brought with the Seaborn library when it is installed. The general path is C: (users) \ \ (user name) \ \ Seaborn data

Step 2: check the storage format of the downloaded library. My initial file format was. Data, which led to an error. It is recommended to change the suffix to. CSV, and then run it again

django.db.utils.OperationalError: no such table: django_admin_log

Problem orientation


Using Python shell to delete custom user table data

from MyApp import models
dU = models.SysUsers.objects.all()
dU.delete()

The error is as follows

django.db.utils.OperationalError: no such table: django_admin_log

terms of settlement


Direct migrate may not work. Parameters should be added as follows

python manage.py makemigrations
python manage.py migrate --run-syncdb

ValueError: The field admin.LogEntry.user was declared with a lazy reference to ‘MyApp.sysusers‘

Problem description


E:\SweetYaya\MyProj03>python manage.py migrate
Operations to perform:
  Apply all migrations: MyApp, admin, auth, contenttypes, sessions
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 202, in handle
    pre_migrate_apps = pre_migrate_state.apps
  File "D:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Program Files\Python36\lib\site-packages\django\db\migrations\state.py", line 208, in apps
    return StateApps(self.real_apps, self.models)
  File "D:\Program Files\Python36\lib\site-packages\django\db\migrations\state.py", line 277, in __init__
    raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'MyApp.sysuser', but app 'MyApp' doesn't provide model 'sysuser'.

Find your own python3. X and enter the site packages/Django/contrib/admin/migrations file directory__ init__. Py file, delete all others( Be careful not to__ init__. If you delete the PY file, don’t delete the migrations in the folder contrib/contenttypes. Otherwise, the function of migrate will be invalid and Django can only be removed.

Detailed explanation of Python__ new__() method

The new () method mainly exists in the new class of Python 2 and in Python 3. It is the static method responsible for creating class instances.

When Python instantiates an object, it first calls the__ new__() Method to construct an instance of a class and allocate the memory space of the corresponding type for it. The memory address of the instance is its unique identifier. And then call__ init__() Method to initialize an instance, usually the properties of the instance.

Here are some examples to illustrate:

Example 1: call first__ new__() Method call again__ init__() method

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        return super().__new__(cls)
    
    def __init__(self):
        print("__init__ called")
		  
a = Person()
		

result:

__new__ called
__init__ called

Example 2: the new () method constructs a class instance and passes it to its own__ init__() Method, i.e__ init__() The self parameter of the method.

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        instance = super().__new__(cls)
        print(type(instance))
        print(instance)
        print(id(instance))
        return instance
    
    def __init__(self):
        print("__init__ called")
        print(id(self))

b = Person()

result:

__new__ called
<class '__main__.Person'>
<__main__.Person object at 0x1093c1580>
4449899904
__init__ called
4449899904

Example 3: if__ new__() Method does not return any instances, the init () method will not be called.

class Person(object):
    
    def __new__(cls):
        print("__new__ called")

    def __init__(self):
        print("__init__ called")

c = Person()

result:

__new__ called

Example 4: if__ new__() Method returns an instance of another class__ init__() Method will not be called. Moreover, the new () method will initialize an object of another class.

class Animal(object):

    def __init__(self):
        pass

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        return Animal()

    def __init__(self):
        print("__init__ called")

d = Person()
print(type(d))
print(d)

result:

__new__ called
<class '__main__.Animal'>
<__main__.Animal object at 0x10fea3550>

Example 5: if overridden__ new__() Method, except for the CLS parameter, if no other parameters are set, it cannot be used__ init__() Method to set initialization parameters.

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        instance = super().__new__(cls)
        return instance
    
    def __init__(self, name):
        print("__init__ called")
        self.name = name

e = Person("Eric")
print(e.name)

result:

Traceback (most recent call last):
  File "example.py", line 102, in <module>
    e = Person("Eric")
TypeError: __new__() takes 1 positional argument but 2 were given

Example 6: in rewriting__ new__() Method, you need to add * args, * * kwargs to the parameters, or explicitly add the corresponding parameters to pass__ init__() Method initialization parameters.

class Person(object):
    
    def __new__(cls, *args,**kwargs):  # Or def __new__(cls, name)
        print("__new__ called")
        instance = super().__new__(cls)
        return instance
    
    def __init__(self, name):
        print("__init__ called")
        self.name = name

e = Person("Eric")
print(e.name)

result:

__new__ called
__init__ called
Eric

[Solved] Access to XMLHttpRequest at ‘http://127.0.0.1:5000/markdownlang/‘ from origin ‘null‘ has been bl

When AJAX is used, the above cross domain request error is reported (using Python flash to build the background)

Error code:

from flask import Flask,render_template
@app.route("/markdownlang/",methods=["post"])
def getMarkdownLang():
    return render_template('result.html')

Solution: add a response header on the server side to simply allow cross source.

from flask import Flask,render_template,make_response
@app.route("/markdownlang/",methods=["post"])
def getMarkdownLang():
    resp = make_response(render_template('result.html'))
    resp.headers['Access-Control-Allow-Origin'] = '*'   
    return resp

There are two other things that can go wrong:

    1. the requested path is not complete. Full path http://127.0.0.1:port number/file path. Cross source must have full path. The request mode has no corresponding response code on the server side. For example, the server should have a post response for a post request

Django PythonConsole error: Requested setting DEFAULT_INDEX_TABLESPACE

Error:
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Solution:
Add to the python file that reports the error:

import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings") # project_name project name
django.setup()

ROS generate_messages_cpp [Compiler error resolution]

ROS generate_ messages_ Solution of CPP compilation error

Learning the knowledge of C + + and python joint programming under ROS, there is an error report when compiling cpp file, the following process is recorded:

    1. in the reference → Article 1 ← for configuration, the insertion of CPP and py has been completed, and

catkin is performed_ There are errors in the make

    1. steps, and the error contents are as follows:
CMake Error at my_pkg/CMakeLists.txt:27 (add_dependencies):
  The dependency target "my_pkg_generate_messages_cpp" of target "listener"
  does not exist.

The cmake version is adjusted according to Article 2 ←, and no error is reported. The principle is that cmake before 3.0 will turn this error report into a warning, and it has passed the compilation, but in actual use, it is still unable to find the listener program built from CPP. Finally, the cmakelists is adjusted according to Article 3 ←,
– first of all, Add the following code block:

catkin_package(
 INCLUDE_DIRS include
# LIBRARIES strands_gazing
 CATKIN_DEPENDS std_msgs
# DEPENDS system_lib
)

After that, in Add_ Added ${catkin> to dependencies _ EXPORTED_ Targets} finally, when compiling, execute catkin first_ make --pkg my_ PKG (here is the PKG name) , and then execute catkin_ Make problem solving

Finally, the revised cmakelists :

cmake_minimum_required(VERSION 3.0.2)
project(my_pkg)

## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)

find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
)

catkin_package(
  INCLUDE_DIRS include
# LIBRARIES strands_gazing
  CATKIN_DEPENDS std_msgs
# DEPENDS system_lib
)

include_directories(include/my_pkg ${catkin_INCLUDE_DIRS}) 
add_executable(listener src/listener.cpp) 
target_link_libraries(listener ${catkin_LIBRARIES}) 
add_dependencies(listener my_pkg_generate_messages_cpp ${catkin_EXPORTED_TARGETS})

No module named numpy error in Python code

Generally, numpy is installed in “control panel + CMD”

Enter “PIP install numpy” in the command line window

The numpy installed at this time is not in the directory line of Python

No module named numpy will report an error, even if “import numpy as numpy” is imported at the beginning of the python program

2. Solutions:

(1) It is to directly find the python installation location in the DOS window and directly enter the “PIP install numpy” statement

Enter enter and wait for installation

(2) Is it mandatory to download the latest version after installation

Find the installation location of Python in DOS window, and input “PIP install numpy — ignore installed numpy” statement

Will be forced to reload in a new location, this is to install the numpy package into python

Note that the following statement is entered in the win system

If you want to build a Linux system, you should add more “sudo” fields in front of it

Namely: “sudo PIP install numpy — ignore installed numpy”

This chapter is my opinion, let’s make progress together

Record the python package EXE file running error importerror, but do not prompt specific error solution

Problem Description:
I made a program, the main program is osrr.py, which imports the other two files excela.py and excelb.py. When I run in visual studio, the program can run normally, but after I use pyinstaller to package it into a separate EXE file, the operation will report an error of “importerror”, but there is no prompt to import which name, The packing command is: pyinstall – F osrr.py – P excela.py – P excelb.py — hidden import excela — hidden import excelb. The error is as shown in the figure below

Problem solving process:
when I didn’t create a new excelb.py, osrr.py and excel.py can be packaged normally. When I created a new excelb and imported it into osrr.py, an error was reported. So I created a new project in excelb.py and imported it into osrr.py. After that, an error was also reported, as shown in the figure below

I deleted all the imports in test1.py, and then tried them one by one, and found that there was a problem with this string of codes:
from pynput.keyboard import key, controller, but the code I wrote ran directly in vs without any error, so I could run normally.

Solution:
I found an article on the Internet, which introduced the reasons and solutions (I’m sorry I didn’t know how to blog before, but I can’t find that article after I finally found this function, I’m sorry for the old brother of the original author)
the cause of the problem is the version of pynput. If the latest version 1.7.3 is installed, the above problems will appear when using the package. Use “PIP install pynput” to uninstall the package, and then use the command “PIP install pynput = = 1.6.8” to install version 1.6.8. After the installation is completed, no error will be reported whether the package exe program or running directly in vs.

Unhandled project rejection type error: webassembly instance

Today, I created a new small program project in wechat developer tool
but when I opened it, such a bug appeared
which made me feel very confused

Unhandled promise rejection TypeError: WebAssembly Instantiation: Argument 0 must be a buffer source or a WebAssembly.Module object

It was very uncomfortable
I went to the wechat developer community and asked
it turned out that the default version of the basic debugging library was too high, which led to an error

A simple solution

Click the details button in the upper right corner
and select local settings
to adjust the basic debugging library back to 2.14.4

Image input data check: Nan inf and do not exist

import os
import cv2
import numpy as np
from tqdm import tqdm

# read txt file content to list
def ReadTxt_to_list(rootdir):
    lines = []
    with open(rootdir, 'r') as file_to_read:
        while True:
            line = file_to_read.readline()
            if not line:
                break
            line = line.rstrip('\n')
            lines.append(line)
    return lines

def check_exist_nan(lstFile):
    rt = os.path.split(lstFile)[0]
    notExist = open(os.path.join(rt,'Lst_notExist.txt'),'w')
    bad = open(os.path.join(rt,'Lst_bad.txt'),'w')

    lines = ReadTxt_to_list(lstFile)
    notNum = 0
    badNum = 0
    newLines = []
    for line in tqdm(lines):
        info_ = line.split('\t')
        assert len(info_) == 3
        _, filePth, idNum = info_
        if not os.path.exists(filePth):
            print('Not exist:', line)
            notExist.write(line+'\n')
            notNum += 1
        else:
            img = cv2.imread(filePth)
            try:
                if np.any(np.isnan(img)) or not np.all(np.isfinite(img)):
                    print('Nan/Inf:', line)
                    badNum += 1
                    bad.write(line + '\n')
                else:
                    newLines.append(line)
            except:
                print('Error:', line)
                badNum += 1
                bad.write(line + '\terror\n')

    print('Not exist', notNum)
    print('Bad', badNum)
    if len(lines) != len(newLines):
        newLst = open(os.path.join(rt,'Lst_new.txt'), 'w')
        for line in newLines:
            newLst.write(line+'\n')
        newLst.close()

    notExist.close()
    bad.close()

if __name__ == '__main__':
    imgLst = '/home/img.lst'
    check_exist_nan(imgLst)