AutoHotkey: Similar function like ClipWait for "Select All" - process

Does AutoHotkey have anything similar to "ClipWait" for "Ctrl+A" / "Select All".
Or is there a possibility to get such a function somehow ?

Would this be sufficient?
^b::
send ^a
selectionWait()
msgbox, All has been selected
return
selectionWait() {
clipboardSave := clipboardAll
loop {
send ^c
if(clipboard != clipboardSave)
if(clipboard != "")
break
}
clipboard := clipboardSave
}
ctrl+c IS fired before everything is selected, but this is on purpose. the action will be repeated until the clipboard contents have changed, and the clipboard will be reset to the previous value afterwards

I had the same problem when selecting many rows from a network database.
The “Select All” command didn't have time to complete, hence making
Copy & ClipWait useless,
Here's the beautiful fix:
Loop
{
Send, ^a
Send, ^c
ClipWait, 1
if (!ErrorLevel)
break
}
Or like this if you want to limit the wait to 5 seconds:
Loop, 5
{
Send, ^a
Send, ^c
ClipWait, 1
if (!ErrorLevel)
break
}

Related

Error - Unexpected } at the end of While Loop

I'm using while true loop to constantly check run this script. After adding the if expression with whitelist ahk gives an error about unexpected } at the end of code. As far as I know there should be }.
Using Loop command gives the same error.
Removing the problematic } at the end causes the code running in background but not doing anything.
;Setup
Sleep, 1000
whiteList = "none"
;Main Loop
While True
{
siteName = YouTube
WinGetActiveTitle, tabName
Sleep, 10000
if tabName = %whiteList%{
Continue
}
;If current website is Youtube, ask if am I supposted to be here
if InStr(tabName, siteName){
Sleep, 10000
MsgBox, 292, Reality Check, Should you do this?
IfMsgBox, Yes
{
whiteList = tabName
}
;Close tab in mozilla
else
{
WinActivate, %tabName%
Sleep, 10
Send ^w
}
}
}
Code is unfinished, It should run in background and when the user is using YouTube fore some time it should ask him whether is he supposted to watch Youtube.
If he clicks yes, the program should ignore that specific page.
Else it should close it.
The % around the whiteList-var shouldn't be there. When I wrote it like below it seems to work:
if tabName = whiteList
Continue
Also the whiteList = tabName will just assign the string "tabName" to whiteList. Use whiteList := tabName for assigning, and if var1 = var2 for comparison.

Perl6: check if STDIN has data

In my Perl 6 script, I want to do a (preferably non-blocking) check of standard input to see if data is available. If this is the case, then I want to process it, otherwise I want to do other stuff.
Example (consumer.p6):
#!/usr/bin/perl6
use v6.b;
use fatal;
sub MAIN() returns UInt:D {
while !$*IN.eof {
if some_fancy_check_for_STDIN() { #TODO: this needs to be done.
for $*IN.lines -> $line {
say "Process '$line'";
}
}
say "Do something Else.";
}
say "I'm done.";
return 0;
}
As a STDIN-Generator I wrote another Perl6 script (producer.p6):
#!/usr/bin/perl6
use v6.b;
use fatal;
sub MAIN() returns UInt:D {
$*OUT.say("aaaa aaa");
sleep-until now+2;
$*OUT.say("nbbasdf");
sleep-until now+2;
$*OUT.say("xxxxx");
sleep-until now+2;
return 0;
}
If consumer.p6 works as expected, it should produce the following output, if called via ./producer.p6 | ./consumer.p6:
Process 'aaaa aaa'
Do something Else.
Process 'nbbasdf'
Do something Else.
Process 'xxxxx'
Do something Else.
I'm done.
But actually, it produces the following output (if the if condition is commented out):
Process 'aaaa aaa'
Process 'nbbasdf'
Process 'xxxxx'
Do something Else.
I'm done.
You are using an old version of Perl 6, as v6.b is from before the official release of the language.
So some of what I have below may need a newer version to work.
Also why are you using sleep-until now+2 instead of sleep 2?
One way to do this is to turn the .lines into a Channel, then you can use .poll.
#!/usr/bin/env perl6
use v6.c;
sub MAIN () {
# convert it into a Channel so we can poll it
my $lines = $*IN.Supply.lines.Channel;
my $running = True;
$lines.closed.then: {$running = False}
while $running {
with $lines.poll() -> $line {
say "Process '$line'";
}
say "Do something Else.";
sleep ½;
}
say "I'm done.";
}
Note that the code above blocks at the my $lines = … line currently; so it doesn't start doing something until the first line comes in. To get around that you could do the following
my $lines = supply {
# unblock the $*IN.Supply.lines call
whenever start $*IN.Supply {
whenever .lines { .emit }
}
}.Channel;

How to implement "fallback condition" in while loop in Expect?

