Attribute Error. Can not access attributes in Class - python

I'm trying to call a class Pager in my main function in Python. When I run the program it gives me an error:
Traceback (most recent call last): File "lab4.py", line 113, in <module>
main() File "lab4.py", line 34, in main
demandPager.processRef(p, clock, rand) File "/Users/kiranbhimani/Desktop/OSLab4/Pager.py", line 16, in processRef
desiredPage = Pager.frameTable.findPageById(testId, process.getProcessId())
**AttributeError: class Pager has no attribute 'frameTable'**
How can I access frameTable? If I insert "self" as a parameter, I can't call the class. It says processRef requires 4 arguments but only 3 are given.
I'm not sure what is going on here. Thank you in advance!
class Pager:
def __init__(self, machineSize, pageSize):
self.machineSize = machineSize
self.pageSize = pageSize
self.frameTable = FrameTable(int(machineSize/pageSize))
#staticmethod
def processRef(process, clock, randreader):
ref = int(process.currentReference)
testId = int(ref / Page.size)
#print Pager.machineSize
desiredPage = Pager.frameTable.findPageById(testId, process.getProcessId())
if (isHit(desiredPage, process)):
desiredPage.addRefdWord(ref)
else:
if (not frameTable.isFull()):
frameTable.addPage(process, testId, ref)
else:
pageToEvict = findPageToReplace(replacementAlgo, randreader)
frameTable.evictPage(pageToEvict)
frameTable.addPage(process, testId, ref)
desiredPage = frameTable.lastPageAdded
desiredPage = frameTable.lastPageAdded
desiredPage.setIfLoaded(true)
process.incrNumPageFaults()
desiredPage.timeLastUsed = clock
frameTable.updateTimes()
This is the main function:
from Process import Process
from Page import Page as Page
from Pager import Pager
from FrameTable import FrameTable
import sys
runningProcesses = []
finishedProcesses = []
def main():
#read input
machineSize = int(sys.argv[1])
pageSize = int(sys.argv[2])
processSize = int(sys.argv[3])
jobMix = int(sys.argv[4])
numOfRefPerProcess = int(sys.argv[5])
replacementAlgo = (sys.argv[6])
demandPager = Pager(machineSize, pageSize)
Page.size = pageSize
Process.size = processSize
setProc(jobMix)
demandPager.replacementAlgo = replacementAlgo
index = 0
clock = 0
while(len(runningProcesses) > 0):
p = runningProcesses[index]
for i in range(3):
demandPager.processRef(p, clock, rand)
p.setCurrentReference(p.calcNextReference(rand))
p.incrRefsMade()
clock+=1
if (p.getRefsMade() == numRefPerProcess):
finishedProcesses.add(p)
runningProcesses.remove(p)
index-=1
break
if (index == numProcesses-1):
index = 0
else:
index+=1
print "printing....."
printOutput(args)

You tried to access a class property frameTable, but this class has no added properties at all. Objects of the class have properties of machineSize, FrameSize, and pageTable -- that's one of each for every object you instantiate.
For instance, there will be a demandPager.frameTable once you hit the creation command, but you haven't given any properties (other than the built-ins) to Pager as a class.
Perhaps you want to use self
desiredPage = self.frameTable.findPageById(testId, process.getProcessId())

Related

Meshcat not showing the changes to a Free Body's Pose

