How to add a "sleep" or "wait" to my Lua Script? - timer

I'm trying to make a simple script for a game, by changing the time of day, but I want to do it in a fast motion. So this is what I'm talking about:
function disco ( hour, minute)
setTime ( 1, 0 )
SLEEP
setTime ( 2, 0 )
SLEEP
setTime ( 3, 0 )
end
and so on. How would I go about doing this?

Lua doesn't provide a standard sleep function, but there are several ways to implement one, see Sleep Function for detail.
For Linux, this may be the easiest one:
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
In Windows, you can use ping:
function sleep(n)
if n > 0 then os.execute("ping -n " .. tonumber(n+1) .. " localhost > NUL") end
end
The one using select deserves some attention because it is the only portable way to get sub-second resolution:
require "socket"
function sleep(sec)
socket.select(nil, nil, sec)
end
sleep(0.2)

If you have luasocket installed:
local socket = require 'socket'
socket.sleep(0.2)

This homebrew function have precision down to a 10th of a second or less.
function sleep (a)
local sec = tonumber(os.clock() + a);
while (os.clock() < sec) do
end
end

wxLua has three sleep functions:
local wx = require 'wx'
wx.wxSleep(12) -- sleeps for 12 seconds
wx.wxMilliSleep(1200) -- sleeps for 1200 milliseconds
wx.wxMicroSleep(1200) -- sleeps for 1200 microseconds (if the system supports such resolution)

I know this is a super old question, but I stumbled upon it while I was working on something. Here's some code that's working for me...
time=os.time()
wait=5
newtime=time+wait
while (time<newtime)
do
time=os.time()
end
And I needed randomization so I added
math.randomseed(os.time())
math.random(); math.random(); math.random()
randwait = math.random(1,30)
time=os.time()
newtime=time+randwait
while (time<newtime)
do
time=os.time()
end

I needed something simple for a polling script, so I tried the os.execute option from Yu Hao's answer. But at least on my machine, I could no longer terminate the script with Ctrl+C. So I tried a very similar function using io.popen instead, and this one does allow early termination.
function wait (s)
local timer = io.popen("sleep " .. s)
timer:close()
end

You should read this:
http://lua-users.org/wiki/SleepFunction
There are several solutions and each one has a description, which is important to know.
This is, what I used:
function util.Sleep(s)
if type(s) ~= "number" then
error("Unable to wait if parameter 'seconds' isn't a number: " .. type(s))
end
-- http://lua-users.org/wiki/SleepFunction
local ntime = os.clock() + s/10
repeat until os.clock() > ntime
end

if you're using a MacBook or UNIX based system, use this:
function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()

You can use "os.time" or "os.clock" with "while" loop, i prefer "repeat until" loop because its shorter, but they are expensive because they cost full usage of a single core.
If you need something less demanding, you can use various wrappers like wxLua that i use, but sometimes, some of them also got usage penalty, specially annoying in games, so its best to test them and get what is best for your project.
Or you can relay on OS like Windows to do sleep function, using applications that exist in system32, via Batch or PowerShell, using ">nul" to hide it with "os.execute" or "io.popen", like "ping" (localhost/127.0.0.1) with timeout, "choice" (works with XP, newer versions may be different, i prefer it), "timeout" (/nobreak may be useless because all Windows commands can be canceled with CTRL+C). Downside are limited to given OS and number limitation as well as seconds or miliseconds, running it on eg. Linux may need Wine emulation for Windows (if application are written for it). You can also use "sleep" or "start-sleep" (from PowerShell), but since Lua are standalone, most people prefer pure Lua or wrappers, and you can use what suits your project.

function wait(time)
local duration = os.time() + time
while os.time() < duration do end
end
This is probably one of the easiest ways to add a wait/sleep function to your script

Related

CommandSequence taking too long to download

With both DKPy-SITL and our APM2 board, the wait_ready method is causing our program to raise an API Exception due to the command list (waypoints) taking too long to download. In the past (with droneapi) this wasn't an issue for me. Some waypoints are being downloaded, but the process takes about 10 seconds for each one, which leads me to believe something weird is going on.
Are there any ways to speed up the download process? I've posted the relevant code below.
self.vehicle = connect(connection_string, baud=baud_rate,
status_printer=dronekit_printer, wait_ready=True)
and later in another asynchronous method
def commands(self):
commands = self.vehicle.commands
commands.download()
commands.wait_ready()
return commands
The error occurs on commands.wait_ready(). There has to be a faster way to download commands than sitting there for over 30 seconds on an i7 4790k processor, especially since I've run the same code off a slower computer in the past with droneapi. If need be, I can raise an issue on the dronekit github as well.
I had the same issue. First time download call always goes well (0 commands). Once you have uploaded some commands the second time you try to download it fails ('Timeout' exception).
What I did to solve this was calling clear without download after the first time.
Something like this:
cmds = vehicle.commands
if not cmds.count > 0:
# Download
cmds.download()
# Wait until download is finished
cmds.wait_ready()
cmds.clear()
# Add / Modify the commands here and then upload them

Julia parallel file processing

