iterating intergers over a method from a range - python

Im trying to create a list of CommandLinks in Revit Dynamo using python with a forloop that checks the length of the inputs list and creates an array of Commandlinks from a range generated from that list. Is it possible to insert the integer into the CommandLink method using a forloop?
`
import clr
import sys
import System
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Clipboard
# import Revit API
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
clr.AddReference("RevitAPIUI")
from Autodesk.Revit.UI import (TaskDialog, TaskDialogCommonButtons,
TaskDialogCommandLinkId, TaskDialogResult)
title = IN[0]
buttonlists = IN[1]
resultslist = IN[2]
dialog = TaskDialog(title)
buttonNum = len(resultslist)
# Properties
dialog.MainInstruction = title
# dialog.ExpandedContent = expanded_content
# Settings and buttons
dialog.TitleAutoPrefix = False
dialog.AllowCancellation = True
dialog.CommonButtons = TaskDialogCommonButtons.Cancel
dialog.DefaultButton = TaskDialogResult.Cancel
# Add Command Link
for n in range(buttonNum+1):
dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink+(n), buttontext+(n))
result = dialog.Show()
if result == TaskDialogResult.Cancel:
OUT = 'Dialog was Cancelled'
if result == TaskDialogResult.CommandLink(n):
OUT = result(n)
`
enter image description here
I need to iterate (n) into the commandlink numbers and results, so it creates commandlinks based on the length of the input list.

Related

TF2 transform can't find an actuall existing frame

In a global planner node that I wrote, I have the following init code
#!/usr/bin/env python
import rospy
import copy
import tf2_ros
import time
import numpy as np
import math
import tf
from math import sqrt, pow
from geometry_msgs.msg import Vector3, Point
from std_msgs.msg import Int32MultiArray
from std_msgs.msg import Bool
from nav_msgs.msg import OccupancyGrid, Path
from geometry_msgs.msg import PoseStamped, PointStamped
from tf2_geometry_msgs import do_transform_point
from Queue import PriorityQueue
class GlobalPlanner():
def __init__(self):
print("init global planner")
self.tfBuffer = tf2_ros.Buffer()
self.listener = tf2_ros.TransformListener(self.tfBuffer)
self.drone_position_sub = rospy.Subscriber('uav/sensors/gps', PoseStamped, self.get_drone_position)
self.drone_position = []
self.drone_map_position = []
self.map_sub = rospy.Subscriber("/map", OccupancyGrid, self.get_map)
self.goal_sub = rospy.Subscriber("/cell_tower/position", Point, self.getTransformedGoal)
self.goal_position = []
self.goal = Point()
self.goal_map_position = []
self.occupancy_grid = OccupancyGrid()
self.map = []
self.p_path = Int32MultiArray()
self.position_pub = rospy.Publisher("/uav/input/position", Vector3, queue_size = 1)
#next_movement in
self.next_movement = Vector3
self.next_movement.z = 3
self.path_pub = rospy.Publisher('/uav/path', Int32MultiArray, queue_size=1)
self.width = rospy.get_param('global_planner_node/map_width')
self.height = rospy.get_param('global_planner_node/map_height')
#Check whether there is a path plan
self.have_plan = False
self.path = []
self.euc_distance_drone_goal = 100
self.twod_distance_drone_goal = []
self.map_distance_drone_goal = []
self.mainLoop()
And there is a call-back function call getTransformed goal, which will take the goal position in the "cell_tower" frame to the "world" frame. Which looks like this
def getTransformedGoal(self, msg):
self.goal = msg
try:
#Lookup the tower to world transform
transform = self.tfBuffer.lookup_transform('cell_tower', 'world', rospy.Time())
#transform = self.tfBuffer.lookup_transform('world','cell-tower' rospy.Time())
#Convert the goal to a PointStamped
goal_pointStamped = PointStamped()
goal_pointStamped.point.x = self.goal.x
goal_pointStamped.point.y = self.goal.y
goal_pointStamped.point.z = self.goal.z
#Use the do_transform_point function to convert the point using the transform
new_point = do_transform_point(goal_pointStamped, transform)
#Convert the point back into a vector message containing integers
transform_point = [new_point.point.x, new_point.point.y]
#Publish the vector
self.goal_position = transform_point
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException) as e:
print(e)
print('global_planner tf2 exception, continuing')
The error message said that
"cell_tower" passed to lookupTransform argument target_frame does not exist.
I check the RQT plot for both active and all, which shows that when active, the topic /tf is not being subscribe by the node global planner. Check the following image, which is for active
enter image description here
and this image is for all the node (include non-active)
enter image description here
But I have actually set up the listner, I have another node call local planner that use the same strategy and it works for that node, but not for the global planner
I'm not sure why this is.
Try adding a timeout to your lookup_transform() function call, as your transformation may not be available when you need it:
transform = self.tfBuffer.lookup_transform('cell_tower', 'world',rospy.Time.now(), rospy.Duration(1.0))