I have a machine I telnet into, and pass "ctrl+C" until I see the prompt. The ctrl+C may not always work, so I must try after every 5 seconds until I see my expected output ($prompt).
In case I don't get a $prompt, how do I ensure I can retry the while loop effectively? Is this code below the best practice? My concern is, that I don't know what I may get when the "ctrl+C" fails, it could be anything and it must be ignored unless it's $prompt.
while { $disableFlag == 0 } {
send "^C\r"
expect {
"*$prompt*" {
puts "Found the prompt"
sleep 5
}
"*" {
set disableFlag 1
puts "Retrying"
sleep 5
}
}
}
You probably want something like this (untested)
set timeout 5
send \03
expect {
"*$prompt*" {
puts "found the prompt"
}
timeout {
puts "did not see prompt within $timeout seconds. Retrying"
send \03
exp_continue
}
}
# do something after seeing the prompt
\03 is the octal value for ctrl-C: see http://wiki.tcl.tk/3038
If you want to bail out eventually:
set timeout 5
set count 0
send \03
expect {
"*$prompt*" {
puts "found the prompt"
}
timeout {
if {[incr count] == 10} { # die
error "did not see prompt after [expr {$timeout * $count}] seconds. Aborting"
}
puts "did not see prompt within $timeout seconds. Retrying"
send \03
exp_continue
}
}

Running multiple exec commands and waiting to finish before continuing

I know I ask a lot of questions and I know there is a lot on here about this exactly what I am trying to do but I have not been able to get it to work in my script nor figure out why it does not let me do this. I am trying to run several commands using exec in the background and the tests can range anywhere between 5 and 45 minutes (longer if they have to cue for a license). It takes forever to run them back to back so I was wondering what I need to do to make my script wait for them to finish before moving on the the next section of script.
while {$cnt <= $len} {
# Begin count for running tests
set testvar [lindex $f $cnt]
if {[file exists $path0/$testvar] == 1} {
cd $testvar
} else {
exec mkdir $testvar
cd $testvar
exec create_symobic_link_here
}
# Set up test environment
exec -ignorestderr make clean
exec -ignorestderr make depends
puts "Running $testvar"
set runtest [eval exec -ignorestderr bsub -I -q lin_i make $testvar SEED=1 VPDDUMP=on |tail -n 1 >> $path0/runtestfile &]
cd ../
incr cnt
}
I know there is nothing here to make the script wait for the process to finish but I have tried many different things any this is the only way I can get it to run everything. It just doesn't wait.
One way is to modify your tests to create a "finished" file. This file should be created whether the test completes correctly or fails.
Modify the startup loop to remove this file before starting the test:
catch { file delete $path0/$testvar/finished }
Then create a second loop:
while { true } {
after 60000
set cnt 1 ; # ?
set result 0
while { $cnt <= $len } {
set testvar [lindex $f $cnt]
if { [file exists $path0/$testvar/finished] } {
incr result
}
incr cnt
}
if { $result == $len } {
break
}
}
This loop as written will never exit if any one test doesn't create the 'finished' file. So I would add in an additional stop condition (no more than one hour) to exit the loop.
Another way would be to save the process ids of the background processes in a list and then the second loop would check each process id to see if it is still running. This method would not require any modifications to the test, but is a little harder to implement (not too hard on unix/mac, harder on windows).
Edit: loop using process id check:
To use process ids, the main loop needs to be modified to save the process ids of the background jobs:
Before the main loop starts, clear the process id list:
set pidlist {}
In the main loop, save the process ids from the exec command (In tcl, [exec ... &] returns the background process id):
lappend pidlist $runtest ; # goes after the exec bsub...
A procedure to check for the existence of a process (for unix/mac). Tcl/Tk does not have any process control commands, so the unix 'kill' command is used. 'kill -0' on unix only checks for process existence, and does not affect the execution of the process.
# return 0 if the process does not exist, 1 if it does
proc checkpid { ppid } {
set pexists [catch {exec kill -0 $ppid}]
return [expr {1-$pexists}]
}
And the second loop to check to see if the tests are done becomes:
set tottime 0
while { true } {
after 60000
incr tottime 1 ; # in minutes
set result 0
foreach {pid} $pidlist {
if { ! [checkpid $pid] } {
incr result
}
}
if { $result == $len } {
break
}
if { $tottime > 120 } {
puts "Total test time exceeded."
break ; # or exit
}
}
If a test process gets hung and never exits, this loop will never exit, so a second stop condition on total time is used.

Opening an MS-Cash Drawer, Wrong Code? Bad Code?

