Matlab instance variable not being saved, reverts to 0s - oop

I am struggling to understand why my instance variables not being saved. Whenever I make a change to CurrentSettings, it does not appear next time I call another function. Basically it does not save and reverts to 0s after each function.
classdef laserControl
%LASERCONTROL This module is designed to control the laser unit.
% It can set the filter position, open and close the shutter and turn
% on/off the laser.
%
%%%%%%%%%%PORT LISTINGS%%%%%%%%%%%
%The set filter command is on port0
%The set shutter is in port1
%Laser 1 on port2
%Laser 2 on port3
%The filter digits are on ports 8-15 (the are on the second box)
properties%(GetAccess = 'public', SetAccess = 'private')
laserPorts; %The #'s of the output ports
currentSettings; %Current high/low settings
dio;
end
methods
%Constructor
%Opens the connection with the digital outputs
%Make sure to close the connection when finished
function Lobj = laserControl()
%Setup the laser
Lobj.laserPorts = [0:3 8:15];% 8:15
Lobj.currentSettings = zeros(1, length(Lobj.laserPorts));
%Make connection and reset values
Lobj.dio = digitalio('nidaq','Dev1');
addline(Lobj.dio, Lobj.laserPorts, 'out');
putvalue(Lobj.dio, Lobj.currentSettings);
end
%Closes the connection to the digital output
function obj = CloseConnection(obj)
putvalue(obj.dio, zeros(1, length(obj.currentSettings)));
delete(obj.dio);
clear obj.dio;
end
%Sets the position of the filter.
%positionValue - the integer amount for the position, cannot be
%larger than 150, as regulated by the box.
%The set filter command is on port0
%The filter digits are on ports 8-15 (the are on the second box)
function obj = SetFilterPosition(obj, positionValue)
if 0 <= positionValue && positionValue < 150
binaryDigit = de2bi(positionValue); %Convert it to binary form
%LaserOn OldSettings NewValue ExtraZeros
obj()
obj.currentSettings()
obj.currentSettings = [1 obj.currentSettings(1, 2:4) binaryDigit...
zeros(1, 8 - length(binaryDigit))];
putvalue(obj.dio, obj.currentSettings);
else
display('Error setting the filer: Value invalid');
end
end
end

Because your class does not inherit from handle, you've written a "value"-type class - in other words, when you make changes, you must capture the return value, like so:
myObj = SetFilterPosition( myObj, 7 );
For more on handle and value classes, see the doc

Related

Calling (importing) other .lua files outside main.lua in Love2D