I've been trying to create my own ManipulationStation for a different robot arm using Pydrake, but I've been unsuccessful so far in adding clutter to my ManipulationStation. For some odd reason, Meshcat won't show the updated poses of my objects.
import numpy as np
import glob
from pydrake.geometry import MeshcatVisualizerCpp
from pydrake.math import RigidTransform, RotationMatrix
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.all import (
DiagramBuilder, FindResourceOrThrow,
SceneGraph, Diagram,
MultibodyPlant, Parser, Simulator, MeshcatVisualizerCpp,
UniformlyRandomRotationMatrix, RandomGenerator)
from pydrake.geometry import Meshcat
class DexterPPStation(Diagram):
def __init__(self, time_step, file_path):
super().__init__()
self.time_step = time_step
self.path = file_path
self.plant = MultibodyPlant(self.time_step)
self.scene_graph = SceneGraph()
self.plant.RegisterAsSourceForSceneGraph(self.scene_graph)
self.controller_plant = MultibodyPlant(self.time_step)
self.object_ids = []
self.object_poses = []
def AddObject(self, file, name, pose):
model_idx = Parser(self.plant).AddModelFromFile(file, name)
indices = self.plant.GetBodyIndices(model_idx)
self.object_ids.append(indices[0])
self.object_poses.append(pose)
return model_idx
def CreateBins(self, path, XP_B1, XP_B2):
bin1 = Parser(self.plant).AddModelFromFile(path, "bin1")
self.plant.WeldFrames(self.plant.world_frame(), self.plant.GetFrameByName("bin_base", bin1), XP_B1)
bin2 = Parser(self.plant).AddModelFromFile(path, "bin2")
self.plant.WeldFrames(self.plant.world_frame(), self.plant.GetFrameByName("bin_base", bin2), XP_B2)
def CreateRandomPickingObjects(self, n = 4):
choices = [f for f in glob.glob("/opt/drake/share/drake/manipulation/models/ycb/sdf/*.sdf")]
z = 0.1
rs = np.random.RandomState()
generator = RandomGenerator(rs.randint(1000))
for i in range(n):
obj = choices[i]
pose = RigidTransform(
UniformlyRandomRotationMatrix(generator),
[rs.uniform(.35,0.6), rs.uniform(-.2, .2), z])
model = self.AddObject(obj, obj.split("/")[-1].split(".")[0] + str(i), pose)
body_idx = self.plant.GetBodyIndices(model)[0]
self.object_ids.append(body_idx)
self.object_poses.append(pose)
z+=0.1
def SetRandomPoses(self, station_context):
plant_context = self.GetSubsystemContext(self.plant, station_context)
for i in range(len(self.object_ids)):
self.plant.SetFreeBodyPose(plant_context, self.plant.get_body(self.object_ids[i]), self.object_poses[i])
def Finalize(self):
self.plant.Finalize()
self.controller_plant.Finalize()
builder = DiagramBuilder()
builder.AddSystem(self.plant)
builder.AddSystem(self.controller_plant)
builder.AddSystem(self.scene_graph)
builder.Connect(self.plant.get_geometry_poses_output_port(), self.scene_graph.get_source_pose_port(self.plant.get_source_id()))
builder.Connect(self.scene_graph.get_query_output_port(), self.plant.get_geometry_query_input_port())
builder.ExportOutput(self.scene_graph.get_query_output_port(), "query_object")
builder.ExportOutput(self.plant.get_geometry_poses_output_port(), "geometry_poses")
builder.ExportOutput(self.scene_graph.get_query_output_port(), "geometry_query")
builder.ExportOutput(self.plant.get_contact_results_output_port(),"contact_results")
builder.ExportOutput(self.plant.get_state_output_port(),"plant_continuous_state")
builder.BuildInto(self)
To test my code, I've been running the script below.
def test():
builder = DiagramBuilder()
station = DexterPPStation(1e-4, "drake/manipulation/models/final_dexter_description/urdf/dexter.urdf")
station.CreateBins("/opt/drake/share/drake/examples/manipulation_station/models/bin.sdf", RigidTransform(np.array([0.5,0,0])), RigidTransform(np.array([0,0.5,0])))
station.CreateRandomPickingObjects(1)
station.Finalize()
builder.AddSystem(station)
station_context = station.CreateDefaultContext()
station.SetRandomPoses(station_context)
MeshcatVisualizerCpp.AddToBuilder(builder, station.GetOutputPort("query_object"), meshcat)
diagram = builder.Build()
simulator = Simulator(diagram)
simulator.set_target_realtime_rate(1.0)
simulator.AdvanceTo(0.1)
test()
I've tried to call the SetRandomPoses() function from inside my Finalize() method, but since I needed to pass in a context to the function, I wasn't sure what to do. I'm new to Drake, so any input would be greatly appreciated.
You've created a station_context and set it to the random poses, but then you don't use it anywhere. When you create the simulator, it is creating another Context (with the default values), which is getting published when you call AdvanceTo.
The solution here, I think, is to not create your own station_context, but do e.g.
simulator = Simulator(diagram)
diagram_context = simulator.get_mutable_context()
station_context = station.GetMyMutableContextFromRoot(diagram_context)
station.SetRandomPoses(station_context)
then you can call AdvanceTo.

