PyRPlidar IndexError: index out of range - python

Running the example code in the pyrplidar documentation
from pyrplidar import PyRPlidar
lidar = PyRPlidar()
lidar.connect(port="COM8", baudrate=256000, timeout=3)
# Linux : "/dev/ttyUSB0"
# MacOS : "/dev/cu.SLAB_USBtoUART"
# Windows : "COM5"
info = lidar.get_info()
print("info :", info)
health = lidar.get_health()
print("health :", health)
samplerate = lidar.get_samplerate()
print("samplerate :", samplerate)
scan_modes = lidar.get_scan_modes()
print("scan modes :")
for scan_mode in scan_modes:
print(scan_mode)
lidar.disconnect()
give this error message
Traceback (most recent call last):
File "C:\Users\ADMIN\Desktop\RPlidar\test1.py", line 10, in <module>
info = lidar.get_info()
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\lib\site-packages\pyrplidar.py", line 73, in get_info
discriptor = self.receive_discriptor()
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\lib\site-packages\pyrplidar.py", line 42, in receive_discriptor
discriptor = PyRPlidarResponse(self.lidar_serial.receive_data(RPLIDAR_DESCRIPTOR_LEN))
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\lib\site-packages\pyrplidar_protocol.py", line 110, in __init__
self.sync_byte1 = raw_bytes[0]
IndexError: index out of range
How do I solve this? Please help

Related

IndexError: list index out of range-QGIS

I Try to make plugin in qgis and I have a problem. Below is my code:
destination_layer = QgsProject.instance().mapLayersByName('Destination')[0]
matrix = QgsProject.instance().mapLayersByName('join')[0]
for f in matrix.getFeatures():
origin_expr = QgsExpression('Site Name={}'.format(f['Site Name']))
destination_expr = QgsExpression('Site Name={}'.format(f['Site Name_2']))
origin_feature = origin_layer.getFeatures(QgsFeatureRequest(origin_expr))
origin_coords = [(f.geometry().asPoint().x(), f.geometry().asPoint().y())
for f in origin_feature]
destination_feature = destination_layer.getFeatures(QgsFeatureRequest(destination_expr))
destination_coords = [(f.geometry().asPoint().x(), f.geometry().asPoint().y())
for f in destination_feature]
params = {
'INPUT':'NCR Road',
'START_POINT':'{},{}'.format(origin_coords[0][0], origin_coords[0][1]),
'END_POINT':'{},{}'.format(destination_coords[0][0], destination_coords[0][1]),
'STRATEGY':0,
'ENTRY_COST_CALCULATION_METHOD':0,
'DIRECTION_FIELD':'',
'VALUE_FORWARD':'',
'VALUE_BACKWARD':'',
'VALUE_BOTH':'',
'DEFAULT_DIRECTION':2,
'SPEED_FIELD':'',
'DEFAULT_SPEED':50,
'TOLERANCE':0,
'OUTPUT': 'Shortest Path Layer' }
print('Executing analysis')
processing.runAndLoadResults("qneat3:shortestpathpointtopoint", params)
Then when I run my code, it show this error:
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 16, in <module>
IndexError: list index out of range
Why it is not working in plugin?
We need more information like which code is on line 90? Anyway I would double check and making sure your index is doing correct things
'START_POINT':'{},{}'.format(origin_coords[0][0], origin_coords[0][1]),
'END_POINT':'{},{}'.format(destination_coords[0][0], destination_coords[0][1]),
And
destination_layer = QgsProject.instance().mapLayersByName('Destination')[0]
matrix = QgsProject.instance().mapLayersByName('join')[0]

IndexError: list index out of range when read LUNA16

When I tried to read the luna dataset,there's the error:
Traceback (most recent call last):
File "run_preprocess.py", line 57, in <module>
save_preprocessed_data()
File "run_preprocess.py", line 48, in save_preprocessed_data
ct = CTScan(seriesuid=series_id, centers=tp_co, radii=radii, clazz=0)
File "C:\Luna16-master\prepare\_classes.py", line 14, in __init__
path = glob(f'''{RESOURCES_PATH} /*/{seriesuid}.mhd''')[0]
IndexError: list index out of range
How to solve it?
Thanks in advance.
The code is:
class CTScan(object):
def __init__(self, seriesuid, centers, radii, clazz):
self._seriesuid = seriesuid
self._centers = centers
path = glob(f'''{RESOURCES_PATH} /*/{seriesuid}.mhd''')[0]
# path = paths[0]
self._ds = sitk.ReadImage(path)
self._spacing = np.array(list(reversed(self._ds.GetSpacing())))
self._origin = np.array(list(reversed(self._ds.GetOrigin())))
self._image = sitk.GetArrayFromImage(self._ds)
self._radii = radii
self._clazz = clazz
self._mask = None

How to Solve WriteFile Error when using PyFirmata