So, I wanted to clean up my code by splitting it into seperate files. But for some reason I can't call the script I want to call through my main.lua.
Here's my main.lua script:
function love.load()
require "splash.lua"
splash.load()
end
function love.update(dt)
splash.update(dt)
end
function love.draw() print("Draw")
splash.draw()
love.graphics.print("FPS "..tostring(love.timer.getFPS( )), 5, 5) print("fps")
love.graphics.setColor(255,0,0) --Red
love.graphics.rectangle("fill", 3, 3, 60, 20)
end
And here's my splash.lua script, separate from the main.lua file:
function splash.load()
timer = 0 print("fadein")
alpha = 0
fadein = 2
display = 4
fadeout = 6
splashScreen = love.graphics.newImage("/images/Splash1.png")
end
function splash.update(dt)
timer = timer + dt
if 0 < timer and timer < fadein then
alpha = timer / fadein
end
if fadein < timer and timer < display then
alpha = 1
end
if display < timer and timer < fadeout then
alpha = 1 - ((timer - display) / (fadeout - display))
end
end
function splash.draw()
love.graphics.setColor(1, 1, 1, alpha)
local sx = love.graphics.getWidth() / splashScreen:getWidth()
local sy = love.graphics.getHeight() / splashScreen:getHeight()
love.graphics.draw(splashScreen, 0, 0, 0, sx, sy)
end
I've searched everywhere on this topic, and the other answers are either extremely vague or outdated. All I want to do is to make the splash.lua run when I start Love.
There were two problems which I noticed and once I fixed them something ran.
Problem 1
In main.lua, require "splash.lua" should be require "splash". If you code in other languages like python, java or javascript, you can think of require as similar to import.
Problem 2
In splash.lua, you are referencing an object(splash) which doesn't exist. To keep your code as similar as I could, I inserted the line splash = {} at the top of splash.lua. Once the object splash is created, you are then able to create functions for this object(splash.load(), splash.update(), and splash.draw()). This isn't a problem in main.lua because love is an object which already exists when the love2d game engine starts.
main.lua
function love.load()
require "splash"
splash.load()
end
function love.update(dt)
splash.update(dt)
end
function love.draw() print("Draw")
splash.draw()
love.graphics.print("FPS "..tostring(love.timer.getFPS( )), 5, 5) print("fps")
love.graphics.setColor(255,0,0) --Red
love.graphics.rectangle("fill", 3, 3, 60, 20)
end
splash.lua
splash = {}
function splash.load()
timer = 0 print("fadein")
alpha = 0
fadein = 2
display = 4
fadeout = 6
splashScreen = love.graphics.newImage("/images/Splash1.png")
end
function splash.update(dt)
timer = timer + dt
if 0 < timer and timer < fadein then
alpha = timer / fadein
end
if fadein < timer and timer < display then
alpha = 1
end
if display < timer and timer < fadeout then
alpha = 1 - ((timer - display) / (fadeout - display))
end
end
function splash.draw()
love.graphics.setColor(1, 1, 1, alpha)
local sx = love.graphics.getWidth() / splashScreen:getWidth()
local sy = love.graphics.getHeight() / splashScreen:getHeight()
love.graphics.draw(splashScreen, 0, 0, 0, sx, sy)
end
Side note: from reading your code, I'm not sure if you understand entirely how the load, update, and draw functions work. Love is an object created by the love2d game engine. The engine runs the load function only once when the game starts. The update function then continually checks for changes to the world that the game exists in and applies the code within love.update according to the conditions inside it. The draw function continually draws what it is told over and over again. These things happen automatically because it's already programmed into the love2d game engine.
The only reason I think you might be confused in this area is that you created a separate splash.load, splash.update, and splash.draw. You can technically name whatever functions you're calling anything you want, I just had the feeling that you might think that these load, update and draw functions might be called automatically, which they're not. Love2d only calls the load, update, and draw functions automatically for the love object.
Changing your require command to the following should work:
require("splash")
Additionally you should create the splash table before creating functions for said table.
splash = {}
splash.myFunction()
.
.
.

How would I rotate a character based on their camera? (Roblox)