I can't pass data from thread to GUI JLabel

if name == 'main':
demo = DesktopFrame()
demo.setLocation(30, 30)
demo.show()
comm = "COM4"
global comPort
comPort = MyCommPort()
comPort.set_port(comm)
poll = Polling(comPort)
poll.start()
poll.join()
This code runs (as def), My GUI comes up and allows me to change the frame content from the menu while the thread POLL sends and receives data from my serial port (fixed test loop of 20 times right now)
**GOAL:
My goal is to have the thread update a JLabel (make it change node address) as it goes through the polling sequence.**
I've been following the jthon-swingutils2.1.1 documentation
https://pythonhosted.org/jython-swingutils/threads.html
-- Running GUI code from background threads.
from swingutils.threads.swing import callSwing
def fillInExchangeRate():
rate = fetchExchangeRate('USD', 'EUR')
callSwing(rateField.setValue, rate)
PROBLEM:
Method pollUpdate(self, address)
I can't discover the correct way for callSwing() to find my GUI JLabel [pollText] I get the following error message.
Exception in thread Thread-1:Traceback (most recent call last):
File "C:\jython2.7.0\Lib\threading.py", line 222, in _Thread__bootstrap self.run()
File "C:\Users\jwkel\Documents\NetBeansProjects\JythonProject\src\mycommport.py", line 95, in run self.xmit_data(self.toOutput)
File "C:\Users\jwkel\Documents\NetBeansProjects\JythonProject\src\mycommport.py", line 71, in xmit_data self.pollUpdate("Polling A")
File "C:\Users\jwkel\Documents\NetBeansProjects\JythonProject\src\mycommport.py", line 66, in pollUpdate callSwing(pollText.setValue, address)
NameError: global name 'pollText' is not defined
now for some general information about my GUI
demo = JFrame
self.menubar = JMenuBar() + 5 JMenu() + 15 JMenuItem() // all working correctly
self.add(self.mainPanel, BorderLayout.EAST)
contains:
self.mainPanel = JPanel()
self.mainText = JTextArea()
self.mainScroll = JScrollPane(self.mainText) +
self.mainScroll.getViewport().setView((self.mainText))
self.mainPanel = JPanel() self.mainPanel.add(self.mainScroll)
self.add(self.modePanel, BorderLayout.NORTH)
contains:
self.modePanel = JPanel()
self.modeText = JLabel("Current Mode Setting : Stand Alone")
self.pollText = JLabel("Polling Reader - ?") ******* MY TARGET ********
self.add(self.panel, BorderLayout.WEST)
contains:
self.panel = JPanel()
self.panel.add(JLabel(ImageIcon(self.showImage)))
problem code
from swingutils.threads.swing import callSwing
class Polling(Thread):
def __init__(self, pollPort):
Thread.__init__(self)
self._pollPort= pollPort
def pollUpdate(self, address):
callSwing(pollText.setValue, address)
def xmit_data(self,sendThis):
'''commands and data sent to readers'''
print 'send this ',sendThis
self.pollUpdate("Polling A")
self._pollPort.outStream.write(sendThis)
time.sleep(0.3)
self._pollPort.outStream.flush()
def recv_data(self):
'''relies and requests from readers'''
print 'recev data'
self.pollUpdate("Polling #")
self.s =''
self.text = ''
for num in range(100):
self.s = self._pollPort.inStream.read()
if self.s == 10:
break
else:
self.text = self.text + chr(self.s)
print 'text = ', self.text
return self.text
def run(self):
for i in range(20):
time.sleep(.100)
self.toOutput="*ATest\n"
self.xmit_data(self.toOutput)
time.sleep(.300)
self.myText = self.recv_data()
print self.myText
I found a better example to follow and rewrote the code to use a java Class SwingWorker. All is well!

RuntimeError: deleteUI: Object 'Animation_Copy_Tool' not found

