Tag Archives: python

The python script tool of ArcGIS reports an error: indentationerror: unexpected indent solution

Background

At the beginning, I wrote an ArcGIS Python script, which is an independent script. I ran it in Python and ran it successfully. But if you put this script in the ArcGIS toolbox, it won’t work properly. The following errors are reported.

IndentationError: unexpected indent。

  The above figure is an article from Baidu experience. Because there was no screenshot at that time, I didn’t bother to reproduce this problem again…

Find solutions

Code indentation problem

When searching for this error report on Baidu, most of the answers are to ask you to find the indentation problem and space problem in the code. As in the article from the above figure.

The problem is that my code can run successfully in pycharm, and I checked the code several times and found no problem…

Chinese in code (including Chinese in notes)

I use ArcGIS 10.2 and python version is 2.7. This version of Python doesn’t support Chinese very much, but generally you can run normally by adding # coding = UTF-8 at the beginning of the code in the python environment.

# coding=utf-8

There is a Chinese comment on the last line of the wrong line of my code. So I tried to remove that line of Chinese notes and succeeded

Summary

1. If the python script of ArcGIS does not need Chinese, do not use Chinese

2. If you have to use Chinese, you can consider adding # coding: cp936 at the beginning of the script code

 

Error when Python executes JavaScript statement

‘gbk’ codec can’t encode character ‘\u20ac’ in position 62114: illegal multibyte sequence
find this line in the JS files:

e = "a€|",

It should be this symbol that reports an error. How to solve it

with open('./encryp_js/eventid_encryp.js', 'r', encoding='utf-8') as f:
    content = f.read()
jsdata = execjs.compile(content)

numpy.concatenate() 253rd; 38169Keyerror: 0 [How to Solve]

numpy.concatenate()

Official Documentation Link
Function Description.
Join a sequence of arrays along an existing axis.
Join a sequence of arrays along an existing axis.

Program error

KeyError Traceback (most recent call last)
F:\Anacondaaa\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3079 try:
-> 3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 0
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
in
—-> 1 np.unique(np.concatenate(movie_type[‘类型’].map(lambda x: x.split(’/’))))
<array_function internals> in concatenate(*args, **kwargs)
F:\Anacondaaa\lib\site-packages\pandas\core\series.py in getitem(self, key)
851
852 elif key_is_scalar:
–> 853 return self._get_value(key)
854
855 if is_hashable(key):
F:\Anacondaaa\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
959
960 # Similar to Index.get_value, but we do not fall back to positional
–> 961 loc = self.index.get_loc(label)
962 return self.index._get_values_for_loc(self, loc, label)
963
F:\Anacondaaa\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
-> 3082 raise KeyError(key) from err
3083
3084 if tolerance is not None:
KeyError: 0


Reasons and Suggestions
keyerror means no data, because np.concatenate itself is connected with the original index, and it doesn’t work because the original index is no longer continuous in the data cleaning process.
Reset the contiguous indexes or use other methods to join the list to achieve this effect.

Gensim Error: AttributeError: The vocab attribute was removed from KeyedVector in Gensim 4.0.0.

gensim error: AttributeError: The vocab attribute was removed from KeyedVector in Gensim 4.0.0.
Use KeyedVector’s .key_to_index dict, .index_to_key list, and methods .get_vecattr(key, attr) and .set_vecattr(key, attr, new_val) instead.
Solution:
1. directly modify the code
Find all the modules of vocab.keys() and modify them if they are mods defined by gensim.

Show:

## Wrong
model = KeyedVectors.load_word2vec_format(word2vec_glove_file)
words = np.random.choice(list(model.vocab.keys()), sample)

## Right
model = KeyedVectors.load_word2vec_format(word2vec_glove_file)
words = np.random.choice(list(model.key_to_index.keys()), sample)

Method 2: install the original version

!pip install gensim==3.0

[Solved] Simple jwt Error: AttributeError: type object ‘BlacklistedToken‘ has no attribute ‘objects

Solution: add in Django setting

'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

For example:

SIMPLE_JWT = {

     'ACCESS_TOKEN_LIFETIME': datetime.timedelta(days=7),
    'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

}

[Solved] Request.url is not modifiable, use Request.replace() instead