In Roblox, your camera has a CFrame with a lookVector and so on. What I'm trying to accomplish is to detect when a player has pressed their right mouse button, and through a loop, rotate their character based on the CFrame of the camera until the button is released.
I've pretty much got it, but instead of rotating the character model, it turns the screen black and kills the player. I've seen this done in RPGs on Roblox before, so I know it's possible, and probably fairly easy. I've worked with CFrames quite a bit in the past, so I'm not sure why I'm having such a hard time with this.
After a couple hours of playing around with ideas and checking online, I thought I'd just ask the question to save time. What's the correct way to achieve this?
Edit: My bad, this is what I have so far. I fixed the black screen, but the player still just dies.
local UIS,Player,Camera,Character,MB2Down = game:GetService('UserInputService'),game.Players.LocalPlayer,workspace.Camera,script.Parent,false
local Torso = Character:FindFirstChild('Torso') or Character:FindFirstChild('UpperTorso')
UIS.InputEnded:Connect(function(Input)
if Input.UserInputType == Enum.UserInputType.MouseButton2 and MB2Down then
MB2Down = false
Character.Humanoid.AutoRotate = true
end
end)
UIS.InputBegan:connect(function(Input,onGui)
if Input.UserInputType == Enum.UserInputType.MouseButton2 and not onGui then
MB2Down = true
Character.Humanoid.AutoRotate = false
while MB2Down and wait() do
Torso.CFrame = CFrame.new(Vector3.new(Torso.CFrame),Vector3.new(Camera.CFrame.p))
end
end
end)
You've almost got it, but let me take a slightly different approach to my solution. When the player presses the right mouse button, let's connect a function to the Heartbeat event that will update the character's rotation to the camera's. Also, we will rotate the HumanoidRootPart instead of the Torso/UpperTorso. The HumanoidRootPart is the PrimaryPart of the character model, and thus is the part we should manipulate if we want to manipulate the model as a whole.
The way we will lock the player's rotation to the camera is as follows:
Get the position of the character.
Get the rotation of the camera (by using arc-tangent and camera's look-vector).
Construct the new CFrame for the player using the position and rotation from steps 1 and 2.
Apply the CFrame to the character's HumanoidRootPart.
The following code is in a LocalScript and is placed under StarterCharacterScripts:
local userInput = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local character = script.Parent
local root = character:WaitForChild("HumanoidRootPart")
local humanoid = character:WaitForChild("Humanoid")
local camera = workspace.CurrentCamera
local dead = false
local heartbeat = nil
function LockToCamera()
local pos = root.Position
local camLv = camera.CFrame.lookVector
local camRotation = math.atan2(-camLv.X, -camLv.Z)
root.CFrame = CFrame.new(root.Position) * CFrame.Angles(0, camRotation, 0)
end
userInput.InputEnded:Connect(function(input)
if (input.UserInputType == Enum.UserInputType.MouseButton2 and heartbeat) then
heartbeat:Disconnect()
heartbeat = nil
humanoid.AutoRotate = true
end
end)
userInput.InputBegan:Connect(function(input, processed)
if (processed or dead) then return end
if (input.UserInputType == Enum.UserInputType.MouseButton2) then
humanoid.AutoRotate = false
heartbeat = game:GetService("RunService").Heartbeat:Connect(LockToCamera)
end
end)
humanoid.Died:Connect(function()
dead = true
if (heartbeat) then
heartbeat:Disconnect()
heartbeat = nil
end
end)
Let me know if you need any clarification.

macOS Sierra: Emulate Mouse Down and Up

after an update to Sierra I had to find that Karabiner is not working anymore, which could emulate pointer clicks really well.
Any chance to get that via Swift or Apple Script or Obj.C ?
Background: Using Karabiner(and seil) I could bind caps-lock + d down and up to mouse down and up and in between the trackpad movement was understood. My trackpad is not processing keypress anymore but works still fine for pointer moves.
Answering myself, hacked it in hammerspoon. Was quite tricky to get chrome select working, maybe it saves somebody an hour or two:
1 ~/.hammerspoon $ cat init.lua
--[[ Left Keyboard Mouse (alt-d)
The main problem was to get chrome based apps select text when we drag via
keyboard.
You MUST return true always in the handle_drag otherwise it fails to select.
FF works, terminal works, chrome apps (atom, ...) don't.
But true is preventing further processing of the drag coords,
hs.mouse.getAbsolutePosition remains constant while dragging (!)
=> i.e. we MUST calc them via DeltaX, DeltaY, see below.
--]]
hs.alert.show("Config loaded")
-- all mechanics stolen from here:
-- local vimouse = require('vimouse')
-- vimouse('cmd', 'm')
now = hs.timer.secondsSinceEpoch
evt = hs.eventtap
evte = evt.event
evtypes = evte.types
evp=evte.properties
drag_last = now(); drag_intv = 0.01 -- we only synth drags from time to time
mp = {['x']=0, ['y']=0} -- mouse point. coords and last posted event
l = hs.logger.new('keybmouse', 'debug')
dmp = hs.inspect
-- The event tap. Started with the keyboard click:
handled = {evtypes.mouseMoved, evtypes.keyUp }
handle_drag = evt.new(handled, function(e)
if e:getType() == evtypes.keyUp then
handle_drag:stop()
post_evt(2)
return nil -- otherwise the up seems not processed by the OS
end
mp['x'] = mp['x'] + e:getProperty(evp.mouseEventDeltaX)
mp['y'] = mp['y'] + e:getProperty(evp.mouseEventDeltaY)
-- giving the key up a chance:
if now() - drag_last > drag_intv then
-- l.d('pos', mp.x, 'dx', dx)
post_evt(6) -- that sometimes makes dx negative in the log above
drag_last = now()
end
return true -- important
end)
function post_evt(mode)
-- 1: down, 2: up, 6: drag
if mode == 1 or mode == 2 then
local p = hs.mouse.getAbsolutePosition()
mp['x'] = p.x
mp['y'] = p.y
end
local e = evte.newMouseEvent(mode, mp)
if mode == 6 then cs = 0 else cs=1 end
e:setProperty(evte.properties.mouseEventClickState, cs)
e:post()
end
hs.hotkey.bind({"alt"}, "d",
function(event)
post_evt(1)
handle_drag:start()
end
)
and alt I mapped to capslock via karabiner elements.

Loop Through Array of Labels Using Temp Variable

I've got a 2D array of 100 labels in a 10x10 matrix (it's 2D because it represents some hardware out in the real world, if anyone cares). I want to loop through and check a conditional, and change the label background color if the conditional is false.
I've tried this ten different ways, but I keep getting an exception thrown because the temp variable I have created won't take an assignment to one of the label names.
'Table for correct switch module for corresponding actuator
Dim ActLabelLookup(,) As Label =
{{MTA91, MTA92, MTA93, MTA94, MTA95, MTA96, MTA97, MTA98, MTA99, MTA100},
{MTA81, MTA82, MTA83, MTA84, MTA85, MTA86, MTA87, MTA88, MTA89, MTA90},
{MTA71, MTA72, MTA73, MTA74, MTA75, MTA76, MTA77, MTA78, MTA79, MTA80},
{MTA61, MTA62, MTA63, MTA64, MTA65, MTA66, MTA67, MTA68, MTA69, MTA70},
{MTA51, MTA52, MTA53, MTA54, MTA55, MTA56, MTA57, MTA58, MTA59, MTA60},
{MTA41, MTA42, MTA43, MTA44, MTA45, MTA46, MTA47, MTA48, MTA49, MTA50},
{MTA31, MTA32, MTA33, MTA34, MTA35, MTA36, MTA37, MTA38, MTA39, MTA40},
{MTA21, MTA22, MTA23, MTA24, MTA25, MTA26, MTA27, MTA28, MTA29, MTA30},
{MTA11, MTA12, MTA13, MTA14, MTA15, MTA16, MTA17, MTA18, MTA19, MTA20},
{MTA1, MTA2, MTA3, MTA4, MTA5, MTA6, MTA7, MTA8, MTA9, MTA10}}
Private Sub UpdateActuatorStatus()
Dim X As Integer
Dim Y As Integer
Dim CurrAct As New Label
For X = 0 To (ActControl.MAX_X - 1)
For Y = 0 To (ActControl.MAX_Y - 1)
If TempFunctionalActuatorMatrix(X, Y) = False Then
CurrAct = ActLabelLookup(X, Y)
CurrAct.BackColor = Color.Firebrick
End If
Next
Next
End Sub
With this code, CurrAct is never getting set to anything. Anyone see what I'm doing wrong?
Your array isn't initialised (well, it is, but it is initialised with nothings as the labels are nothing as the form instance is created).
Try filling it before parsing (in Form Load or in UpdateActuatorStatus):
ActLabelLookup =
{{MTA91, MTA92, MTA93, MTA94, MTA95, MTA96, MTA97, MTA98, MTA99, MTA100},
{MTA81, MTA82, MTA83, MTA84, MTA85, MTA86, MTA87, MTA88, MTA89, MTA90},
{MTA71, MTA72, MTA73, MTA74, MTA75, MTA76, MTA77, MTA78, MTA79, MTA80},
{MTA61, MTA62, MTA63, MTA64, MTA65, MTA66, MTA67, MTA68, MTA69, MTA70},
{MTA51, MTA52, MTA53, MTA54, MTA55, MTA56, MTA57, MTA58, MTA59, MTA60},
{MTA41, MTA42, MTA43, MTA44, MTA45, MTA46, MTA47, MTA48, MTA49, MTA50},
{MTA31, MTA32, MTA33, MTA34, MTA35, MTA36, MTA37, MTA38, MTA39, MTA40},
{MTA21, MTA22, MTA23, MTA24, MTA25, MTA26, MTA27, MTA28, MTA29, MTA30},
{MTA11, MTA12, MTA13, MTA14, MTA15, MTA16, MTA17, MTA18, MTA19, MTA20},
{MTA1, MTA2, MTA3, MTA4, MTA5, MTA6, MTA7, MTA8, MTA9, MTA10}}
Change the member-level declaration of ActLabelLookup to just:
Dim ActLabelLookup(,) As Label
In the form's Load event handler add a line to initialize it:
ActLabelLookup(,) =
{{MTA91, MTA92, MTA93, MTA94, MTA95, MTA96, MTA97, MTA98, MTA99, MTA100},
{MTA81, MTA82, MTA83, MTA84, MTA85, MTA86, MTA87, MTA88, MTA89, MTA90},
{MTA71, MTA72, MTA73, MTA74, MTA75, MTA76, MTA77, MTA78, MTA79, MTA80},
{MTA61, MTA62, MTA63, MTA64, MTA65, MTA66, MTA67, MTA68, MTA69, MTA70},
{MTA51, MTA52, MTA53, MTA54, MTA55, MTA56, MTA57, MTA58, MTA59, MTA60},
{MTA41, MTA42, MTA43, MTA44, MTA45, MTA46, MTA47, MTA48, MTA49, MTA50},
{MTA31, MTA32, MTA33, MTA34, MTA35, MTA36, MTA37, MTA38, MTA39, MTA40},
{MTA21, MTA22, MTA23, MTA24, MTA25, MTA26, MTA27, MTA28, MTA29, MTA30},
{MTA11, MTA12, MTA13, MTA14, MTA15, MTA16, MTA17, MTA18, MTA19, MTA20},
{MTA1, MTA2, MTA3, MTA4, MTA5, MTA6, MTA7, MTA8, MTA9, MTA10}}