Getting this error when pressing the "Close Window" button in my UI. This button should delete the UI window but isn't. Full traceback:
Error: deleteUI: Object 'Animation_Copy_Tool' not found.
Traceback (most recent call last):
File "", line 36, in closeBtnCmd
RuntimeError: deleteUI: Object 'Animation_Copy_Tool' not found. #
# Animation Copy Tool
# Bakari Holmes 5/7/2015
# This is designed to copy and existing animation
# from one rig to another and make the process easier
# with a simple UI
import maya.cmds as mc
import functools
import maya.mel as mm
import pprint
class AnimCopyWindow(object):
##classmethod
def showUI(cls):
win = cls()
win.create()
return win
def __init__(self):
self.window = "Animation Copy Tool"
self.title = "Animation Copier"
self.size = (546,350)
def pasteTheseKeys(self, *args):
self.offsetVal = mc.intFieldGrp(self.int_offset, q=True, value1=True)
self.selObj_pasteKeys = mc.ls(sl=True)
for objectQuant in self.selObj_pasteKeys:
print objectQuant
self.ct = mc.currentTime(query = True)
self.t = self.ct + self.offsetVal
mc.currentTime(self.t)
# mc.selectKey(selObj_pasteKeys[objectQuant])
mc.pasteKey(time=(self.t,self.t), f=(1.0,1.0), option="merge", copies=1, to=0, fo=0, vo=0)
def closeBtnCmd(self,*args):
mc.deleteUI(self.window,window=True)
def create(self):
# check to see if window exists already
if mc.window(self.window,exists=True):
mc.deleteUI(self.window,window=True)
self.window = mc.window(self.window, title=self.title,widthHeight=self.size,menuBar=True)
self.copyAnim = mc.window(title="Transfer Animation Tool", backgroundColor=[0.3,0.3,0.3],sizeable=False,resizeToFitChildren=True)
#set the layout for UI
mc.columnLayout(adjustableColumn=True)
self.tx_src = mc.textFieldGrp(label="Source Object", editable=False, text=sel[0])
self.int_offset = mc.intFieldGrp(label="Frame Offset Amount", value1=0)
#add paste animation button
self.btn1 = mc.button(label="PASTE ANIMATION", command=self.pasteTheseKeys, bgc=[0.1,0.1,0.5])
#add close button window
self.btn2 = mc.button(label="CLOSE WINDOW", command=self.closeBtnCmd, bgc=[0.2,0.2,0.2])
mc.showWindow()
#################################
#####end of class definition#####
#################################
def keys_as_dictionary(channel):
"""return a dictionay of times:values for <channel>"""
keys = mc.keyframe(channel, q=True, tc=True) or []
values = mc.keyframe(channel, q=True, vc=True) or []
return dict(zip(keys, values))
def channels():
"""return a dictionary of <plug>:<channel_dict> for each animated plug selected"""
keys = mc.keyframe(sl=True, n=True, q=True)
result = {}
for k in keys:
plugs = mc.listConnections(k, p=True)[0]
result[plugs]= keys_as_dictionary(k)
return result
#store selected object info
sel = mc.ls(selection=True)
if (len(sel) != 1):
mm.eval("warning Must select one animated object;")
else:
mc.copyKey()
win = AnimCopyWindow()
win.create()
pprint.pprint(channels())
This error almost always means your UI element is not named what you think it is: Maya will automatically rename the items to make sure that no two siblings have the same name -- you can ask for "my_window" and get back "my_window123" . So you need to capture the actual name that is returned from cmds.window() or whatever ui command you use and delete that. Hard coded names are never reliable

Python: Can't pop from an empty list