Encountered in a scene_ In the redis project, the URL needs to be filtered and de duplicated, so a de duplication class is customized

Simply copy the source code directly, and then rewrite the request_ See, to change the logic, the original direct assignment will report the error of the title

    def request_seen(self, request):
        temp_request = request
        if "ref" in temp_request.url:
            # An error is reported here, you cannot assign a value directly
            temp_request.url = temp_request.url.split("ref")[0]
        fp = self.request_fingerprint(temp_request)
        added = self.server.sadd(self.key, fp)
        return added == 0

Solution:

Use _set_URL (URL) is OK

temp_request._set_url(temp_request.url.split("ref")[0])

The complete code is as follows:

from scrapy.dupefilters import BaseDupeFilter
from scrapy.utils.request import request_fingerprint
from scrapy_redis import get_redis_from_settings
from scrapy_redis import defaults
import logging
import time

logger = logging.getLogger(__name__)


class UrlFilter(BaseDupeFilter):
    logger = logger

    def __init__(self, server, key, debug=False):
        self.server = server
        self.key = key
        self.debug = debug
        self.logdupes = True

    @classmethod
    def from_settings(cls, settings):
        server = get_redis_from_settings(settings)
        # XXX: This creates one-time key. needed to support to use this
        # class as standalone dupefilter with scrapy's default scheduler
        # if scrapy passes spider on open() method this wouldn't be needed
        # TODO: Use SCRAPY_JOB env as default and fallback to timestamp.
        key = defaults.DUPEFILTER_KEY % {'timestamp': int(time.time())}
        debug = settings.getbool('DUPEFILTER_DEBUG')
        return cls(server, key=key, debug=debug)

    @classmethod
    def from_crawler(cls, crawler):
        """Returns instance from crawler.

        Parameters
        ----------
        crawler : scrapy.crawler.Crawler

        Returns
        -------
        RFPDupeFilter
            Instance of RFPDupeFilter.

        """
        return cls.from_settings(crawler.settings)

    def request_seen(self, request):
        temp_request = request
        if "ref" in temp_request.url:
            temp_request._set_url(temp_request.url.split("ref")[0])
        fp = self.request_fingerprint(temp_request)
        added = self.server.sadd(self.key, fp)
        return added == 0

    def request_fingerprint(self, request):
        """Returns a fingerprint for a given request.

        Parameters
        ----------
        request : scrapy.http.Request

        Returns
        -------
        str

        """
        return request_fingerprint(request)

    @classmethod
    def from_spider(cls, spider):
        settings = spider.settings
        server = get_redis_from_settings(settings)
        dupefilter_key = settings.get("SCHEDULER_DUPEFILTER_KEY", defaults.SCHEDULER_DUPEFILTER_KEY)
        key = dupefilter_key % {'spider': spider.name}
        debug = settings.getbool('DUPEFILTER_DEBUG')
        return cls(server, key=key, debug=debug)

    def close(self, reason=''):
        """Delete data on close. Called by Scrapy's scheduler.

        Parameters
        ----------
        reason : str, optional

        """
        self.clear()

    def clear(self):
        """Clears fingerprints data."""
        self.server.delete(self.key)

    def log(self, request, spider):
        """Logs given request.

        Parameters
        ----------
        request : scrapy.http.Request
        spider : scrapy.spiders.Spider

        """
        if self.debug:
            msg = "Filtered duplicate request: %(request)s"
            self.logger.debug(msg, {'request': request}, extra={'spider': spider})
        elif self.logdupes:
            msg = ("Filtered duplicate request %(request)s"
                   " - no more duplicates will be shown"
                   " (see DUPEFILTER_DEBUG to show all duplicates)")
            self.logger.debug(msg, {'request': request}, extra={'spider': spider})
            self.logdupes = False

Brew Install python Error: tar: Error opening archive: Failed to open’***‘

Check the reason for the error. At first, I thought it was a permission problem and didn’t write it. After modifying the permission, I found that it still couldn’t be installed.

Check carefully and find that gdbm dependency is not installed.

terms of settlement

To install gdbm dependencies, enter the command line

brew install gdbm

The following indicates that the installation is successful

Finally, execute the command brew install again [email protected]

Installation succeeded!

[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”.