How to delete X% of entries from a DynamoDB Table?

I want to remove 10% of entries from a DDB table every time a script is ran. So far, I have created a Python script using boto3 that will delete all items from a DDB table:
import boto3
import sys
src_region = sys.argv[1]
src_profile_name = sys.argv[2]
src_ddb_table = sys.argv[3]
# Create source session.
src_session = boto3.session.Session(profile_name=src_profile_name)
dynamoclient = src_session.client('dynamodb', region_name=src_region)
dynamoresponse = dynamoclient.get_paginator('scan').paginate(
TableName=src_ddb_table,
Select='ALL_ATTRIBUTES',
ReturnConsumedCapacity='NONE',
ConsistentRead=True
)
for page in dynamoresponse:
for item in page['Items']:
dynamoclient.delete_item(
Key={'testTableDest': item['testTableDest']},
TableName=src_ddb_table)
How can I modify this script to allow the user to select a percentage of entries they want to delete?
Thank you for any help!
If you want to delete them at random and are ok with a non-exact percentage you can do this easily with the python random package.
import boto3
import sys
import random
src_region = sys.argv[1]
src_profile_name = sys.argv[2]
src_ddb_table = sys.argv[3]
percent_delete = int(sys.argv[4]) # 20
# Create source session.
src_session = boto3.session.Session(profile_name=src_profile_name)
dynamoclient = src_session.client('dynamodb', region_name=src_region)
dynamoresponse = dynamoclient.get_paginator('scan').paginate(
TableName=src_ddb_table,
Select='ALL_ATTRIBUTES',
ReturnConsumedCapacity='NONE',
ConsistentRead=True
)
for page in dynamoresponse:
for item in page['Items']:
if random.random() * 100 < percent_delete:
dynamoclient.delete_item(
Key={'testTableDest': item['testTableDest']},
TableName=src_ddb_table)
This isn't "perfectly random" but will suffice.

How do I use a csv data as variables to apply it for a formula?

