ROS2, TypeError when publishing custom message to Topic (python) - python

I have defined a custom message: uint8[] data
The custom message is imported in my Node class with no problems: from my_shared.msg import MyMessage
In the same Node, I create the publisher with: self.my_publisher = self.create_publisher(MyMessage, 'topic_in', 200)
and I publish the message with: self.my_publisher.publish(my_msg)
my_msg is built in the following way:
payload_bitstream = np.fromstring(my_data, np.uint8)
my_msg = payload_bitstream.tolist()
Sadly, I get a TypeError: File "/opt/ros/eloquent/lib/python3.6/site-packages/rclpy/publisher.py", line 68, in publish raise TypeError() TypeError
Could you help out with this if you know what I am doing wrong pls?
Thanks in advance, G.

The issue is in your assignment of my_msg, which is an instance of the class MyMessage containing attributes defined in the my_shared.msg file, namely my_msg.data which has type of uint8[]. It's correct that you did payload_bitstream.tolist() to get a list of native python ints with uint8 values, but you need to assign it to the data attribute. TL;DR:
my_msg.data = payload_bitstream.tolist()

Related

ValueError: [TypeError("'_cffi_backend.FFI' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')] in FastAPI

I am working with FastAPI and Firestore and I created a very basic endpoint to read all the documents in a collection. However, I get the following error when I run my code and I can't seem to figure out where it's coming from.
ValueError: [TypeError("'_cffi_backend.FFI' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
The code that I have used is below:
#router.get("/reviews/{review_id}")
def read_review(review_id: str):
# Get all documents in the Reviews collection
db = firestore.client()
reviews_ref = db.collection('Reviews')
docs = reviews_ref.stream()
output = {}
for doc in docs:
output[doc.id] = doc.to_dict()
return output
I am not sure why this error is being generated and I couldn't find anything related to the FastAPI for this error.

Cannot (always) fetch an attribute in an object even though it exists

I'm currently developing locally an Azure function that communicates with Microsoft Sentinel, in order to fetch the alert rules from it, and more specifically their respective querys :
credentials = AzureCliCredential()
alert_rules_operations = SecurityInsights(credentials, SUBSCRIPTION_ID).alert_rules
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv('RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
The issue is that when I'm looping over list_alert_rules, and try to see each rule's query, I get an error:
Exception: AttributeError: 'FusionAlertRule' object has no attribute 'query'.
Yet, when I check their type via the type() function:
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv(
'RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
for rule in list_alert_rules:
print(type(rule))
##console: <class 'azure.mgmt.securityinsight.models._models_py3.ScheduledAlertRule'>
The weirder issue is that this error appears only when you don't print the attribute. Let me show you:
Print:
for rule in list_alert_rules:
query = rule.query
print('query', query)
##console: query YAY I GET WHAT I WANT
No print:
for rule in list_alert_rules:
query = rule.query
...
##console: Exception: AttributeError: 'FusionAlertRule' object has no attribute 'query'.
I posted the issue on the GitHub repo, but I'm not sure whether it's a package bug or a runtime issue. Has anyone ran into this kind of problems?
BTW I'm running Python 3.10.8
TIA!
EDIT:
I've tried using a map function, same issue:
def format_list(rule):
query = rule.query
# print('query', query)
# query = query.split('\n')
# query = list(filter(lambda line: "//" not in line, query))
# query = '\n'.join(query)
return rule
def main(mytimer: func.TimerRequest) -> None:
# results = fetch_missing_data()
credentials = AzureCliCredential()
alert_rules_operations = SecurityInsights(
credentials, SUBSCRIPTION_ID).alert_rules
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv(
'RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
list_alert_rules = list(map(format_list, list_alert_rules))
I have tried with same as you used After I changed like below; I get the valid response.
# Management Plane - Alert Rules
alertRules = mgmt_client.alert_rules.list_by_resource_group('<ResourceGroup>')
for rule in alertRules:
# Try this
test.query = rule.query //Get the result
#print(rule)
if mytimer.past_due:
logging.info('The timer is past due!')
Instead of this
for rule in list_alert_rules:
query = rule.query
Try below
for rule in list_alert_rules:
# Try this
test.query = rule.query
Sorry for the late answer as I've been under tons of work these last few days.
Python has an excellent method called hasattr that checks if the object contains a specific key.
I've used it in the following way:
for rule in rules:
if hasattr(rule, 'query'):
...
The reason behind using this is because the method returns object of different classes, however inherited from the one same mother class.
Hope this helps.

Create activities for an user with Stream-Framework

I'm trying to setup stream-framework the one here not the newer getstream. I've setup the Redis server and the environment properly, the issue I'm facing is in creating the activities for a user.
I've been trying to create activities, following the documentation to add an activity but it gives me an error message as follows:
...
File "/Users/.../stream_framework/activity.py", line 110, in serialization_id
if self.object_id >= 10 ** 10 or self.verb.id >= 10 ** 3:
AttributeError: 'int' object has no attribute 'id'
Here is the code
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
feed = UserPinFeed(13)
print(feed)
activity = Activity(
actor=13, # Thierry's user id
verb=1, # The id associated with the Pin verb
object=1, # The id of the newly created Pin object
)
feed.add(activity) # Error at this line
I think there is something missing in the documentation or maybe I'm doing something wrong. I'll be very grateful if anyone helps me get the stream framework working properly.
The documentation is inconsistent. The verb you pass to the activity should be (an instance of?*) a subclass of stream_framework.verbs.base.Verb. Check out this documentation page on custom verbs and the tests for this class.
The following should fix the error you posted:
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
from stream_framework.verbs import register
from stream_framework.verbs.base import Verb
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
class Pin(Verb):
id = 5
infinitive = 'pin'
past_tense = 'pinned'
register(Pin)
feed = UserPinFeed(13)
activity = Activity(
actor=13,
verb=Pin,
object=1,
)
feed.add(activity)
I quickly looked over the code for Activity and it looks like passing ints for actor and object should work. However, it is possible that these parameters are also outdated in the documentation.
* The tests pass in classes as verb. However, the Verb base class has the methods serialize and __str__ that can only be meaningfully invoked if you have an object of this class. So I'm still unsure which is required here. It seems like in the current state, the framework never calls these methods, so classes still work, but I feel like the author originally intended to pass instances.
With the help of great answer by #He3lixxx, I was able to solve it partially. As the package is no more maintained, the package installs the latest Redis client for python which was creating too many issues so by installation redis-2.10.5 if using stream-framework-1.3.7, should fix the issue.
I would also like to add a complete guide to properly add activity to a user feed.
Key points:
If you are not using feed manager, then make sure to first insert the activity before you add it to the user with feed.insert_activity(activity) method.
In case of getting feeds with feed[:] throws an error something like below:
File "/Users/.../stream_framework/activity.py", line 44, in get_hydrated
activity = activities[int(self.serialization_id)]
KeyError: 16223026351730000000001005L
then you need to clear data for that user using the key format for it in my case the key is feed:user:13 for user 13, delete it with DEL feed:user:13, In case if that doesn't fix the issue then you can FLUSHALL which will delete everything from Redis.
Sample code:
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
from stream_framework.verbs import register
from stream_framework.verbs.base import Verb
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
class Pin(Verb):
id = 5
infinitive = 'pin'
past_tense = 'pinned'
register(Pin)
feed = UserPinFeed(13)
print(feed[:])
activity = Activity(
actor=13,
verb=Pin,
object=1)
feed.insert_activity(activity)
activity_id = feed.add(activity)
print(activity_id)
print(feed[:])

Error trying to use pyad to update user account

I'm trying to update a user attribute in Active Directory using pyad. This is my code
from pyad import *
pyad.set_defaults(ldap_server="server.domain.local",
username="admin", password="password")
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
and this is the error i recieve.
Traceback (most recent call last):
File "c:\Users\Administrator\Desktop\scripts\AD-Edit-user.py", line 12, in
<module>
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\pyad-0.5.20-py3.6.egg\pyad\adobject.py", line 318, in
update_attribute
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
AttributeError: 'str' object has no attribute 'get_attribute'
This makes me assume that I need to change the attribute type from str to something else. I have verified that mail is the correct attribute name.
I know ldap connection is working because i can create a user using a similar script.
Your problem is how you use pyad.
Specifically in this line:
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
if we look at the source of pyad.adobject.ADObject, we can see the following:
def update_attribute(self, attribute, newvalue, no_flush=False):
"""Updates any mutable LDAP attribute for the object. If you are adding or removing
values from a multi-valued attribute, see append_to_attribute and remove_from_attribute."""
if newvalue in ((),[],None,''):
return self.clear_attribute(attribute)
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
self._set_attribute(attribute, 2, pyadutils.generate_list(newvalue))
if not no_flush:
self._flush()
self here is not a parameter of the function, it is a reference to the class instance. Your call includes self='testuser1' which is str.
Please lookup the documentation on how to use this function / functionality / module, here. You will notice that there is no "self"... other than looking into the source code I am not sure how you got to the conclusion you needed self.
I have no way of testing the following, but this is roughly how it should work:
# first you create an instance of the object, based on
# the distinguished name of the user object which you
# want to change
my_ad_object = pyad.adobject.ADObject.from_dn('the_distinguished_name')
# then you call the update_attribute() method on the instance
my_ad_object.update_attribute(attribute='mail', newvalue='my#email.com')

Passing a variable to a JSON web service

I am accessing the class from the code api_service.py, which can be found here. When I call the first function, I have no problem, because no variables are passed:
from api_service import ApiService
import json
def main():
api_key = *removed*
access_token = *removed*
calling = ApiService(api_key,access_token)
survey_list = calling.get_survey_list()
But when I use the same type of routine as above to call a function from ApiService that requires a variable, I'm told that I should pass an object.
survey_details = calling.get_survey_details("1234")
survey_details = json.loads(json.dumps(survey_details))
print survey_details
The specific error message:
{u'status': 3, u'errmsg': u"Value '1234' for field '_data' is not of type object"}
Details for the get_survey_details aspect of the SurveyMonkey API are here, although I think a python-guru can solve this without knowing about the API.
This is a javascript/json object:
{field:'value'}
You have passed a string which, doesn't count as an "object" for these purposes.
Note that the error message is being generated by the service you are accessing. This question would be better directed to the creator of the service.

Categories

Resources