Key Releases Psychopy

I'm fairly new to psychopy but I'm having a lot of trouble recording keyboard events so far. The keyboard demo works so I know it is possible, but when I implement the code in my own program it doesn't record any keyboard activity at all. Right now my program is super simple as I'm just trying to get the hang of it. I have a picture and want to record the duration of keypresses during the time the picture is on screen. I have a couple print statements as sanity checks and when I run it (and am using the keyboard) it doesn't print anything. Here's an outline of my code:
from psychopy.iohub import launchHubServer, EventConstants
io = launchHubServer()
keyboard = io.devices.keyboard
keyboard.reporting = True
#-------Start Routine "trial"-------
continueRoutine = True
io.clearEvents('all')
duration_lst=[]
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image* updates
if t >= 0.0 and image.status == NOT_STARTED:
# keep track of start time/frame for later
image.tStart = t # underestimates by a little under one frame
image.frameNStart = frameN # exact frame index
image.setAutoDraw(True)
if image.status == STARTED and t >= (0.0 + (5.0- win.monitorFramePeriod*0.75)): #most of one frame period left
image.setAutoDraw(False)
# *ISI* period
if t >= 0.0 and ISI.status == NOT_STARTED:
# keep track of start time/frame for later
ISI.tStart = t # underestimates by a little under one frame
ISI.frameNStart = frameN # exact frame index
ISI.start(0.5)
elif ISI.status == STARTED: #one frame should pass before updating params and completing
ISI.complete() #finish the static period
# get keyboard events
for event in keyboard.getEvents():
print event
if event.type == EventConstants.KEYBOARD_CHAR:
key_press_duration=event.duration
duration_lst.append(key_press_duration)
print duration_lst
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
I tried stripping off all unnecessary stuff here (variables, window, stimuli etc.) and uses keyboard.getReleases() so it boils down to this:
from psychopy import iohub
io = iohub.launchHubServer()
keyboard = io.devices.keyboard
print 'press something now!'
while True:
# get keyboard releases
for event in keyboard.getReleases():
print 'Released!'
This should print all info about each key release in the console. It works for me, at least. If it also works for you, the problem is probably related to something else in your script.