Humbling expierence here and I think this one will make a fool of me, but...I'm trying to convert an ancient cash register program to .net. Conquered everything else, but I can't pop open the cash register. Its connected to COM1, you are supposed to send a "trigger" text down COM1 that will cause the register to open.
Here is the .net code.
MsgBox("Opening Drawer")
Dim port As System.IO.Ports.SerialPort
port = New System.IO.Ports.SerialPort("Com1")
port.PortName = "COM1"
port.BaudRate = 9600
port.Parity = IO.Ports.Parity.None
port.DataBits = 8
port.StopBits = IO.Ports.StopBits.One
'port.Handshake = IO.Ports.Handshake.RequestToSend
port.RtsEnable = True
'port.DtrEnable = True
port.Open()
If port.IsOpen Then
'MsgBox("Attempt 1")
port.Write("####################")
MsgBox("Signal Sent: " & Chr(65))
Else
MsgBox("Port is not open")
End If
port.Close()
MsgBox("Pop, durn it!")
I get msgboxes "Signal Sent", "Done Pop Drawer"
Dang thing, just won't pop. It's an MS-Cash Drawer (EP125KC). Definitely connected to COM1, definitely has power. Chr(65) is the old code used to pop drawer and it works:
Open drawerComPort For Output Access Write As #1
Print #1, Chr$(65); "A";
Close #1
NOTE: The above code worked successfully. The root problem was caused by a reveresed power cord (negative was on the wrong side).
Thanks for all the help guys!
You've set your handshake to None but the cash drawer probably has its own idea. Also set DtrEnable to True. Chr(65) is the ASCII code for an "A", your VB code suggests the real command is "AA".
The manual documents that the cash drawer auto-tunes its baudrate. It recommends sending at least 20 # characters. And that the real command is Ctrl+G (Chr(7)). The "AA" command might have worked previously due to a baudrate mismatch. Perhaps.
If I remember my very rusty BASIC.
Print #1, Chr$(65); "A";
means print to port1 the character 65 followed by the string "A", Now the character 65 is 'A', so this looks to me like you should be sending "AA" to port1
port.Write("AA");
or alternately,
port.Write(new byte[]{65,'A'}, 0, 2);
It might be sending Unicode 65, which would be 0065, which would not end well.
Just a thought, can you try sending a raw int?
I dont use .net, but is the port buffered? do you need to send a flush/fflush()?
Are you sure you're supposed to send out this code? I would have always thought that the code is prefixed by ESC i.e. 0x1b hexadecimal...for cash drawers...
"\x1bA"
Interesting that double 'A' is used...oh well... :)
Edit: After thinking about this I realized there is another way of doing it, read on...
I have modified your original BASIC code with a bit of bullet-proofing...save it to opendrawer.bas
Sub OpenDrawer()
drawerComPort = "COM1"
Open drawerComPort For Output Access Write As #1
REM ADDED ERROR HANDLING
ON ERROR GOTO ErrHandler
Print #1, Chr$(65); "A";
Close #1
print "Drawer Ok"
OpenDrawer_Exit:
On Error Goto 0
Exit Sub
ErrHandler:
print "Oops, Write Failed"
Goto OpenDrawer_Exit
End Sub
REM The Main....
OpenDrawer
Download the old QB4.5 MS-Quick Basic compiler, and compile that to an executable, into opendrawer.exe, the QB4.5 can be found here. Now, the onus is on you to make this bulletproof, i.e. what happens if writing to COM1 fails, issue a message like in the example BASIC code I modified
Then you can use the System.Diagnostics.Process to shell out using a hidden window
public class TestDrawer
{
private StringBuilder sbRedirectedOutput = new StringBuilder();
public string OutputData
{
get { return this.sbRedirectedOutput.ToString(); }
}
public void Run()
{
System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo();
ps.FileName = "opendrawer";
ps.ErrorDialog = false;
ps.CreateNoWindow = true;
ps.UseShellExecute = false;
ps.RedirectStandardOutput = true;
ps.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = ps;
proc.Exited += new EventHandler(proc_Exited);
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.WaitForExit();
proc.BeginOutputReadLine();
while (!proc.HasExited) ;
}
}
void proc_Exited(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("proc_Exited: Process Ended");
if (this.sbRedirectedOutput.ToString().IndexOf("Oops, write failed") > -1){
MessageBox.Show(this, "Error in opening Cash Drawer");
}
if (this.sbRedirectedOutput.ToString().IndexOf("Drawer Ok") > -1){
MessageBox.Show(this, "Drawer Ok");
}
}
void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (e.Data != null) this.sbRedirectedOutput.Append(e.Data + Environment.NewLine);
//System.Diagnostics.Debug.WriteLine("proc_OutputDataReceived: Data: " + e.Data);
}
The process shells out to a hidden window and all output is redirected and handled in the event handler...that should do the trick. Notice, how the redirected output goes into the sbRedirectedOutput (a StringBuilder instance). In the proc_ProcExited event handler, it checks the sbRedirectedOutput for the message 'Oops Write failed' which would be issued from the QB4.5 program.
Be aware, that you may need to include the QB4.5's run-time library in the same directory...not 100% sure...it's being years...
What do you think?
Hope this helps,
Best regards,
Tom.