I am trying to move the mouse every 2 minutes so that the session doesn't time out. But despite no syntax errors, it doesn't work.
My code:
global $x = 1
global $y = 1
If Mod(#MIN, 3) = 0 Then
MouseMove (global $x, global $y, 2)
global $x++
global $y++
endif
Its more usefull to perform a callback function for timed calls.
AdlibRegister('_MouseMove', 2000*60) ; calls the function every 2000*60 ms
OnAutoItExitRegister('_UnRegister') ; unregister the callback function when the script ends
Func _MouseMove()
Local $aPos = MouseGetPos()
; move 1px right and back after a short brake - so that your interface can detect the movement
MouseMove($aPos[0]+1, $aPos[1])
Sleep(50)
MouseMove($aPos[0], $aPos[1])
EndFunc
Func _UnRegister()
AdlibUnRegister('_MouseMove')
EndFunc
Btw.: Increasing values with AutoIt works so
$x += 1
Edit:
I'm not sure, if you want 2 or 3 minutes (you've written both). So you can change it in the time parameter in AdlibRegister(). The interval must given in ms.
When you run your script in SciTE you should see the following error message:
You need the global keyword only when declaring a variable. When using a variable you have to ommit the global keyword. You should change your script accordingly and it might work then.
The following script move the mouse one pixel every 3 minutes, preventing the session time out, with minimal impact on the computer usage.
HotKeySet( "{ESC}" , "Sair")
While True
MouseMove(MouseGetPos(0)+1,MouseGetPos(1))
Sleep(180000)
MouseMove(MouseGetPos(0)-1,MouseGetPos(1))
Sleep(180000)
WEnd
Func Sair()
Exit
EndFunc
Related
I want to have the possibility to stop a function launched by a button by pushing an other button. More precisely, I want to stop a while loop by changing a parameter :
stop=%F
while ... & stop<>%T
...
end
I tried to write a callback function that change a variable to stop the while :
function callback(handles)
stop=%T
end
but the action isn't triggered before the end of the previous one.
I guess there must be something to do with some threads but i don't have this knowledge in scilab.
You have two solutions. The first one with a prioritary expression callback:
b = uicontrol("style","pushbutton","callback","stop=%t","callback_type",10);
stop = %f;
while ~stop
sleep(1)
end
the second one with a prioritary function callback:
function fun()
stop = %t;
stop = resume(stop);
end
b = uicontrol("style","pushbutton","callback","fun","callback_type",12);
stop = %f;
while ~stop
sleep(1)
end
In the second case you have to use resume to return the local variable stop in the main workspace. Making callback prioritary is a must to interrupt waiting loops.
While memoization of a function is a good idea, it could cause a program to crash because the program could potentially run out of memory.
Therefore it is NOT A SAFE OPTION to be used in a production program.
Instead I have developed caching with a fixed memory slots below with a soft limit and hard limit. When the cache slots is above the hard limit, it will have the least used slots deleted until the number of slots is reduced to the soft limit.
struct cacheType
softlimit::Int
hardlimit::Int
memory::Dict{Any,Any}
freq::Dict{Any,Int}
cacheType(soft::Int,hard::Int) = new(soft,hard,Dict(),Dict())
end
function tidycache!(c::cacheType)
memory_slots=length(c.memory)
if memory_slots > c.hardlimit
num_to_delete = memory_slots - c.softlimit
# Now sort the freq dictionary into array of key => AccessFrequency
# where the first few items have the lowest AccessFrequency
for item in sort(collect(c.freq),by = x -> x[2])[1:num_to_delete]
delete!(c.freq, item[1])
delete!(c.memory, item[1])
end
end
end
# Fibonacci function
function cachefib!(cache::cacheType,x)
if haskey(cache.memory,x)
# Increment the number of times this key has been accessed
cache.freq[x] += 1
return cache.memory[x]
else
# perform housekeeping and remove cache entries if over the hardlimit
tidycache!(cache)
if x < 3
cache.freq[x] = 1
return cache.memory[x] = 1
else
result = cachefib!(cache,x-2) + cachefib!(cache,x-1)
cache.freq[x] = 1
cache.memory[x] = result
return result
end
end
end
c = cacheType(3,4)
cachefib!(c,3)
cachefib!(c,4)
cachefib!(c,5)
cachefib!(c,6)
cachefib!(c,4)
println("c.memory is ",c.memory)
println("c.freq is ",c.freq)
I think this would be most useful in a production environment than just using memorization with no limits of memory consumption which could result in a program crashing.
In Python language, they have
#functools.lru_cache(maxsize=128, typed=False)
Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.
Since a dictionary is used to cache results, the positional and keyword arguments to the function must be hashable.
Is there an equivalent in Julia language?
There is LRUCache.jl, which provides an LRU type which basically acts like a Dict. Unfortunately, this doesn't seem to work with the Memoize.jl package, but you can use my answer to your other question:
using LRUCache
const fibmem = LRU{Int,Int}(3) # store only 3 values
function fib(n)
get!(fibmem, n) do
n < 3 ? 1 : fib(n-1) + fib(n-2)
end
end
My AutoIt script should do a left click every 40 minutes inside a given time interval:
Func Main()
Run("kocske.jpg")
While 0 < 1
If CheckTime() == true Then
MouseClick("left")
EndIf
; Sleep for 40 minutes
Sleep(60000 * 40)
WEnd
EndFunc
; The function checks if the current time is between 17:00 and 20:00
Func CheckTime()
If #Hour >= 17 AND #Hour <= 20 Then
Return true
Else
Return false
EndIf
EndFunc
I saved it as .au3 file and compiled it to an executable. But when I run it, nothing happens (as if it never started).
I added Run("kocske.jpg") to test if the script starts at all, and placed a JPG file named "kocske.jpg" in the script's folder. It does not open the file, and the task manager does not show it running.
Why doesn't my script run?
I rewrote your program a bit to include usual habits (commented below)
Main() ; calls the Main() Function
Func Main()
ShellExecute("kocske.jpg") ; opens the image with it's default viewer; Note: you should add full path
While True
If CheckTime(17, 21) Then ; good habit to work with parameters; makes your function flexible
; probably you want to locate your mouse to a special location before clicking
; and also activate a certain application? Consider ControlClick()
MouseClick("left")
EndIf
Sleep(60000 * 40) ; Sleep for 40 minutes
WEnd
EndFunc ;==>Main
; The function checks if the current time is between 17:00 and 20:00 (19:59:59)
Func CheckTime($TimeA = 17, $TimeB = 20) ; defines default parameters, if they are not given
If #HOUR >= $TimeA And #HOUR < $TimeB Then Return True ; no Else needed
Return False
EndFunc ;==>CheckTime
Note: #HOUR < $TimeB instead of #HOUR <= $TimeB
Running functions
Why doesn't my script run?
Because functions are defined, but not called.
If you want Main() to be executed then add a line "Main()" outside of function definitions (global scope). Example (first line, as per Documentation - Keyword Reference - Func...Return...EndFunc):
Main()
Func Main()
Run("kocske.jpg")
While 0 < 1
If CheckTime() == true Then
MouseClick("left")
EndIf
; Sleep for 40 minutes
Sleep(60000 * 40)
WEnd
EndFunc
; The function checks if the current time is between 17:00 and 20:00
Func CheckTime()
If #Hour >= 17 AND #Hour <= 20 Then
Return true
Else
Return false
EndIf
EndFunc
Opening files
I added Run("kocske.jpg") to test if the script starts at all …
As per Documentation - Function Reference - Run():
Runs an external program.
"kocske.jpg" is not "an external program"; use ShellExecute("kocske.jpg") instead:
Runs an external program using the ShellExecute API.
Comparison operator
There is no differentiation for = -use between assignment and comparison (as per Documentation - Language Reference - Operators). Example:
; Equal sign (=) as assignment operator:
Global Const $g_bValue = True
; Equal sign (=) as comparison operator:
If $g_bValue = True Then; Or just: If $g_bValue Then
Beep(500, 1000)
EndIf
As per Documentation - Language Reference - Operators:
==Tests if two strings are equal. Case sensitive. The left and right values are converted to strings if they are not strings already. This operator should only be used if string comparisons need to be case sensitive.
I have a simple function like
function clearit() {
REM=$(($LINENO % $LINES))
DIV=$(($LINENO / $LINES))
if [[ $DIV -gt 0 && $REM -lt 3 && $DIV ]]; then
clear
fi
echo $LINENO, $LINES
}
add-zsh-hook preexec clearit
In the above function a static value of $LINE and $LINES is added to the prehook function. I want to get the current value when the prexec is executed. How can I do that ?
For normal shell variables, you will get the current value:
% x=1
% function test_hook() { echo $x; }
% add-zsh-hook preexec test_hook
% true
1
% x=2
1
% true
2
However, $LINENO is a very special variable. From the documentation:
LINENO <S>
The line number of the current line within the current script, sourced file, or shell function being executed, whichever was started most recently. Note that in the case of shell functions the line number refers to the function as it appeared in the original definition, not necessarily as displayed by the functions builtin.
When your hook function is executing, it is by definition the most recently started shell function, script or sourced file. So $LINENO always gives you the current line within your hook function. There is no way to access the $LINENO for the outer scope.
However, even if you could access the outer $LINENO in your hook, it would lead to very strange behaviour in my opinion. Let's say your terminal is 30 lines high ($LINES is 30), it would clear the terminal before executing the 30th, 31st and 32nd command, then nothing for the next 27 commands, then again clearing before the 60th, 61st and 62nd, and so on. I don't think this is remotely what you are trying to achieve...
My code for display all days in this year.
I don't understand why if NewSec =< EndSec -> init:stop() end did not execute the first time in run_calendar?
I expect init:stop() could be executed first time but it is not.
What is wrong?
Code:
-module(cal).
-export([main/0]).
main() ->
StartSec = calendar:datetime_to_gregorian_seconds({{2009,1,1},{0,0,0}}),
EndSec = calendar:datetime_to_gregorian_seconds({{2009,12,31},{0,0,0}}),
run_calendar(StartSec,EndSec).
run_calendar(CurSec, EndSec) ->
{Date,_Time} = calendar:gregorian_seconds_to_datetime(CurSec),
io:format("~p~n", [Date]),
NewSec = CurSec + 60*60*24,
if NewSec =< EndSec -> init:stop() end,
run_calendar(NewSec, EndSec).
Result:
wk# erlc cal.erl
wk# erl -noshell -s cal main
{2009,1,1}
{2009,1,2}
{2009,1,3}
{2009,1,4}
{2009,1,5}
...
{2009,12,22}
{2009,12,23}
{2009,12,24}
{2009,12,25}
{2009,12,26}
{2009,12,27}
{2009,12,28}
{2009,12,29}
{2009,12,30}
{2009,12,31}
wk#
I believe that init:stop() is an asynchronous process that will attempt to shut down the runtime smoothly. According to the docs, "All applications are taken down smoothly, all code is unloaded, and all ports are closed before the system terminates."
It probably takes a while to actually stop, because you have an actively running process. If you change "init:stop()" to "exit(stop)", it will terminate immediately:
3> cal:main().
{2009,1,1}
** exception exit: stop
in function cal:run_calendar/2
Init:stop is asynchronous and it will take time to quit. An alternate way would be to wrap up the test in the call itself and use pattern matching to terminate the loop:
-module(cal).
-export([main/0]).
main() ->
StartSec = calendar:datetime_to_gregorian_seconds({{2009,1,1},{0,0,0}}),
EndSec = calendar:datetime_to_gregorian_seconds({{2009,12,31},{0,0,0}}),
run_calendar(false, StartSec, EndSec).
run_calendar(true, _StartSec, _EndSec) ->
finished;
run_calendar(false, CurSec, EndSec) ->
{Date,_Time} = calendar:gregorian_seconds_to_datetime(CurSec),
io:format("~p~n", [Date]),
NewSec = CurSec + 60*60*24,
run_calendar(NewSec =< EndSec, NewSec, EndSec).
(or something similar, hopefully you get the idea)
You have a mistake in your if statement
You said
if NewSec =< EndSec -> init:stop() end,
This is incorrect. You have to write something like:
if
A =< B -> do something ...;
true -> do something else
end
The if syntax is
if
Condition1 -> Actions1;
Condition2 -> Actions2;
...
end
One of these conditions must always be true.
Why is this?
Erlang is a functional language, not a statement language. In an functional
language every expression must have a value. if is an expression, so it must have a value.
The value of (if 2 > 1 -> 3 end) is 3 but what is the value of
(if 1 > 2 -> 3 end) - answer it has no value - but it must have a value
everything must have a value.
In a statement language everything is evaluated for its side effect -so this would
be a valid construction.
In Erlang you will generate an exception.
So your code generates an exception - which you don't trap so you don't see it and
init:stop() never gets called ...