Loop help (roblox) - loops

I have a problem with this script:
local plight = script.Parent.Bulb.PointLight
local slight = script.Parent.Bulb.SpotLight
local rotatingPart = script.Parent.Bulb
local reader = script.Parent.Parent["card-reader1a"].reader1a.ProximityPrompt
local c = 0
local cc = 0
local tweenService = game:GetService("TweenService")
local tInfo = TweenInfo.new(0.5, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false)
local function rotating()
if c == 0 then
c = 1
local play1 = tweenService:Create(rotatingPart, tInfo, {CFrame = rotatingPart.CFrame * CFrame.Angles(0, math.rad(120), 0)})
play1:Play()
play1.Completed:Connect(rotating)
c = 0
end
end
reader.Triggered:Connect(rotating)
I have infinitive loop and I don't know how to stop it. I tried many methods and nothing worked. Can someone help?

Try removing
play1.completed:Connect(rotating)
This line of code means that upon the tween's completion fire the rotating function. Effectively causing an infinite loop.
Additionally since :Connect() a signal doesn't yield, every time rotating is called, c is set from 1 to 0 almost instantaneously. Which allows all calls to pretty much bypass the debounce.
If you wish to wait until the tween is complete, try using
play1.completed:Wait()

Related

iOS9 Beta and MusicTrackLoopInfo

Has anyone been able to loop a MIDI file without problems on IOS9 Beta?
As soon as I try to loop by setting numberOfLoops to 0 in MusicTrackLoopInfo, it locks up the app by sending random MIDI to the player. I've reported it, but am wondering if anyone has found a work around. The same code works perfectly under all other iOS versions.
MusicTrackLoopInfo loopInfo;
loopInfo.loopDuration = loopLength;
loopInfo.numberOfLoops = 0;
OK I just heard iOS9 will ship with this bug in it. Terrible.
Here is a work around.
Don't set numberOfLoops at all, OR set numberOfLoops = 1; // means loop once
Now make a variable (i.e. myVariableToKeepTrackOfAddedCopies) that keeps track of the number of times you will actually perform the following:
In your MIDIReadProc at some point BEFORE the track has finished playing, do the following:
// Copy the track to itself - effectively doubling the length
MusicTrack theTrack=nil;
MusicTrackGetProperty(theTrack, kSequenceTrackProperty_TrackLength, &trackLen, &trackLenLen);
trackLen = 4.0; //<-- this is your real track length
MusicTrackCopyInsert(theTrack, 0, trackLen, theTrack, 0);
myVariableToKeepTrackOfAddedCopies++;
So now your track is twice as long before it ends and the track will continue. This will work the same as looping except you are taking up more memory since you are making the track length longer after each iteration.
When you stop the sequence/track, cut the track back to the original size.
MusicTrackCut(theTrack, 4.0, 4.0 + (4.0*myVariableToKeepTrackOfAddedCopies));
MusicTrackGetProperty(theTrack, kSequenceTrackProperty_TrackLength, &trackLen, &trackLenLen);
Irritating, but it works. I just verified on iOS9 beta 5. Hope it helps.
This is fixed as of iOS release 9.2
Oddly enough, the tempo track does not seem to have this problem. The following code does not lock up for me:
MusicTrack tempoTrack;
OSSTATUS = MusicSequenceGetTempoTrack(self.sequence, &tempoTrack);
SafeMusicTrackClear(tempoTrack); //calls into MusicTrackClear
MusicTrackNewExtendedTempoEvent(tempoTrack, 0, self.tempo * self.tempoMultiplier);
MIDIMetaEvent timeSignatureMetaEvent;
timeSignatureMetaEvent.metaEventType = 0x58;
timeSignatureMetaEvent.dataLength = 4;
timeSignatureMetaEvent.data[0] = 1;
timeSignatureMetaEvent.data[1] = 4;
timeSignatureMetaEvent.data[2] = 0x18;
timeSignatureMetaEvent.data[3] = 0x08;
MusicTrackNewMetaEvent(tempoTrack, 0, &timeSignatureMetaEvent);
MusicTrackLoopInfo loopInfo;
loopInfo.loopDuration = 0.25f;
loopInfo.numberOfLoops = 0;
MusicTrackSetProperty(tempoTrack, kSequenceTrackProperty_LoopInfo, &loopInfo, sizeof(loopInfo));
Unfortunately, it does not seem that the tempo track can actually play notes.
UPDATE:
After a few hours of digging around and trying to figure out a better solution to the problem, I settled on manually looping by sending a user event at the end of my sequence.
My sequence is created in a method...
-(void) loadPacketsForLoopingSequence {
SafeMusicTrackClear(loopingTrack); //calls into MusicTrackClear
// calculate timestampToPlaySequenceAt -- the starting point of the current sequence iteration, probably in the past, based on MusicPlayerGetTime and the length of the sequence -- here
// calculate timestampToPlayNextSequenceAt -- the starting point of the next sequence iteration, based on MusicPlayerGetTime and the length of the sequence -- here
// a single iteration of the notes get added to loopingTrack here, starting at timestampToPlaySequenceAt
MusicEventUserData event;
event.length = 1;
event.data[0] = 0xab; //arbitrary designation
// -0.5 to make sure we still have time to do the next step in the callback
MusicTrackNewUserEvent(loopingTrack, timestampToPlayNextSequenceAt - 0.5, &event);
}
...which is called again in the callback:
void sequenceCallback(void* inClientData,
MusicSequence inSequence,
MusicTrack inTrack,
MusicTimeStamp inEventTime,
const MusicEventUserData* inEventData,
MusicTimeStamp inStartSliceBeat,
MusicTimeStamp inEndSliceBeat) {
CSMidiMusicPlayer* musicPlayer = (CSMidiMusicPlayer*)inClientData;
[musicPlayer loadPacketsForLoopingSequence];
}
The callback has to be registered during sequence init using MusicSequenceSetUserCallback.
The -0.5 kludge could probably be eliminated altogether by examining the parameters in sequenceCallback and modifying loadPacketsForLoopingSequence to accept a parameter, but I haven't gotten that far yet.
I like this solution because it stays in MIDI time and doesn't modify the MIDI file in unexpected, stateful ways. (New notes basically get streamed in when you get close enough to a loop marker.)