I am using pyFirmata to move servo motors for my project. When ever i run my project, it runs two times and the following errors come out. The code and the result is given below.
from pyfirmata2 import Arduino, SERVO
import time
board = Arduino('COM3')
servo = board.get_pin('d:9:s')
board.digital[9].mode = SERVO
# def rotateServo(pin, angle):
# board.digital[9].write(angle)
# time.sleep(0.1)
current_angle = servo.read()
while True:
# for i in range (0,180):
# rotateServo(9, i)
print(current_angle)
if current_angle != 0 or current_angle == 0:
servo.write(0)
print("0")
time.sleep(2)
servo.read()
servo.write(90)
print("90")
time.sleep(2)
errors:
*C:\Python_Virtualenv\Scripts\python.exe "E:/Python Projects/servo.py"
0
0
90
0
Traceback (most recent call last):
File "E:\Python Projects\servo.py", line 18, in <module>
servo.write(0)
File "C:\Users\n1v3d\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfirmata2\pyfirmata2.py", line 608, in write
self.board.sp.write(msg)
File "C:\Users\n1v3d\AppData\Local\Programs\Python\Python39\lib\site-packages\serial\serialwin32.py", line 317, in write
raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))
serial.serialutil.SerialException: WriteFile failed (PermissionError(13, 'The device does not recognize the command.', None, 22))
Exception ignored in: <function Board.__del__ at 0x000001F25EB3D040>
Traceback (most recent call last):
File "C:\Users\n1v3d\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfirmata2\pyfirmata2.py", line 148, in __del__
File "C:\Users\n1v3d\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfirmata2\pyfirmata2.py", line 385, in exit
File "C:\Users\n1v3d\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfirmata2\pyfirmata2.py", line 528, in _set_mode
File "C:\Users\n1v3d\AppData\Local\Programs\Python\Python39\lib\site-packages\serial\serialwin32.py", line 317, in write
serial.serialutil.SerialException: WriteFile failed (PermissionError(13, 'The device does not recognize the command.', None, 22))
Process finished with exit code 1*
Please tell me how to fix this error!

bbox works when inputting exact coordinates within module but fails with variable containing identical data

I'm having an issue trying to make a screen grab of an area defined by lines in a config file:
The following code:
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1,coordstore.y1,coordstore.x2,coordstore.y2 = (line[4]).strip(),(line[5]).strip(),(line[6]).strip(),(line[7]).strip() # note: confusing. 0=line 1, 1=line2 etc.
coordstore.coords = coordstore.x1+',',coordstore.y1+',',coordstore.x2+',',coordstore.y2
coordstore.stripped = ' '.join((coordstore.coords))
print(coordstore.stripped)
return(coordstore.stripped)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
prints exactly this value: 10, 20, 100, 300
it then fails with this Traceback:
Traceback (most recent call last):
File "file location", line 82, in <module>
screenshot()
File "file location", line 80, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 38, in _grab
x1, y1, x2, y2 = bbox
ValueError: too many values to unpack (expected 4)
If I manually replace (bbox=(coordstore.stripped)) with (bbox=(10, 20, 100, 300)) which is literally identical to what the variable prints, the code works perfectly but is not useful for my needs. What am I not seeing? Thanks for the help!
UPDATE:
I have tried another approach.
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1 = (line[4]).strip()
coordstore.y1 = (line[5]).strip()
coordstore.x2 = (line[6]).strip()
coordstore.y2 = (line[7]).strip()
print(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2)
return(coordstore.x1, coordstore.y1, coordstore.x2, coordstore.y2)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
This prints
10, 20, 100, 300
but returns the following Traceback errors:
Traceback (most recent call last):
File "module location", line 84, in <module>
screenshot()
File "module location", line 82, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 42, in _grab
raise ValueError('bbox y2<=y1')
ValueError: bbox y2<=y1
As you have mentioned in comments the value of coordstore.stripped is string. And expected argument by ImageGrab2.grab is type of tuple so, first you have to convert it into tuple.
Update the method like this:
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=tuple(map(int, coordstore.stripped.split(', ')))) # X1,Y1,X2,Y2
im.save('tc.png')

Handling exceptions in while loop - Python

Here is my code (almost full version for #cdhowie :)):
def getResult(method, argument=None):
result = None
while True:
print('### loop')
try:
print ('### try hard...')
if argument:
result = method(argument)
else:
result = method()
break
except Exception as e:
print('### GithubException')
if 403 == e.status:
print('Warning: ' + str(e.data))
print('I will try again after 10 minutes...')
else:
raise e
return result
def getUsernames(locations, gh):
usernames = set()
for location in locations:
print location
result = getResult(gh.legacy_search_users, location)
for user in result:
usernames.add(user.login)
print user.login,
return usernames
# "main.py"
gh = Github()
locations = ['Washington', 'Berlin']
# "main.py", line 12 is bellow
usernames = getUsernames(locations, gh)
The problem is, that exception is raised, but I can't handle it. Here is an output:
### loop
### try hard...
Traceback (most recent call last):
File "main.py", line 12, in <module>
usernames = getUsernames(locations, gh)
File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames
for user in result:
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__
newElements = self.__grow()
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 45, in __grow
newElements = self._fetchNextPage()
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 37, in _fetchNextPage
return self.get_page(page)
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 48, in get_page
None
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Requester.py", line 69, in requestAndCheck
raise GithubException.GithubException(status, output)
github.GithubException.GithubException: 403 {u'message': u'API Rate Limit Exceeded for 11.11.11.11'}
Why it doesn't print ### handling exception?
Take a close look at the stack trace in the exception:
Traceback (most recent call last):
File "main.py", line 12, in <module>
usernames = getUsernames(locations, gh)
File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames
for user in result:
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__
newElements = self.__grow()
...
The exception is being thrown from code being called by the line for user in result: after getResult finishes executing. This means that the API you're using is using lazy evaluation, so the actual API request doesn't quite happen when you expect it to.
In order to catch and handle this exception, you'll need to wrap the code inside the getUsernames function with a try/except handler.

Categories

Resources