Category Archives: Python

Python calendar.month() Error [How to Solve]

When calling calendar.month today, an error is reported. The
code is as follows

import calendar

yy=int(input("year:"))
mm=int(input("month:"))
print(calendar.month(yy,mm))

The error report is shown in the figure below

look at the yellow part circled in the figure. Circular import may be circular. You can see that the program file name is calendar.py, which is consistent with the introduced calendar, so it causes an error.

Solution
just modify the file name, which cannot have the same name as the imported package

[Solved] NPM install Error: check python checking for Python executable python2 in the PATH

Scenario: after upgrading the node environment, an error is reported when the project version number does not match. After deciding to reinitialize, an error is reported again

Building: G:\nodejs\node.exe F:\test\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
gyp info it worked if it ends with ok
gyp verb cli [
gyp verb cli   'G:\\nodejs\\node.exe',
gyp verb cli   'F:\\test\\node_modules\\node-gyp\\bin\\node-gyp.js',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose',
gyp verb cli   '--libsass_ext=',
gyp verb cli   '--libsass_cflags=',
gyp verb cli   '--libsass_ldflags=',
gyp verb cli   '--libsass_library='
gyp verb cli ]
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed     at getNotFoundError (F:\test\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (F:\test\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (F:\test\node_modules\which\which.js:80:29)
gyp verb `which` failed     at F:\test\node_modules\which\which.js:89:16
gyp verb `which` failed     at F:\test\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at F:\test\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqCallback.oncomplete (fs.js:158:21)
gyp verb `which` failed  python2 Error: not found: python2
gyp verb `which` failed     at getNotFoundError (F:\test\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (F:\test\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (F:\test\node_modules\which\which.js:80:29)
gyp verb `which` failed     at F:\test\node_modules\which\which.js:89:16
gyp verb `which` failed     at F:\test\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at F:\test\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqCallback.oncomplete (fs.js:158:21) {
gyp verb `which` failed   stack: 'Error: not found: python2\n' +
gyp verb `which` failed     '    at getNotFoundError (F:\\test\\node_modules\\which\\which.js:13:12)\n' +
gyp verb `which` failed     '    at F (F:\\test\\node_modules\\which\\which.js:68:19)\n' +
gyp verb `which` failed     '    at E (F:\\test\\node_modules\\which\\which.js:80:29)\n' +
gyp verb `which` failed     '    at F:\\test\\node_modules\\which\\which.js:89:16\n' +
gyp verb `which` failed     '    at F:\\test\\node_modules\\isexe\\index.js:42:5\n' +
gyp verb `which` failed     '    at F:\\test\\node_modules\\isexe\\windows.js:36:5\n' +
gyp verb `which` failed     '    at FSReqCallback.oncomplete (fs.js:158:21)',
gyp verb `which` failed   code: 'ENOENT'
gyp verb `which` failed }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb `which` succeeded python G:\Python\Python37-32\python.EXE
gyp ERR! configure error
gyp ERR! stack Error: Command failed: G:\Python\Python37-32\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:295:12)
gyp ERR! stack     at ChildProcess.emit (events.js:210:5)
gyp ERR! stack     at maybeClose (internal/child_process.js:1021:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
gyp ERR! System Windows_NT 10.0.18362
gyp ERR! command "G:\\nodejs\\node.exe" "F:\\test\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsas
s_library="
gyp ERR! cwd F:\test\node_modules\node-sass
gyp ERR! node -v v12.13.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN [email protected] requires a peer of ajv@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2019-11-18T07_33_10_767Z-debug.log

Process finished with exit code 1

The solution for online search is:

npm install --global windows-build-tools --save

But it got stuck when installing windows build tools, so the solution is as follows

1, run npm install -g windows-build-tools
2, in the %temp% folder, find the latest file with a filename similar to dd_installer_20210421124746.log
3, check this file, make sure the log output Closing the installer with exit code 0
4, make sure you have vscode installed
PS: In fact, you can skip steps 2-4, because your python environment has already been installed, and the repeated steps of the installer have already been executed.
5, create a file named dd_client_.log in the %temp% directory
6, edit the file created in 5, add a line Closing installer. return code: 3010. and save it.
Note: Paste %temp% directly in Explorer to open your Windows temp directory.

Finally, NPM install is installed successfully

[Solved] Python Error: positional argument follows keyword argument

Syntax error: position argument follows keyword argument
syntax error: position parameter follows keyword parameter
error example </ font>

def sub(a, b):
    return

s3 = sub(a = 9, 3)
s4 = sub(b = 9, 3)

When a function is called, an error will be reported if the parameter passed (····, formal parameter = argument, argument, ······) occurs
solution:
make the following modifications

def sub(a, b,):
    return
s0 = sub(9,3)
s1 = sub(a=9, b=3)
s2 = sub(9, b = 3)

Pandas Error: ValueError: setting an array element with a sequence.

Pandas apply returns multiple columns

Originally, I wanted to process the dataframe line by line through NP. Vectorize() and return several new fields. An error valueerror: setting an array element with a sequence

def test():
    arr = np.random.randn(4,4)
    cols = ['a', 'b', 'c']
    df = pd.DataFrame(data=arr,columns=['e','f','g','h'])
    def func(a,b,c):
        output1 = a+1
        output2 = b*2
        output3 = c-4
        return pd.Series([output1,output2,output3])
    vfunc = np.vectorize(func)
    df[cols] = vfunc(df['e'],df['f'],df['g'])
    print(df)
test()

The reason for the error is that the assigned DF [cols] is inconsistent with the dimension returned by vffunc, and the shape between the returned data frame and the result does not match. Use apply to solve it, and the parameter result_ Type = “expand” means that the result will be converted into columns, and each returned value will be used as the value in the column of result dataframe. In apply (func), the number of results returned by func should be the same as the number of col columns in DF [col]

def test():
    arr = np.random.randn(4,4)
    cols = ['a', 'b', 'c']
    df = pd.DataFrame(data=arr,columns=['e','f','g','h'])
    def func(row):
        a,b,c = row['e'],row['f'],row['g']
        output1 = a+1
        output2 = b*2
        output3 = c-4
        return output1,output2,output3
    df[cols] = df.apply(func,axis=1, result_type="expand")
    print(df)
test()

output

          e         f         g         h         a         b         c
0  0.493280 -0.092513 -3.014135 -0.361842  1.493280 -0.185027 -7.014135
1  0.300695 -0.745392  0.591653 -1.752471  1.300695 -1.490785 -3.408347
2 -0.033944 -1.556307 -0.359979  1.808213  0.966056 -3.112615 -4.359979
3  0.701741 -0.272337  0.041114  0.150049  1.701741 -0.544674 -3.958886

For a single column

df['id'] 

And

ID = ['id']
df[ID]

The results obtained are different. The former is [1,2,3,4], and the latter is [[1], [2], [3], [4]

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

Segmentation fault (core dumped) in open3d operation [Solved]

When using open3d, normal visualization can be performed after the point cloud is established, but it involves calculation, such as calling estimate_ Normals or o3d.pipelines.registration.registration_ ICP, an error segmentation fault (core dumped) will be reported

Solution: import open3d as O3D at the beginning( It seems that the reference order of some packages will affect open3d.)

# Here are my codes below:
pc_pre=o3d.geometry.PointCloud()  
pc_cur=o3d.geometry.PointCloud()
pc_pre.points=o3d.utility.Vector3dVector(pre_cloud)
pc_cur.points=o3d.utility.Vector3dVector(cur_cloud)
res=o3d.pipelines.registration.registration_icp(source=pc_cur,target=pc_pre,
        max_correspondence_distance=threshold)
print(res)

[Solved] Python Error: local variable ‘var‘ referenced before assignment

Unboundlocalerror: local variable ‘var’ referenced before assignment
local variable “var” referenced before assignment

error example 1

var = 10
def f1():
    print(var)
    var = 2
    print(var)
f1()

When VaR is a global variable, it is modified and undeclared in the function

solution:
declare the global variable Global var  before calling

error example 2 

def f2():
    var = 0
    def f3():
        var *= 0
        return var
    return f3()
f2()

VaR is a local variable defined in F2. Its value is modified in nested functions and is not declared
solution:
declare nonlocal var  in nested functions in advance

Panda error in modifying line name index does not support mutable operations

During the panda data operation, two tricks appear during expansion:

Using data_PD. Append(), when expanding data in rows, the row names need to be the same in order to realize automatic expansion and use data_ PD. Columns = [], when modifying the row name, slicing is not allowed, and only a list can be created according to the original data length for assignment modification

# Iterate through different individual data and perform data stitching
response_pd = pd.DataFrame() # Create an empty panda
for ii in range(100, 106):
    sub = 'Sub%d'%ii
    index = np.where((np.array(filter_pd[sub+'_fg'])!=-100)&
                    (np.array(filter_pd[sub+'_frt'])!=-100))[0]
    ii=ii-100
    col_index =list(range(2, 7))+list(range(8, 20))+[23+ii*4,21+ii*4,22+ii*4]
    # Filter the data in the specified row
    temp_pd=filter_pd.iloc[index].iloc[:, col_index]
    ## Modify the row names, note that the slicing operation is not allowed here, only the original data length, create a list to assign values
    temp_pd.columns = list(temp_pd.columns)[:-3]+['first glance', 'first RT', 'last RT']
    # Expand the rows, note that you need the same row name to expand the data for the corresponding row
    response_pd = response_pd.append(temp_pd,
                                ignore_index=True)
    print('table shape',response_pd.shape)

Python asynchronous co process crawler error: [aiohttp. Client]_ Exceptions: serverdisconnected error: Server Disconnected]

Background description:

I just started to contact crawlers, read online tutorials and began to learn a little bit. All the knowledge points are relatively shallow. If there are better methods, please comment and share.

The initial crawler is very simple: crawl the data list in a web page, and the format returned by the web page is also very simple. It is in the form of a dictionary, which can be directly accessed by saving it as a dictionary with . Json() .

At the beginning of contact with asynchronous collaborative process, after completing the exercise, try to transform the original crawler, resulting in an error.

Initial code:

async def download_page(url):
	async with aiohttp.ClientSession() as session:
		async with session.get(url) as resp:
			await result = resp.text()

async def main(urls):
	tasks = []	
	for url in urls:
		tasks.append(asyncio.create_task(download_page(url)))  # 我的python版本为3.9.6
	await asyncio.await(tasks)

if __name__ == '__main__':
	urls = [ url1, url2, …… ]
	asyncio.run(main(urls))

This is the most basic asynchronous collaborative process framework. When the amount of data is small, it can basically meet the requirements. However, if the amount of data is slightly large, it will report errors. The error information I collected is as follows:

aiohttp.client_exceptions.ClientOSError: [WinError 64] The specified network name is no longer available.
Task exception was never retrieved

aiohttp.client_exceptions.ClientOSError: [WinError 121] The signal timeout has expired
Task exception was never retrieved

aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
Task exception was never retrieved

The general error message is that there is a problem with the network request and connection
as a beginner, I didn’t have more in-depth understanding of network connection, nor did I learn more in-depth asynchronous co process operation. Therefore, it is difficult to solve the problem of error reporting.

Solution:

The big problem with the above error reports is that each task creates a session. When too many sessions are created, an error will be reported.

Solution:

Try to create only one session

async def download_page(url,session):
	async with session.get(url) as resp:
		await result = resp.text()

async def main(urls):
	tasks = []	
	async with aiohttp.ClientSession() as session:  # The session will be created in the main function, and the session will be passed to the download_page function as a variable.
		for url in urls:
			tasks.append(asyncio.create_task(download_page(url,session)))
			#My python version is 3.9.6, python version 3.8 and above, if you need to create asynchronous tasks, you need to create them via asyncio.create_task(), otherwise it will run normally but will give a warning message await asyncio.await(tasks)

if __name__ == '__main__':
	urls = [ url1, url2, …… ]
	asyncio.run(main(urls))

In this way, the problem of connection error can be solved to a certain extent when crawling a large amount of data.

Sentiment:  in the process of programming, thinking should be more flexible. A little change may improve the efficiency a lot.

Solve the problem of error reporting from scipy.misc import imread & imresize in Python

from scipy.misc import imread& imresize

Problem description solution 1 solution 2

Problem description

from scipy.misc import imread # error

After query, the reason is that the from scipy.misc import imread, imwrite and other methods have been abandoned, and python has encapsulated the imread method in the imageio module

Solution 1

To install the imageio Library:

pip install imageio 

Normal use!

import imageio
imageio.imread("xxxx.png")

Solution 2

If the higher version is discarded, we can reduce the SciPy version!

Reduce the SciPy version to 1.2.1

pip install scipy==1.2.1

Web: xssfworkbook error NoClassDefFoundError [How to Solve]

I. background introduction

The Java Web environment needs to read the data in the excel table and insert it into the database. The xssfworkbook class needs to be used to read the table file. The key codes are as follows:

  //read excel
    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }

        } catch (FileNotFoundException e) {
            LOGGER.error(e.toString());
        } catch (IOException e) {
            LOGGER.error(e.toString());
        } 
        return wb;
    }

II. Occurrence of problems

Running locally, such as writing a main method or running with @ test, can run normally, but on the web, the interruption point finds that this class cannot be found
so it tries to upgrade the dependency package

or not. Unable to solve it, he fell into deep thinking. It’s really hard to deal with environmental problems and dependency problems
tried the recommended dependencies and versions given by other authors, but still failed:
First:

Second:

Three problem solving

Bypass the problem. If the mountain doesn’t come, I’ll go
change the file format: that is, xlsx is XLS, and finally return to the hssfworkbook class for reading.

PATH = "/Users/xxx/work/B/A_info.xlsx";

by

PATH = "/Users/xxx/work/B/A_info.xls";

So you can access it in the web layer
(PS: it should be noted that if you directly change the. Xlsx format file to. XLS, you need to open the file first and click Save as. XLS format. You can’t be lazy here. The author has also stepped on this pit)