I'm relatively new to Julia language, and I 've been recently trying to process some files in parallel manner. My code looks something like>
for ln in eachline (somefile)
...
proces this line
for ln2 in eachline (someotherfile)
..
..
process ln and ln2
..
..
I've been trying to speed things up a bit with #everywhere and #parallel functions, but it doesn't seem to work for eachline function.
Am I missing something?
Thanks for help.
From #parallel macro we already know that:
#parallel [reducer] for var = range
body
end
The specified range is partitioned and locally executed across all workers.
To do the above job in minimum time, #parallel gets length(range) then partitions it between nworkers().
for more details you can:
. see macro output -> macroexpand(:(#parallel for i in 1:5 i end))
or:
. check macro source -> milti.jl
EachLine is one of Julia iterables, it implements all mandatory methods of iterable interface, but length() is not one of those. (check this discussion), so EachLine is not a range and #parallel fails to do it's task because lack of length() function.
But there are at list two solutions to parallelize the process part:
use lis=readlines() to collect a range of lines, the #parallel for li in lis
use pmap()
Julia’s pmap() (page 483) is designed for the case where each function
call does a large amount of work. In contrast, #parallel for can
handle situations where each iteration is tiny, perhaps merely summing
two numbers.
a sample code:
len=function(s::AbstractString)
string(length(s)) * " " * string(myid());
end
function test()
open("eula.1028.txt") do io
pmap(len,eachline(io))
end
end

tcl multithreading like in c, having hard time to execute thread with procedure

I used to work in C, where threads are easy to create with a specific function I choose.
Now in tcl I can't use thread to start with a specific function I want, I tried this:
package require Thread
proc printme {aa} {
puts "$aa"
}
set abc "dasdasdas"
set pool [tpool::create -maxworkers 4 ]
# The list of *scripts* to evaluate
set tasks {
{puts "ThisisOK"}
{puts $abc}
{printme "1234"}
}
# Post the work items (scripts to run)
foreach task $tasks {
lappend jobs [tpool::post $pool $task]
}
# Wait for all the jobs to finish
for {set running $jobs} {[llength $running]} {} {
tpool::wait $pool $running running
}
# Get the results; you might want a different way to print the results...
foreach task $tasks job $jobs {
set jobResult [tpool::get $pool $job]
puts "TASK: $task"
puts "RESULT: $jobResult"
}
I always get:
Execution error 206: invalid command name "printme"invalid command name "printme"
while executing
"printme "1234""
invoked from within
"tpool::get $pool $job"
Why?
You problem is, that the Tcl threading model is very different from the one used in C. Tcl's model is a basically 'shared nothing by default' model mostly based on message passing.
So every thread in the pool is an isolated interpreter and does not know anything about a proc printme. You need to initialize those interpreters with the procs you need.
See the docs for the ::tpool::create command, it has an option to provide a -initcmd where you can define or package require the stuff you need.
So try this to initialize your threads:
set pool [tpool::create -maxworkers -initcmd {
proc printme {aa} {
puts "$aa"
}}]
https://www.tcl.tk/man/tcl/ThreadCmd/tpool.htm#M10
To answer your comment a bit more detailed:
No, there is no way to make Tcl threads work like C threads and share objects and procs freely. It is a fundamental design decision and allows Tcl to have an interpreter without a massive global lock (in contrast to e.g. CPython), as most things are thread local and use thread local storage.
But there are some ways to make initialization and use of multiple thread interpreters easier. One is the -initcmd parameter from ::tpool::create which allows you to run initialization code for every single interpreter in your pool without doing it manually. If all your code lives in a package, you simply add a package require and your interpreter is properly initialized.
If you really want to share state between multiple threads, you can use the ::tsv subcommands. It allows you to share arrays and other things between threads in an explict way. But under the hood it involves the typical locks and mutexes you might know from C to mediate access.
There is another set of commands in the thread package that allow you to make initialization easier. This is the ttrace command, which allows you to simply trace what gets executed in one interpreter and automatically repeat it in another interpreter. It is quite smart and only shares/copies the procs you really use to the target instead of loading all things upfront.

Python: How to pause a while True loop?

So I'm making a python version of cookie clicker :D
To add the cps to the cookies counter, I use this code:
while True:
cps = b1*1 + b2*5 + b3*10 + b4*20 + b5*25
c=c+cps
time.sleep(60)
print('you now have %s cookies' %c)
note: the b1, b2 etc and the amounts of different cookie producers
Problem is, the time.sleep pauses the whole script, not just the while loop you can see above
BTW this is my first post, sorry if I did something wrong :/
Thanks for reading this :P
You can make a method for this loop then start a new thread for this after that you can just simply cal .sleep() which will only make that thread suspend for the given time not the whole code.
Check the Link it will help about multi-threading.
import threading
def worker():
"""your code in this method"""
t = threading.Thread(target=worker)
t.start()
AS far as i can see you have two options:
You measure the time between each call to update the cookieamount c and multiply it accordingly.
You make a new thread. Then sleep will just pause your thread to update your cookieamount.

both video & audio run as fast as possible - ffmpeg

using this code example (dranger - ffmpeg):
https://github.com/arashafiei/dranger-ffmpeg-tuto/blob/master/tutorial03.c
and dranger tutorial for ffmpeg:
http://dranger.com/ffmpeg/tutorial02.html
The video runs as fast as possible but it makes sense because there is no timer and we just extract the frames as soon as we have them ready. But for some reason, the sound also runs as fast as possible even though he says that it shouldn't.
I'm using mac os x (Maybe that has something to do with it).
Any suggestions?
Try adding:
aCodecCtx = pFormatCtx->streams[audioStream]->codec;
> aCodecCtx->request_sample_fmt = AV_SAMPLE_FMT_S16;

Resources