I am creating a python program to detect and enable usb to usb data transfer between usb storage drives. However I am having an issue with updating the dev_label (device name of the drive) and passing it to Exchange. Here is the code :
serial_list=[]
context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='block',device_type='partition')
observer = GUDevMonitorObserver(monitor)
def device_connected(observer, device):
Welcome.device_count+=1
flag =False
for iden in serial_list :
if iden == device.__getitem__('ID_SERIAL_SHORT'):
flag=True
if flag ==False:
serial_list.append(device.__getitem__('ID_SERIAL_SHORT'))
Welcome.dev_label.append(str(device.__getitem__('ID_FS_LABEL')))
size = len(Welcome.dev_label)
label = gtk.Label('Device connected :: {0!r}'.format(Welcome.dev_label[size-1]))
Welcome.vbox.pack_start(label)
Welcome.window.show_all()
if Welcome.device_count<2:
label = gtk.Label('Connect the second device')
Welcome.vbox.pack_start(label)
Welcome.window.show_all()
else :
Exchange()
observer.connect("device-added",device_connected)
monitor.start()
class Welcome:
device_count = 0
window = gtk.Window()
vbox= gtk.VBox(False, 5)
dev_label = []
def __init__(self):
self.window.set_default_size(300, 300)
self.window.set_title("Welcome")
label = gtk.Label("Connect the desired device")
self.vbox.pack_start(label)
self.window.add(self.vbox)
self.window.connect("destroy", lambda q: gtk.main_quit())
self.window.show_all()
class Exchange:
window1 = gtk.Window(Welcome.dev_label.pop())
window2 = gtk.Window(Welcome.dev_label.pop())
def __init__(self):
width = gtk.gdk.screen_get_default().get_width()
height = gtk.gdk.screen_get_default().get_height()
self.window1.resize(width/2,height)
self.window2.resize(width/2,height)
self.window2.move(self.window1.get_position()[0]+width/2, self.window1.get_position()[1])
label = gtk.Label("Hello")
self.window1.add(label)
self.window1.connect("destroy" , lambda q : gtk.main_quit())
self.window1.show_all()
label = gtk.Label("World")
self.window2.add(label)
self.window2.connect("destroy",lambda q : gtk.main_quit())
self.window2.show_all()
Welcome()
gtk.main()
The error shown in the trace back is :
Traceback (most recent call last):
File "project.py", line 70, in <module>
class Exchange:
File "project.py", line 71, in Exchange
window1 = gtk.Window(Welcome.dev_label.pop())
IndexError: pop from empty list
I can't figure out how to synchronize all these event so that the compiler doesn't throw an error. Values are being popped from Welcome.dev_label only after they've been updated in device_connected so why does the compiler have a problem? I am a python newbie so please be gentle.
This is not the compiler givin errors but the program.
You can change your class to this:
import time
class Exchange:
while not Welcome.dev_label: time.sleep(0.001)
window1 = gtk.Window(Welcome.dev_label.pop()) # line 4
while not Welcome.dev_label: time.sleep(0.001)
window2 = gtk.Window(Welcome.dev_label.pop())
This would be kind of a synchronization primitive given that only line 4 and 6 remove content.
In general you would use a queue for this.
import queue # Python3 # import Queue Python 2
Welcome.dev_label # = queue.Queue()
Welcome.dev_label.put(...) # instead of append
Welcome.dev_label.get(...) # instead of pop
But I do not know wether your code uses threads and runs in parallel. If the time.sleep example works then you can switch to a queue.

Cocos2d: AttributeError: 'Director' object has no attribute '_window_virtual_width'

We are using the cocos2d framework to create a game. We're completely new to this framework, so we cannot get the director object to work as we are expecting. Here is our code skeleton:
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter():
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def main():
scene = TestScene()
director.init(world_width, world_height, do_not_scale=True)
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
So for some reason the director doesn't have all the attributes we want.
Our stack trace is:
Traceback (most recent call last):
File "map.py", line 49, in <module>
main()
File "map.py", line 39, in main
scene = TestScene()
File "map.py", line 29, in __init__
super(TestScene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/scene.py", line 95, in __init__
super(Scene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/cocosnode.py", line 114, in __init__
self.camera = Camera()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 56, in __init__
self.restore()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 76, in restore
width, height = director.get_window_size()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/director.py", line 522, in get_window_size
return ( self._window_virtual_width, self._window_virtual_height)
AttributeError: 'Director' object has no attribute '_window_virtual_width'
You need to initialise the director before you instantiate your first scene. The director is the global object that initialises your screen, sets up the Cocos2D framework, etc.
I found a few other errors:
You need to change ColorLayer to be fully qualified, e.g. cocos.layer.ColorLayer.
on_enter needs to have self as the first argument.
You need to define f_refresh_marks in your TestScene class.
Here's a working copy of the code. (Working, in the sense that it does not throw errors, not that it does any sort of scrolling.)
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def f_refresh_marks(self):
pass
def main():
director.init(world_width, world_height, do_not_scale=True)
scene = TestScene()
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
if __name__ == '__main__': main()
I had the same issue (with a very similar stack trace) and it was because I was trying to create a layer before calling director.init(). Moving director.init() to earlier in the code fixed it for me.

Categories