GetThreadTimes( ) returning 0 (zero) as the kernel and user time for all the threads

I was trying to get CPU utilization for particular thread by using GetThreadTimes, however for all threads kernel and user time getting equated to zero.
Note:thread is getting created by _beginthreadex.
(dThreadID->hThread = (HANDLE) _beginthreadex(NULL, 0,
(LPTHREAD_START_ROUTINE)threadFunc, threadParam, 0,
&(dThreadID->threadID));)
is this case anything to do with security attributes of _beginthreadex?
Please let me know how to resolve this case.
Thanks in advance
Code:
I am calling this inside a static function so pasting the same.
threadId = GetCurrentThreadId();
curThread = GetCurrentThread();
GetThreadTimes(curThread, &ftCreation, &ftExit, &ftKernel, &ftUser);
GetSystemTimes(&ftidle, &ftKernelCpu, &ftUserCpu);
ftSysKernelDiff = SubtractTimes(&ftKernelCpu, &ftKernelCpu_old);
ftSysUserDiff = SubtractTimes(&ftUserCpu, &ftUserCpu_old);
ftProcKernelDiff =SubtractTimes(&ftKernel, &ftKernel_old);
ftProcUserDiff =SubtractTimes(&ftUser, &ftUser_old);
nTotalSys = ftSysKernelDiff + ftSysUserDiff;
nTotalProc = ftProcKernelDiff + ftProcUserDiff;
nCpuUsage = (short)((100.0 * nTotalProc) / nTotalSys);

Lua determining when out of range