I'm trying to use data from a csv file ( https://www.kaggle.com/jingbinxu/sample-of-car-data ). I only need the horsepower and weight columns as variables for the equation: ( 1/4 mile et = 6.290 * (weight/hp) ** .33 ), but it won't apply it. I don't know if the storage is working or I shouldn't do it as a class. When I run the program it doesn't show any errors, but it doesn't show results either. Then I got to plot the results, but I don't think it's even calculating and storing results. Any help is appreciated. Thanks in advance.
Here's the current code i have:
import numpy as np
class car_race_analysis():
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename,delimiter= ',', skip_header = 1 )
def race_stats(self,w,h):
#cars in data
cars = np.unique(self.data[:,0])
#storage for output
race_times = []
#for each car
for car in cars:
#mask
mask = self.data[:,0] == car
#get data
w = self.data[mask,12]
h = self.data[mask,18]
#apply formula
qrtr_mile = 6.290 * ( w / h ) ** .33
race_times.append(qrtr_mile)
#new atribute
self.race_times = np.array(race_times)
print(race_times)
def trend_plotter(self):
import matlib.pyplot as plt
#inputs
self.race_stats
cars = np.unique(self.data[:,0])
#plot
plt.plot(cars,self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
filename = 'car_data.csv'
Two problems:
I think you meant matplotlib instead of matlib. Make sure you install it pip3 install matplotlib --user and edit your code accordingly.
Your previous code wasn't working because you weren't instantiating a class or running any methods. The only "work" your program did was to define the class and then set a filename variable.
To solve #2, replace your filename=... line with the code below.
Here's what it does:
It checks to see if the file is being run directly (i.e. from command prompt such as python3 <your_file_name>.py. If this class is being imported and used from a different python file, this code would not be executed. More reading: https://www.geeksforgeeks.org/what-does-the-if-name-main-do/
We instantiate a instance of your class and supply the filename variable since that it was your class' __init__ method expects.
We invoke the trend_plotter method on the instance of the class.
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()
Even with those changes, your program will not work because it has other errors. I made a guess at fixing it, which I've pasted below, but I strongly encourage you do diff my changes to understand what I altered to be sure it does what you want.
import numpy as np
import matplotlib.pyplot as plt
class car_race_analysis():
race_times = []
cars = []
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename, delimiter=',', skip_header=1)
def race_stats(self, w, h):
#cars in data
self.cars = np.unique(self.data[:, 0])
# storage for output
self.race_times = []
# for each car
for car in self.cars:
# mask
mask = self.data[:, 0] == car
# get data
w = self.data[mask, 12]
h = self.data[mask, 18]
# apply formula
qrtr_mile = 6.290 * (w / h) ** .33
self.race_times.append(qrtr_mile)
# new atribute
self.race_times = np.array(self.race_times)
def trend_plotter(self):
# inputs
self.race_stats(len(self.cars), len(self.race_times))
# plot
plt.plot(self.cars, self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
plt.show()
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()

text_generator.py "Access is Denied"

I'm having trouble with this code. For some reason whenever I use the test client, I get this message.
import stdio
import sys
from markov_model import MarkovModel
def main():
k = int(sys.argv[1])
T = int(sys.argv[2])
# text from standard input initialized to variable
text = sys.stdin.read()
# slices text and initializes it to kgram
kgram = text[:k]
model = markov_model(text, k)
# model is used to generate random length of text
stdio.writeln(model.gen(kgram, T))
if __name__ == '__main__':
main()
text_generator.py 5 50 < data / bible.txt
Access is denied.

'list' object has no attribute 'winType'

I'm trying to run a python script but I get this error. AttributeError: 'list' object has no attribute 'winType':
The actual contents of the file are:
import time
import pylsl
import bci.open_bci_v3 as bci
#from random import random as rand
from pylsl import StreamInfo, StreamOutlet
from psychopy import prefs
prefs.general['audioLib'] = ['pygame']
from psychopy import visual, core, sound
import esys_cfg
NUM_CHANNELS = 8
SAMP_RATE = 100
info = StreamInfo('OpenBCI', 'EEG', NUM_CHANNELS, SAMP_RATE, 'float32', 'myuid34234')
outlet = StreamOutlet(info)
#funtion call to start displaying images
#def displayStimuli
# for file in os.listdir('directory'):
# for i in range(0,len(images)):
# def display(files, .....):
# ex: file_name = ['/dir/dir2/img.png']
window = visual.Window([512, 512])
cfg = esys_cfg.create_config('../stimulus-config/test.yml')
print(cfg.trial_order)
#trial_order = ['one', 'two', 'one']
for element in cfg.trial_order: #loop through all elements in array trial_order
imageIndex = 0
for imageIndex in range(len(cfg.trials[element].files)):
stimulis = cfg.trials[element].stimuli_folder + '/' + cfg.trials[element].files[imageIndex]
showStim = visual.ImageStim(window, stimulis)
showStim.draw([window])
window.flip()
core.wait(2.0)
How can I correct this and run the program?
The error arises in the line
showStim.draw([window])
which should read
showStim.draw(window)
and if you only have one window, simply do
showStim.draw()
which draws in the window that showStim was given as argument at initialization. BTW, initializing a psychopy stimulus is computationally heavy (easily takes a few hundred milliseconds), so do it once at the beginning of the script and then update the relevant aspect during runtime. In your case, do this:
showStim = visual.ImageStim(window) # initialize the stimulus
for element in cfg.trial_order: #loop through all elements in array trial_order
imageIndex = 0
for imageIndex in range(len(cfg.trials[element].files)):
stimulis = cfg.trials[element].stimuli_folder + '/' + cfg.trials[element].files[imageIndex]
showStim.image = stimulus # update the image
As you have only one window you could use:
showStim.window = window # stimulus is now drawn to window
showStim.draw()
If you have more than one window you can pass the relevant window as a parameter (The brackets in your code are redundant).
# Note that this just changes **default** window for stimulus.
showStim.draw(win1)
showStim.draw(win2)

Categories

Resources