Drone's motion is not stable with rostopics...what can I do ?
import rospy
import time
#import library untuk mengirim command dan menerima data navigasi dari quadcopter
from geometry_msgs.msg import Twist
from std_msgs.msg import String
from std_msgs.msg import Empty
from ardrone_autonomy.msg import Navdata
#import class status untuk menentukan status ddari quadcopter
from drone_status import DroneStatus
COMMAND_PERIOD = 1000
class AutonomousFlight():
def __init__(self):
self.status = ""
rospy.init_node('forward', anonymous=False)
self.rate = rospy.Rate(10)
self.pubTakeoff = rospy.Publisher("ardrone/takeoff",Empty, queue_size=10)
self.pubLand = rospy.Publisher("ardrone/land",Empty, queue_size=10)
self.pubCommand = rospy.Publisher('cmd_vel',Twist, queue_size=10)
self.command = Twist()
#self.commandTimer = rospy.Timer(rospy.Duration(COMMAND_PERIOD/1000.0),self.SendCommand)
self.state_change_time = rospy.Time.now()
rospy.on_shutdown(self.SendLand)
def SendTakeOff(self):
self.pubTakeoff.publish(Empty())
self.rate.sleep()
def SendLand(self):
self.pubLand.publish(Empty())
def SetCommand(self, linear_x, linear_y, linear_z, angular_x, angular_y, angular_z):
self.command.linear.x = linear_x
self.command.linear.y = linear_y
self.command.linear.z = linear_z
self.command.angular.x = angular_x
self.command.angular.y = angular_y
self.command.angular.z = angular_z
self.pubCommand.publish(self.command)
self.rate.sleep()
if __name__ == '__main__':
try:
i = 0
uav = AutonomousFlight()
while not rospy.is_shutdown():
uav.SendTakeOff()
if i <= 30 :
uav.SetCommand(0,0,1,0,0,0)
i+=1
elif i<=60 :
uav.SetCommand(0,0,0,0,0,0)
i+=1
else:
uav.SendLand()
except rospy.ROSInterruptException:
pass
I need to just takeoff, go up and go to hover mode,
uav.SendTakeOff()
if i <= 30 :
uav.SetCommand(0,0,1,0,0,0)
i+=1
elif i<=60 :
uav.SetCommand(0,0,0,0,0,0)
after take off, this code makes the drone go to little back and some random motion and going up and going to hover mode. How can I fix this ?
Related
I use a Teledyne Dalsa line scan camera. Sometimes when I increase the line rate of my Teledyne Dalsa line scan camera to 13000 or higher and trigger it with an Arduino at 3V3, the images are not consistently captured from the buffer for every trigger, unlike when the line rate is 10000 or lower.
The trigger seems to be perfectly working in Sapera Software for increased line rate.
Attaching the code:
import platform
import os
import sys
import time
from harvesters.core import Harvester
import cv2
import numpy as np
h = Harvester()
gentl_file = r"C:\Program Files\MATRIX VISION\mvIMPACT Acquire\bin\x64\mvGenTLProducer.cti"
h.add_file(gentl_file)
h.update()
ia = h.create(0)
ia.remote_device.node_map.Width.value = 2048
ia.remote_device.node_map.Height.value = 2000
ia.remote_device.node_map.PixelFormat.value = 'RGB8'
ia.remote_device.node_map.AcquisitionLineRate.set_value(15000)
ia.remote_device.node_map.ExposureTime.set_value(47)
ia.remote_device.node_map.Gain.set_value(6)
ia.remote_device.node_map.TriggerSelector.value = "FrameBurstStart"
ia.remote_device.node_map.TriggerMode.value = "On"
ia.remote_device.node_map.triggerFrameCount.set_value(1) # new
ia.remote_device.node_map.TriggerSource.value = "Line2"
ia.remote_device.node_map.TriggerActivation.value = "RisingEdge"
ia.remote_device.node_map.TriggerDelay.set_value(0.0) # new
ia.remote_device.node_map.triggerDelaySource.value = "lineTriggerSignal" # new
ia.remote_device.node_map.LineSelector.value = "Line2"
ia.remote_device.node_map.LineFormat.value = "SingleEnded"
ia.remote_device.node_map.lineDetectionLevel.value = "Threshold_for_3V3"
ia.remote_device.node_map.LineInverter.value = False
ia.remote_device.node_map.lineDebouncingPeriod.value = 0
ia.remote_device.node_map.lineElectricalTermination.value = "Disabled"
ia.start()
start = time.time()
ia.start()
def image_capture():
global ia
print('Image capture started')
lst_app = []
with ia.fetch() as buffer:
component = buffer.payload.components[0]
_2d_new = component.data.reshape(component.height,component.width,int(component.num_components_per_pixel))
_2d_new = cv2.cvtColor(_2d_new , cv2.COLOR_RGB2BGR)
lst_app.append(_2d_new)
if len(lst_app) == 1:
print('Buffer is full')
arr = np.vstack(lst_app)
lst_app = []
return np.array(arr)
count = 0
while True:
image = image_capture()
print('captured', count)
count += 1
Thanks in Advance
Even after including all the parameters from the Sapera software, the image still doesn't get returned for certain triggers.
I have this code(A sample of a larger one).
import streamlit as st
from PIL import Image
import datetime as dt
from streamlit_option_menu import option_menu
img_16 = Image.open("PATH/81.png")
with st.container():
st.write("---")
left_column, middle_column, right_column = st.columns(3)
with left_column:
st.subheader(16)
st.image(img_16)
if st.button("Click me ⤵️",key=16):
st.write("""
Team: ABC\n
""" )
st.write("---")
condition_now = st.radio(label = "Have a live 🎤",options = ["ichi", "ni", "san"])
st.write('<style>div.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True)
if condition_now == "ichi":
st.write("ichi da!")
elif condition_now == "ni":
st.write("ni da!")
else:
st.write("san?")
After clicking the "click me" button
I want to choose one one the radio buttons, yet when I click on any radio button all will dissapear or get rest. How can I stop resetting?
The st.session_stat could be the key, but couldn't figure how.
adding st.button() to form is not supported, and st.button() has ephemeral
True states which are only valid for a single run.
Here you need to capture and save status of both button and Radio. Here is the code I tired and its not resetting radios
import streamlit as st
from PIL import Image
if 'bt_clkd' not in st.session_state:
st.session_state.bt_clkd = ''
if 'rd_clkd' not in st.session_state:
st.session_state.rd_clkd='film'
img_16 = Image.open("sampleImage.png")
with st.container():
st.write("---")
left_column, middle_column, right_column = st.columns([3,2,2],gap='small')
with left_column:
st.subheader(16)
st.image(img_16)
# n = st.session_state.bt
b = st.button("Click me ⤵️")
# b = st.button('ckick me',key='a')
if (b) or (st.session_state.bt_clkd== 'y'):
rd = st.radio('select choice',options=['film','surfing','reading'],key='rdkey',index=0,horizontal=True)
st.session_state.bt_clkd = 'y'
if (st.session_state.bt_clkd=='y') and (rd =='film'):
st.session_state.rd_clkd = 'film'
st.write('film!!')
elif (st.session_state.bt_clkd=='y') and (rd=='surfing'):
st.session_state.rd_clkd = 'surfing'
st.write('surfing!!')
else:
st.session_state.rd_clkd = 'reading'
st.write('reading!')
I'm currently working on a project to download a bunch of hentai using api requests. The code works, but whenever i found a bug, I always had to use the search function to see where variables or funktions i created are located in the code. Then I had the idea, to change the color of the funktions, so that if i wanted to look for the funktion Sample_funktion i would just have to look for the color red.
from time import sleep
from keyboard import is_pressed
import random
import win32clipboard
# SETTINGS
pyautogui.PAUSE = 0.5
reloadtime = 1
s2tv = 1
nothing = 1786, 327
filedownload = "720p.png"
# VARIABLES
captchas_destroyed = 0
fucked_by_captchas = 0
data = None
def get_URL():
global data
pyautogui.hotkey('ctrl', 'l')
pyautogui.hotkey('ctrl', 'c')
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
def p720_checker():
p720 = pyautogui.locateCenterOnScreen(filedownload, grayscale=True, confidence=0.95)
if p720 is not None:
pyautogui.click(p720)
def check4ads():
ads = pyautogui.locateCenterOnScreen('close_ad.png', grayscale=True, confidence=0.95)
if ads is not None:
pyautogui.click(ads)
def yellow_download():
yellow_download_kink = pyautogui.locateCenterOnScreen('getdownloadlinks.png', grayscale=True, confidence=0.9)
if yellow_download_kink is not None:
pyautogui.click(yellow_download_kink)
def cloud_download_checker():
download_cloud = pyautogui.locateCenterOnScreen("gray_cloud.png", grayscale=True, confidence=0.9)
if download_cloud is not None:
pyautogui.click(download_cloud)
def randomclick(box):
x_click = int(random.uniform(box.left, box.left + box.width))
y_click = int(random.uniform(box.top, box.top + box.height))
pyautogui.moveTo(x_click, y_click, duration=random.uniform(0.1, 0.2))
sleep(random.uniform(0.2, 0.3))
pyautogui.click()
sleep(random.uniform(1, 2))
def moverandomasf():
for hot_single_moms in range(random.randint(2, 6)):
x_click = random.randint(1, 1080)
y_click = random.randint(1, 1080)
pyautogui.moveTo(x=x_click, y=y_click, duration=random.uniform(0.2, 0.5))
def reload():
pyautogui.hotkey('ctrl', 'r')
sleep(reloadtime)
def s2t():
sleep(s2tv)
def andere_tabs_schließen():
pyautogui.hotkey('alt', 'o')
sleep(s2tv)
def captcha_checka():
global captchas_destroyed, fucked_by_captchas
captchabox = pyautogui.locateOnScreen("Roboterfeld.png", grayscale=False, confidence=0.9)
if captchabox is not None:
moverandomasf()
randomclick(captchabox)
if pyautogui.locateCenterOnScreen("imnotarobotiswear.png", grayscale=True, confidence=0.9):
print("I DESTROYED DA CAPTCHA BADABABOOM")
captchas_destroyed += 1
elif pyautogui.locateCenterOnScreen("fucked_by_captcha.png", grayscale=True, confidence=0.9):
print("I just got fucked by the captcha... rest in pieces")
reload()
fucked_by_captchas += 1
captcha_checka()
else:
print("No captcha that I can destroy!")
while True:
if is_pressed("ü"):
s2t()
while not is_pressed("ü"):
check4ads()
pyautogui.scroll(-120)
gay_heart = pyautogui.locateCenterOnScreen("gray_heart.png", grayscale=False, confidence=0.9)
if gay_heart is not None:
pyautogui.click(gay_heart)
cloud_download_checker()
s2t()
check4ads()
captcha_checka()
yellow_download()
s2t()
p720_checker()
Sample of my code
Is this possible in pycharm 2020.3.3?
Kind regards, Alupy
As far as I understand, Pycharm does not currently support separate colors for specific functions. It does support using a single color for ALL function definitions and another single color for ALL function calls.
I would start becoming familiar with the actions 'Find Usage', 'Find Usages', 'Find Usages in File', and 'Show Usages'. These will all help you locate where a function is being used.
Here's the error:
File "/Users/KarenLee/Desktop/temp/worldmodel.py", line 76, in update_on_time
obj = VeinAction(entity, image_store)
NameError: global name 'VeinAction' is not defined
And here is my code (this is in the file "actions.py"):
import entities
import worldmodel
import pygame
import math
import random
import point
import image_store
BLOB_RATE_SCALE = 4
BLOB_ANIMATION_RATE_SCALE = 50
BLOB_ANIMATION_MIN = 1
BLOB_ANIMATION_MAX = 3
FREEZE_ANIMATION_RATE = 100
FREEZE_STEPS = 4
ORE_CORRUPT_MIN = 20000
ORE_CORRUPT_MAX = 30000
QUAKE_STEPS = 10
QUAKE_DURATION = 1100
QUAKE_ANIMATION_RATE = 100
VEIN_SPAWN_DELAY = 500
VEIN_RATE_MIN = 8000
VEIN_RATE_MAX = 17000
WYVERN_RATE_MIN = 200
WYVERN_RATE_MAX = 600
WYVERN_ANIMATION_RATE = 100
class VeinAction:
def __init__(self, entity, image_store):
self.entity = entity
self.image_store = image_store
def vein_action(self, world, action, ticks):
entity = self.entity
open_pt = find_open_around(world, entities.get_position(entity),
entities.get_resource_distance(entity))
if open_pt:
ore = create_ore(world,
"ore - " + entities.get_name(entity) + " - " + str(ticks),
open_pt, ticks, action.image_store)
worldmodel.add_entity(world, ore)
tiles = [open_pt]
else:
tiles = []
schedule_action(world, entity, VeinAction(entity, action.image_store),
ticks + entities.get_rate(entity))
return tiles
def vein_take_action(self, world, action, ticks):
entities.remove_pending_action(self.entity, action)
if isinstance(action, VeinAction):
return self.vein_action(world, action, ticks)
And this is in the file "worldmodel.py":
import entities
import pygame
import ordered_list
import actions
import occ_grid
import point
class WorldModel:
def __init__(self, num_rows, num_cols, background):
self.background = occ_grid.Grid(num_cols, num_rows, background)
self.num_rows = num_rows
self.num_cols = num_cols
self.occupancy = occ_grid.Grid(num_cols, num_rows, None)
self.entities = []
self.action_queue = ordered_list.OrderedList()
def update_on_time(world, ticks):
tiles = []
next = world.action_queue.head()
obj = VeinAction(entity, image_store)
while next and next.ord < ticks:
world.action_queue.pop()
tiles.extend(obj.vein_take_action(world, next.item, ticks))
tiles.extend(actions.take_action(world, next.item, ticks))
next = world.action_queue.head()
return tiles
The error message comes from the update_on_time function in "worldmodel.py". I thought that this was how you would call a method from a class in a different file in a function, but it doesn't work! What is the correct way to do this? Or, is it possible to do this? Thanks in advance.
You imported the module actions which contains the class VeinAction. However, Python does not know this. You need to tell Python where VeinAction is located by adding actions. before it:
obj = actions.VeinAction(entity, image_store)
That, or you could import VeinAction directly:
from actions import VeinAction
Either way, you need to make sure that Python can find the class VeinAction.
I am trying to monitor keystrokes on my Macbook on order to build a statistics analyzer. But how can I isolate the chars from "event" which is more something like :
NSEvent: type=KeyDown loc=(850,248) time=66551.8 flags=0x100 win=0x0
winNum=0 ctxt=0x0 chars="l" unmodchars="l" repeat=0 keyCode=37
So do anyone know how to, based on the script posted below, fulfill a .txt doc with the value of chars (from NSEvent) ? I need a text file with a the pressed keys in order to run my other script on it and analyze the frequency etc...
Thanks in advance ;)
#!/usr/bin/python
# -*- coding: utf-8 -*-
from AppKit import NSApplication, NSApp
from Foundation import NSObject, NSLog
from Cocoa import NSEvent, NSKeyDownMask
from PyObjCTools import AppHelper
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, notification):
mask = NSKeyDownMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, handler)
def handler(event):
try:
print event
except KeyboardInterrupt:
AppHelper.stopEventLoop()
def main():
app = NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
#!/usr/bin/python2.6
# You _must_ turn on assistive devices under Accessibility prefpane
# for any of this code to work. Otherwise it won't do anything.
from Cocoa import *
from Foundation import *
from PyObjCTools import AppHelper
import keycode
import string
import sys
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, aNotification):
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, handler)
def handler(event):
if event.type() == NSKeyDown and keycode.tostring(event.keyCode()) in string.printable:
print keycode.tostring(event.keyCode())
def main():
app = NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
I dug around a bit and found github user 'gurgeh's OSX modifications for selfspy in his branch - https://github.com/gurgeh/selfspy/blob/new_activity/sniff_cocoa.py.
I put a few of my own ideas into it and this is the result. Kudos to gurgeh for figuring out how to capture window change events - this makes the key logger much more interesting since you could basically ignore apps that don't provide interesting events, or for the statistically minded, graph out which apps you use the most and what you're doing in them..
#!/usr/bin/python2.6
import exceptions
import sys
from Foundation import NSObject, NSLog
from AppKit import NSApplication, NSApp, NSWorkspace
from Cocoa import *
from Quartz import CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, kCGNullWindowID
from PyObjCTools import AppHelper
import keycode
evtypes = dict(
NSLeftMouseDown = 1,
NSLeftMouseUp = 2,
NSRightMouseDown = 3,
NSRightMouseUp = 4,
NSMouseMoved = 5,
NSLeftMouseDragged = 6,
NSRightMouseDragged = 7,
NSMouseEntered = 8,
NSMouseExited = 9,
NSKeyDown = 10,
NSKeyUp = 11,
NSFlagsChanged = 12,
NSAppKitDefined = 13,
NSSystemDefined = 14,
NSApplicationDefined = 15,
NSPeriodic = 16,
NSCursorUpdate = 17,
NSScrollWheel = 22,
NSTabletPoint = 23,
NSTabletProximity = 24,
NSOtherMouseDown = 25,
NSOtherMouseUp = 26,
NSOtherMouseDragged = 27
)
evtypes_rev = dict([[v,k] for k,v in evtypes.items()])
class Hooker(object):
def __call__(self, *args, **kwargs):
try:
evt = kwargs.get('event')
del kwargs['event']
items = ' '.join( [ x[0]+"="+unicode(x[1]) for x in kwargs.iteritems()] )
print "%20s | %22s | %s" % ( self.__class__.__name__, evtypes_rev[evt.type()], items)
except Exception as e:
print 'Horrific error!', e
AppHelper.stopEventLoop()
sys.exit(0)
class KeyHooker(Hooker): pass
class MouseButtonHooker(Hooker): pass
class MouseMoveHooker(Hooker): pass
class ScreenHooker(Hooker): pass
class SniffCocoa:
def __init__(self):
self.key_hook = KeyHooker()
self.mouse_button_hook = MouseButtonHooker()
self.mouse_move_hook = MouseMoveHooker()
self.screen_hook = ScreenHooker()
self.currentApp = None
def createAppDelegate (self) :
sc = self
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, notification):
mask = (
NSKeyDownMask
| NSKeyUpMask
| NSLeftMouseDownMask
| NSLeftMouseUpMask
| NSRightMouseDownMask
| NSRightMouseUpMask
| NSMouseMovedMask
| NSScrollWheelMask
)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, sc.handler)
return AppDelegate
def run(self):
NSApplication.sharedApplication()
delegate = self.createAppDelegate().alloc().init()
NSApp().setDelegate_(delegate)
self.workspace = NSWorkspace.sharedWorkspace()
AppHelper.runEventLoop()
def cancel(self):
AppHelper.stopEventLoop()
def handler(self, event):
try:
activeApps = self.workspace.runningApplications()
for app in activeApps:
if app.isActive():
if app.localizedName() != self.currentApp:
self.currentApp = app.localizedName()
options = kCGWindowListOptionOnScreenOnly
windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID)
for window in windowList:
if window['kCGWindowOwnerName'] == self.currentApp:
geom = window['kCGWindowBounds']
self.screen_hook( event=event,
name = window['kCGWindowName'],
owner = window['kCGWindowOwnerName'],
x = geom['X'],
y = geom['Y'],
w = geom['Width'],
h = geom['Height'])
break
break
loc = NSEvent.mouseLocation()
# mouse clicky buttons
if event.type() in ( NSLeftMouseDown, NSRightMouseDown, NSLeftMouseUp, NSRightMouseUp):
self.mouse_button_hook(event=event, x=loc.x, y=loc.y)
# mouse scrolly buttons
elif event.type() == NSScrollWheel:
if event.deltaY() > 0 and event.deltaY() < 0:
self.mouse_button_hook(event=event, x=loc.x, y=loc.y)
if event.deltaX() > 0 and event.deltaX() < 0:
self.mouse_button_hook(event=event, x=loc.x, y=loc.y)
# keys down
elif event.type() in ( NSKeyDown, NSKeyUp ):
flags = event.modifierFlags()
modifiers = [] # OS X api doesn't care it if is left or right
if (flags & NSControlKeyMask):
modifiers.append('CONTROL')
if (flags & NSAlternateKeyMask):
modifiers.append('ALTERNATE')
if (flags & NSCommandKeyMask):
modifiers.append('COMMAND')
self.key_hook(event=event, key=event.keyCode(), char=keycode.tostring( event.keyCode() ), mods=modifiers, is_repeat=event.isARepeat())
# Mouse moved
elif event.type() == NSMouseMoved:
self.mouse_move_hook(event=event, x=loc.x, y=loc.y)
else:
pass
except ( KeyboardInterrupt ) as e:
print 'handler', e
AppHelper.stopEventLoop()
if __name__ == '__main__':
sc = SniffCocoa()
sc.run()
For using Keycode module. Just clone it from here and run "sudo setup.py install" . You will have keycode module
https://github.com/abarnert/pykeycode