I have a function called preprocess. It looks like this
function image_utils.preprocess(meanfile, oneD_image_table)
local img_mean = torch.load(meanfile).img_mean:transpose(3,1)
return function()
for t_class, img_path in pairs(oneD_image_table) do
local im3 = image.load(img_path)
local im4 = image.scale(im3,227,227,'bilinear')*25
return im4 - image.scale(img_mean, 227, 227, 'bilinear')
end
end
Here's how I call it:
im_f = image_util.preprocess(meanfile, path_list)
repeat
im=im_f()
batch[count]:copy(im)
count = count + 1
until count == batchSize
This works. However, I would like to be detect when im_f doesn't have any more iterations left and use that to determine when I should stop looping.In other words, something like this:
repeat
im = im_f()
count = count+1
batch[count] = im
until im == nil (or im is some sentinel value that tells me to stop)
However, I have not been able to make this work due to out of range error.
In short, I want to loop until im_f tells me to stop; rather than using a predetermined number to tell me when to stop.

How to call an m file from another m file in MATLAB and retrieve an output?

I know this is a simple question, but for some reason I can't find a straight answer that works no matter where I look.
Basically, I have 4 values that were found in one m file, and I want to run them through a separate m file and retrieve the output from it.
I tried something like these, but none worked:
result = generate(nrow,ncol,a,b);
function result = generate(nrow,ncol,a,b);
result = #generate(nrow,ncol,a,b);
The final value in the m file "generate" is called result, and I'm trying to carry that across to my initial m file.
Any advice as to what I'm doing wrong would be greatly appreciated! Please and thank you
if your file generate.m defines a function it should have itself the following structure (which takes into account the fact that you have four returned values)
function [ret1 ret2 ret3 ret4] = generate(nrow,ncol,a,b)
.... % # Some processing of yours
ret1 = ... ; % # Returned values are eventually set
ret2 = ... ;
ret3 = ... ;
ret4 = ... ;
end
The function should be called (e.g. in your main script) as
[ret1 ret2 ret3 ret4] = generate(nrow,ncol,a,b);
now you have the variables ret1,ret2,ret3,ret4 available in the caller scope.
Be aware that the file generate.m must be in the current matlab PATH.

Matlab, timed iteration over a matrix

I'm developing a simulator of sorts as a hobby project. The specific function i'm having trouble with takes a row from a matrix and supplies to a function every 50'th millisecond, but I'm a novice with Matlab scripting and need some help.
Each time the timer clicks, the next row in the matrix should be supplied to the function "simulate_datapoint()". Simulate_datapoint() takes the row, performs some calculation magic and updates a complex "track" object in the tracks array.
Is this a completely backwards way of trying to solve this problem or am I close to a working solution? Any help would be greatly appreciated.
Here's what I have right now that doesn't work:
function simulate_data(data)
if ~ismatrix(data)
error('Input must be a matrix.')
end
tracks = tracks_init(); % create an array of 64 Track objects.
data_size = size(data,1); % number of rows in data.
i = 0;
running = 1;
t = timer('StartDelay', 1, 'Period', 0.05, 'TasksToExecute', data_size, ...
'ExecutionMode', 'fixedRate');
t.StopFcn = 'running = 0;';
t.TimerFcn = 'i = i+1; simulate_datapoint(tracks, data(i,:));';
disp('Starting timer.')
start(t);
while(running==1)
% do nothing, wait for timer to finish.
end
delete(t);
disp('Execution complete.')
end
You're very close to a working prototype. A few notes.
1) Your string specified MATLAB functions for the timerFn and stopFn don't share the same memory address, so the variable "i" is meaningless and not shared across them
2) Use waitfor(myTimer) to wait... for the timer.
The following code should get you started, where I used "nested functions" which do share scope with the calling function, so they know about and share variables with the calling scope:
function simulate
iterCount = 0;
running = true;
t = timer('StartDelay', 1, 'Period', 0.05, 'TasksToExecute', 10, ...
'ExecutionMode', 'fixedRate');
t.StopFcn = #(source,event)myStopFn;
t.TimerFcn = #(source,event)myTimerFn;
disp('Starting timer.')
start(t);
waitfor(t);
delete(t);
disp('Execution complete.')
% These are NESTED functions, they have access to variables in the
% calling function's (simulate's) scope, like "iterCount"
% See: http://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html
function myStopFn
running = false;
end
function myTimerFn
iterCount = iterCount + 1;
disp(iterCount);
end
end

Resources