.py
a = (0,0,70)
b = (90,0,45)
c = ("1 2","0 2","0 1")
d = 0
e = 1
class Travel(object):
def trip(self,latitude,longitude,canTravel,origin,destination):
self.latitude = latitude
self.longitude = longitude
self.canTravel = canTravel
self.origin = origin
self.destination = destination
print(latitude)
print(longitude)
print(origin)
print(destination)
print(canTravel)
for c in canTravel:
print(c)
pass
c = Travel()
c.trip(a,b,c,d,e)
output
(0, 0, 70)
(90, 0, 45)
0
1
<__main__.Travel object at 0x000000E836D25898>
Traceback (most recent call last):
File ".\shortestpath.py", line 26, in <module>
c.trip(a,b,c,d,e)
File ".\shortestpath.py", line 20, in trip
for c in canTravel:
TypeError: 'Travel' object is not iterable
I want to pass the tuple of string ("1 2","0 2","0 1") to the trip function, and want to iterate over it.
How do I iterate over the <main.Travel object at 0x000000E836D25898>
Related
i am working with ros about 3 month! I work on a robot controller.
i got error in ui about this client:
import sys
import rospy
from database_helper.srv import get_moves, get_movesRequest, get_movesResponse, get_move
def get_data(name: str):
"""This function can extract model names from DB"""
try:
rospy.init_node("get_moves_client")
except:
pass
rospy.wait_for_service('get_moves')
try:
moves = rospy.ServiceProxy('get_moves', get_moves)
except rospy.ServiceException as e:
print(31)
print(e)
return
id = 0
try:
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
except:
print(43)
return
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
try:
for i in range(len(wps)):
print(i)
data = {}
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
except rospy.ServiceException:
pass
print(list_of_data)
return list_of_data
this client can get data from DB and save with dict and save all dict in a list.
i most write "try/except" and i see 43 number! so i know my except is in for i in range(len(wps)):
the amazing point is, i can run this script and i get answer, but if call this script in my ui, after i using save waypoint and i try to load waypoint, i get ServiceException!
my "add_move.py" code:
from typing import List, Dict
import rospy
from database_helper.srv import add_move
from database_helper.msg import move, waypoint
def _add_move(name: str, wp: List[Dict]):
"""This Function can for send insert query for DB"""
rospy.init_node('add_move_client', anonymous=True)
rospy.wait_for_service('add_move')
_move = move()
_move.name = name
for i in range(len(wp)):
_waypoint = waypoint()
_waypoint.x = wp[i]['x_traj']
_waypoint.y = wp[i]['y_traj']
_waypoint.z = wp[i]['z_traj']
_waypoint.displacement_time_to_next_waypoint = wp[i]['time_tarj']
_waypoint.pitch = wp[i]['pich_traj']
_waypoint.roll = wp[i]['roul_traj']
_waypoint.yaw = wp[i]['ya_traj']
_waypoint.camera_focus = wp[i]['focus_camer']
_waypoint.camera_iris = wp[i]['iris_camera']
_waypoint.camera_zoom = wp[i]['zoom_camera']
_waypoint.rail_speed = wp[i]['speed_rail']
_waypoint.rail_displacement = wp[i]['disp_or_time_rail']
_waypoint.rail_direction = wp[i]['direction_rail']
_move.waypoints.append(_waypoint)
add = rospy.ServiceProxy('add_move', add_move)
return add(_move).id
if __name__ == "__main__":
from random import randint
data = {'x_traj': 12, 'y_traj': 12, 'z_traj': 33, 'time_tarj': 11,
'pich_traj': 13, 'roul_traj': 43, 'ya_traj': 21,
'focus_camer': 11, 'iris_camera': 55, 'zoom_camera': 32,
'disp_or_time_rail': 21, 'speed_rail': 109, 'direction_rail':44,
'joint1_slider': 12, 'joint2_slider': 666, 'joint3_slider': 567,
'joint4_slider': 32, 'joint5_slider': 79, 'joint6_spin': 100
}
wp = []
wp.append(data)
print(_add_move("t1", wp))
my error in terminal without "try/except" is:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 223, in deserialize_messages
msg_queue.append(data.deserialize(q))
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/srv/_get_moves.py", line 247, in deserialize
val2 = database_helper.msg.waypoint()
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/msg/_waypoint.py", line 95, in __init__
self.rail_displacement = 0
AttributeError: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 735, in receive_once
p.read_messages(b, msg_queue, sock)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 361, in read_messages
rospy.msg.deserialize_messages(b, msg_queue, self.recv_data_class, queue_size=self.queue_size, max_msgs=1, start=1) #rospy.msg
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 245, in deserialize_messages
raise genpy.DeserializationError("cannot deserialize: %s"%str(e))
genpy.message.DeserializationError: cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 522, in call
responses = transport.receive_once()
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 751, in receive_once
raise TransportException("receive_once[%s]: DeserializationError %s"%(self.name, str(e)))
rospy.exceptions.TransportException: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./benchmark_new_version_4_1.py", line 730, in get_data_query
self.wp_saver = get_data(response)
File "/home/ajax/Documents/iotive/src/gui/ui/scripts/get_moves_clinet.py", line 36, in get_data
for i in (moves(True).moves):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 442, in __call__
return self.call(*args, **kwds)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 532, in call
raise ServiceException("transport error completing service call: %s"%(str(e)))
rospy.service.ServiceException: transport error completing service call: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
what is my wrong?
srv/get_move:
int32 id
---
waypoint[] waypoints
srv/get_moves:
bool add_waypoints
---
move[] moves
msg/move:
int32 id
string name
waypoint[] waypoints
msg/waypoint:
int32 id
int32 order
float64 x
float64 y
float64 z
float64 roll
float64 pitch
float64 yaw
int32 camera_focus
int32 camera_iris
int32 camera_zoom
int32 rail_displacement
int32 rail_time
int32 rail_speed
bool rail_direction
int32 displacement_time_to_next_waypoint
So we need to remove service variables when we do not have anything else.
like this:
rospy.wait_for_service('get_moves')
moves = rospy.ServiceProxy('get_moves', get_moves)
id = 0
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
for i in range(len(wps)):
print(i)
data = {}
data['order_traj'] = wps[i].order
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
del move
del moves
print(list_of_data)
return list_of_data
I discovered this last night!
I found this thread how to make a variable change from the text "1m" into "1000000" in python
My string values are in a column within a pandas dataframe. The string/0bkects values are like 18M, 345K, 12.9K, 0, etc.
values = df5['Values']
multipliers = { 'k': 1e3,
'm': 1e6,
'b': 1e9,
}
pattern = r'([0-9.]+)([bkm])'
for number, suffix in re.findall(pattern, values):
number = float(number)
print(number * multipliers[suffix])
Running the code gives this error:
Traceback (most recent call last):
File "c:/Users/thebu/Documents/Python Projects/trading/screen.py", line 19, in <module>
for number, suffix in re.findall(pattern, values):
File "C:\Users\thebu\Anaconda3\envs\trading\lib\re.py", line 223, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
Thanks
Here's another way using regex:
import re
def get_word(s):
# find word
r = re.findall(r'[a-z]', s)
# find numbers
w = re.findall(r'[0-9]', s)
if len(r) > 0 and len(w) > 0:
r = r[0]
v = multipliers.get(r, None)
if v:
w = int(''.join(w))
w *= v
return round(w)
df['col2'] = df['col'].apply(get_word)
print(df)
col col2
0 10k 10000
1 20m 20000000
Sample Data
df = pd.DataFrame({'col': ['10k', '20m']})
l = {}
name = [(str, input().split()) for i in range(0, 15)]
dob = [(int, input().split()) for i in range(0, 15)]
print({name[i]:dob[i] for i in range(len(dob))})
I want to print 15 items in a dictionary format of name as key and dateofbirth(dob) as value.What wrong I am doing?
.....................................................................................
the error is:
Traceback (most recent call last):
File "main.py", line 4, in <module>
print({name[i]:dob[i] for i in range(len(dob))})
File "main.py", line 4, in <dictcomp>
print({name[i]:dob[i] for i in range(len(dob))})
TypeError: unhashable type: 'list'
The issue is not in the print() function but in the way you make up the first list: instead of pulling out the names, it gives you a (<class 'str'>, 'string') tuple that cannot be used as a key for a dictionary. The same happens with the 'dob' variable, but the issue is only with keys.
Try doing:
name = [input() for i in range(0, 15)] #this takes and returns the input. no need to convert to string
dob = [int(input()) for i in range(0, 15)] #this takes an input and returns it's numeric value
I would do it like this (this returns a generator):
name = map(str, input().split())
dob = map(int, input().split())
print({n: d for n, d in zip(name, dob)})
If you want it to return a list instead:
name = list(map(str, input().split()))
dob = list(map(int, input().split()))
print({n: d for n, d in zip(name, dob)})
When I run the code below, it begins to loop through and returns the time and length of temp_data, but before reaching 100 in the loop throws the error. If I update the code to sleep for 5 seconds instead of 1, it will make it through all 100 iterations.
start_date = 1483228800*1000 #jan 1 2017
pair = 'ETHBTC'
timeframe = '1m'
final_data = []
for _ in range(0,100):
url = 'https://api.bitfinex.com/v2/candles/trade:'+timeframe+':t'+pair+'/hist?sort=1&limit=1000&start='+str(start_date)
r = requests.get(url)
temp_data = r.json()
final_data = final_data+temp_data
start_date = temp_data[len(temp_data)-1][0]+60*1000
print(time.ctime(), len(temp_data))
time.sleep(1)
print(len(final_data))
Error:
Traceback (most recent call last):
File
"/Users/michael/PycharmProjects/bot/venv/datasets/dataset.py", line
18, in <module>
start_date = temp_data[len(temp_data)-1][0]+60*1000
TypeError: can only concatenate str (not "int") to str
you should convert 60*1000 to str.
start_date = temp_data[len(temp_data)-1][0] + str(60*1000)
I want to perform column subtraction. for example [[0,2],[2,5],[3,11]] for this I want to perform (5-2),(11-5). then find which has the maximum difference.so for that I created a dictionary and store the differences along with its pair. for example difference of (5-2) is stored with 0, and difference of (11-5) is stored with 2.
error is :
Traceback (most recent call last): File
"/home/viki/Music/keypress.py", line 14, in
keypressTime(l) File "/home/viki/Music/keypress.py", line 10, in keypressTime
d = x[i+1][1] - x[i][1] IndexError: list index out of range
import operator
l = [[0,2],[2.4],[0,8],[3,9],[5,20]]
def keypressTime(x):
dic = {}
d = 0
for i in range(len(x)-1):
if i <(len(x)-1):
d = x[i+1][1] - x[i][1]
dic["i"] = d
return max(dict.items(),key=operator.itemgetter(1))[0]
keypressTime(l)
There is a typo in the variable declaration of l.
l = [[0,2],[2.4],[0,8],[3,9],[5,20]] -> change 2.4 to 2,4
And dict.items() should probably be dic.items()