#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(let (NoData 0  NoDataMax -1  NoDataMaxline "!"  TotFile 0  NumFile 0)
   (let InFiles
      (glue ","
         (mapcar
            '((File)
               (in File
                  (while (split (line) "^I")
                     (let (Len (length @)  Date (car @)  TotLine 0  NumLine 0)
                        (for (L (cdr @)  L  (cddr L))
                           (if (> 1 (format (cadr L)))
                              (inc 'NoData)
                              (when (gt0 NoData)
                                 (when (= NoDataMax NoData)
                                    (setq NoDataMaxline (pack NoDataMaxline ", " Date)) )
                                 (when (> NoData NoDataMax)
                                    (setq NoDataMax NoData  NoDataMaxline Date) ) )
                              (zero NoData)
                              (inc 'TotLine (format (car L) 3))
                              (inc 'NumLine) ) )
                        (inc 'TotFile TotLine)
                        (inc 'NumFile NumLine)
                        (tab (-7 -12 -7 3 -9 3 -11 11 -11 11)
                           "Line:" Date
                           "Reject:" (- (/ (dec Len) 2) NumLine)
                           "  Accept:" NumLine
                           "  Line_tot:" (format TotLine 3)
                           "  Line_avg:"
                           (and (gt0 NumLine) (format (*/ TotLine @) 3)) ) ) ) )
               File )
            (argv) ) )
      (prinl)
      (prinl "File(s)  = " InFiles)
      (prinl "Total    = " (format TotFile 3))
      (prinl "Readings = " NumFile)
      (prinl "Average  = " (format (*/ TotFile NumFile) 3))
      (prinl)
      (prinl
         "Maximum run(s) of " NoDataMax
         " consecutive false readings ends at line starting with date(s): " NoDataMaxline ) ) )

(bye)


text1: procedure options (main); /* 13 May 2010 */

   declare line character (2000) varying;
   declare 1 pairs(24),
               2 value fixed (10,4),
               2 flag  fixed;
   declare date character (12) varying;
   declare no_items fixed decimal (10);
   declare (nv, sum, line_no, ndud_values, max_ndud_values) fixed;
   declare (i, k) fixed binary;
   declare in file input;

   open file (in) title ('/TEXT1.DAT,TYPE(TEXT),RECSIZE(2000)' );

   on endfile (in) go to finish_up;

   line_no = 0;
loop:
   do forever;
      get file (in) edit (line) (L);
      /* put skip list (line); */
      line = translate(line, ' ', '09'x);
      line_no = line_no + 1;
      line = trim(line);
      no_items = tally(line, ' ') - tally(line, '  ') + 1;
      if no_items ^= 49 then
         do; put skip list ('There are not 49 items on this line'); iterate loop; end;
      k = index(line, ' '); /* Find the first blank in the line. */
      date = substr(line, 1, k);
      line = substr(line, k) || ' ';
      on conversion go to loop;
      get string (line) list (pairs);
      sum, nv, ndud_values, max_ndud_values = 0;
      do i = 1 to 24;
         if flag(i) > 0 then
            do; sum = sum + value(i); nv = nv + 1;
            ndud_values = 0; /* reset the counter of dud values */
            end;
         else
            do; /* we have a dud reading. */
                ndud_values = ndud_values + 1;
                if ndud_values > max_ndud_values then
                  max_ndud_values = ndud_values;
            end;
      end;
      if nv = 0 then iterate;
      put skip list ('Line ' || trim(line_no) || ' average=', divide(sum, nv, 10,4) );
      if max_ndud_values > 0 then
         put skip list ('Maximum run of dud readings =', max_ndud_values);
   end;

finish_up:

end text1;


#import std
#import nat

readings        = (*F ~&c/;digits+ rlc ==+ ~~ -={` ,9%cOi&,13%cOi&}) readings_dot_txt

valid_format    = all -&length==49,@tK27 all ~&w/`.&& ~&jZ\digits--'-.',@tK28 all ~&jZ\digits--'-'&-

duplicate_dates = :/'duplicated dates:'+ ~&hK2tFhhPS|| -[(none)]-!

good_readings   = --' good readings'@h+ %nP+ length+ *~ @tK28 all ~='0'&& ~&wZ/`-

#show+

main = valid_format?(^C/good_readings duplicate_dates,-[invalid format]-!) readings


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
			"\readings.txt",1)
Set objDateStamp = CreateObject("Scripting.Dictionary")

Total_Records = 0
Valid_Records = 0
Duplicate_TimeStamps = ""

Do Until objFile.AtEndOfStream
	line = objFile.ReadLine
	If line <> "" Then
		token = Split(line,vbTab)
		If objDateStamp.Exists(token(0)) = False Then
			objDateStamp.Add token(0),""
			Total_Records = Total_Records + 1
			If IsValid(token) Then
				Valid_Records = Valid_Records + 1
			End If
		Else
			Duplicate_TimeStamps = Duplicate_TimeStamps & token(0) & vbCrLf
			Total_Records = Total_Records + 1
		End If
	End If
Loop

Function IsValid(arr)
	IsValid = True
	Bad_Readings = 0
	n = 1
	Do While n <= UBound(arr)
		If n + 1 <= UBound(arr) Then
			If CInt(arr(n+1)) < 1 Then
				Bad_Readings = Bad_Readings + 1
			End If
		End If
		n = n + 2
	Loop
	If Bad_Readings > 0 Then
		IsValid = False
	End If
End Function

WScript.StdOut.Write "Total Number of Records = " & Total_Records
WScript.StdOut.WriteLine
WScript.StdOut.Write "Total Valid Records = " & Valid_Records
WScript.StdOut.WriteLine
WScript.StdOut.Write "Duplicate Timestamps:"
WScript.StdOut.WriteLine
WScript.StdOut.Write Duplicate_TimeStamps
WScript.StdOut.WriteLine

objFile.Close
Set objFSO = Nothing


#50 = Buf_Num           // Current edit buffer (source data)
File_Open("|(PATH_ONLY)\output.txt")
#51 = Buf_Num           // Edit buffer for output file
Buf_Switch(#50)

#11 = #12 = #13 = #14 = #15 = 0
Reg_Set(15, "xxx")

While(!At_EOF) {
    #10 = 0
    #12++

    // Check for repeated date field
    if (Match(@15) == 0) {
        #20 = Cur_Line
        Buf_Switch(#51)   // Output file
        Reg_ins(15) IT(": duplicate record at ") Num_Ins(#20)
        Buf_Switch(#50)   // Input file
        #13++
    }

    // Check format of date field
    if (Match("|d|d|d|d-|d|d-|d|d|w", ADVANCE) != 0) {
        #10 = 1
        #14++
    }
    Reg_Copy_Block(15, BOL_pos, Cur_Pos-1)

    // Check data fields and flags:
    Repeat(24) {
        if ( Match("|d|*.|d|d|d|w", ADVANCE) != 0 || Num_Eval(ADVANCE) < 1) {
            #10 = 1
            #15++
            Break
        }
        Match("|W", ADVANCE)
    }
    if (#10 == 0) { #11++ }             // record was OK
    Line(1, ERRBREAK)
}

Buf_Switch(#51)         // buffer for output data
IN
IT("Valid records:       ") Num_Ins(#11)
IT("Duplicates:          ") Num_Ins(#13)
IT("Date format errors:  ") Num_Ins(#14)
IT("Invalid data records:") Num_Ins(#15)
IT("Total records:       ") Num_Ins(#12)


$file = '.\readings.txt'
$lines = Get-Content $file # $args[0]
$valid = $true
$startDate = $currStart = $endDate = ''
$startHour = $endHour = $currHour = $max = $currMax = $total = $readings = 0
$task = @()
foreach ($var in $lines) {
    $date, $rest = [regex]::Split($var,'\s+')
    $reject = $accept = $sum = $cnt = 0
    while ($rest) {
        $cnt += 1
        [Double]$val, [Double]$flag, $rest = $rest
        if (0 -lt $flag) {
            $currMax = 0
            $sum += $val
            $accept += 1
        } else {
            if (0 -eq $currMax) {
                $currStart = $date
                $currHour = $cnt
            }
            $currMax += 1
            $reject += 1
            if ($max -lt $currMax) {
                $startDate, $endDate = $currStart, $date
                $startHour, $endHour = $currHour, $cnt
                $max = $currMax
            }
        }
    }
    $readings += $accept
    $total += $sum
    $average = if (0 -lt $accept) {$sum/$accept} else {0}
    $task += [PSCustomObject]@{
        'Line' = $date
        'Reject' = $reject
        'Accept' = $accept
        'Sum' = $sum.ToString("N")
        'Average' = $average.ToString("N3")
    }
    $valid = 0 -eq $reject
}
$task  | Select -Last 3
$average = $total/$readings
"File(s)  = $file"
"Total    = {0}" -f $total.ToString("N")
"Readings = $readings"
"Average  = {0}" -f $average.ToString("N3")
""
"Maximum run(s) of $max consecutive false readings."
if (0 -lt $max) {
    "Consecutive false readings starts at line starting with date $startDate at hour {0:0#}:00." -f $startHour
    "Consecutive false readings ends at line starting with date $endDate at hour {0:0#}:00." -f $endHour
}


import "io" for File
import "/pattern" for Pattern
import "/fmt" for Fmt
import "/sort" for Sort

var p = Pattern.new("+1/s")
var fileName = "readings.txt"
var lines = File.read(fileName).trimEnd().split("\r\n")
var count = 0
var invalid = 0
var allGood = 0
var map = {}
for (line in lines) {
    count = count + 1
    var fields = p.splitAll(line)
    var date = fields[0]
    if (fields.count == 49) {
        map[date] = map.containsKey(date) ? map[date] + 1 : 1
        var good = 0
        var i = 2
        while (i < fields.count) {
            if (Num.fromString(fields[i]) >= 1) good = good + 1
            i = i + 2
        }
        if (good == 24) allGood = allGood + 1
    } else {
        invalid = invalid + 1
   }
}

Fmt.print("File = $s", fileName)
System.print("\nDuplicated dates:")
var keys = map.keys.toList
Sort.quick(keys)
for (k in keys) {
    var v = map[k]
    if (v > 1) Fmt.print("  $s  ($d times)", k, v)
}
Fmt.print("\nTotal number of records   : $d", count)
var percent = invalid/count * 100
Fmt.print("Number of invalid records : $d ($5.2f)\%", invalid, percent)
percent = allGood/count * 100
Fmt.print("Number which are all good : $d ($5.2f)\%", allGood, percent)


MODULE RosettaIsaac;

FROM Strings IMPORT
  Length, Assign, Append;
FROM STextIO IMPORT
  WriteString, WriteLn;
FROM Conversions IMPORT
  CardBaseToStr;

CONST
  MaxStrLength = 256;

TYPE
  TMode = (iEncrypt, iDecrypt);
  TString = ARRAY [0 .. MaxStrLength - 1] OF CHAR;
  TCardIndexedFrom0To7 = ARRAY [0 .. 7] OF CARDINAL;

VAR
(* TASK globals *)
  Msg: TString = 'a Top Secret secret';
  Key: TString = 'this is my secret key';
  XorCipherText: TString = '';
  ModCipherText: TString = '';
  XorPlainText: TString = '';
  ModPlainText: TString = '';
  Mode: TMode = iEncrypt;
  HexText: TString;

(* ISAAC globals *)
(* external results *)
  RandRsl: ARRAY [0 .. 256] OF CARDINAL;
  RandCnt: CARDINAL;

(* internal state *)
  MM: ARRAY [0 .. 256] OF CARDINAL;
  AA: CARDINAL = 0;
  BB: CARDINAL = 0;
  CC: CARDINAL = 0;

PROCEDURE Isaac;
VAR
  I, X, Y: CARDINAL;
BEGIN
   CC := CC + 1;    (* CC just gets incremented once per 256 results *)
   BB := BB + CC;   (* then combined with BB *)
   FOR I := 0 TO 255 DO
     X := MM[I];
     CASE (I MOD 4) OF
        0: AA := AA BXOR (AA SHL 13); |
        1: AA := AA BXOR (AA SHR 6); |
        2: AA := AA BXOR (AA SHL 2); |
        3: AA := AA BXOR (AA SHR 16);
     ELSE
     END;
     AA := MM[(I + 128) MOD 256] + AA;
     Y  := MM[(X SHR 2) MOD 256] + AA + BB;
     MM[I] := Y;
     BB := MM[(Y SHR 10) MOD 256] + X;
     RandRsl[I] := BB;
   END; (* FOR *)
   RandCnt := 0;  (* Prepare to use the first set of results. *)
END Isaac;

PROCEDURE Mix(VAR A: TCardIndexedFrom0To7);
BEGIN
  A[0] := A[0] BXOR A[1] SHL 11; A[3] := A[3] + A[0]; A[1] := A[1] + A[2];
  A[1] := A[1] BXOR A[2] SHR  2; A[4] := A[4] + A[1]; A[2] := A[2] + A[3];
  A[2] := A[2] BXOR A[3] SHL  8; A[5] := A[5] + A[2]; A[3] := A[3] + A[4];
  A[3] := A[3] BXOR A[4] SHR 16; A[6] := A[6] + A[3]; A[4] := A[4] + A[5];
  A[4] := A[4] BXOR A[5] SHL 10; A[7] := A[7] + A[4]; A[5] := A[5] + A[6];
  A[5] := A[5] BXOR A[6] SHR  4; A[0] := A[0] + A[5]; A[6] := A[6] + A[7];
  A[6] := A[6] BXOR A[7] SHL  8; A[1] := A[1] + A[6]; A[7] := A[7] + A[0];
  A[7] := A[7] BXOR A[0] SHR  9; A[2] := A[2] + A[7]; A[0] := A[0] + A[1];
END Mix;

PROCEDURE RandInit(Flag: BOOLEAN);
VAR
  I, J: CARDINAL;
  A: TCardIndexedFrom0To7;
BEGIN
  AA := 0; BB := 0; CC := 0;
  A[0] := 2654435769; (* $9e3779b9: the golden ratio *)
  FOR J := 1 TO 7 DO
    A[J] := A[0];
  END;

  FOR I := 0 TO 3 DO (* Scramble it *)
    Mix(A);
  END;
  FOR I := 0 TO 255 BY 8 DO (* Fill in MM[] with messy stuff. *)
    IF Flag THEN (* Use all the information in the seed. *)
      FOR J := 0 TO 7 DO
        A[J] := A[J] + RandRsl[I + J];
      END;
    END;
    Mix(A);
    FOR J := 0 TO 7 DO
      MM[I + J] := A[J];
    END;
  END; (* FOR I*)

  IF Flag THEN
    (* Do a second pass to make all of the Seed affect all of MM *)
    FOR I := 0 TO 255 BY 8 DO
      FOR J := 0 TO 7 DO
        A[J] := A[J] + MM[I + J];
      END;
      Mix(A);
      FOR J := 0 TO 7 DO
        MM[I + J] := A[J];
      END;
    END; (* FOR I *)
  END;
  Isaac(); (* Fill in the first set of results *)
  RandCnt := 0; (* Prepare to use the first set of results *)
END RandInit;

(* Seed ISAAC with a given string.
  The string can be any size. The first 256 values will be used. *)
PROCEDURE SeedIsaac(Seed: ARRAY OF CHAR; Flag: BOOLEAN);
VAR
  I, M: CARDINAL;
BEGIN
  FOR I := 0 TO 255 DO
    MM[I] := 0;
  END;
  M := Length(Seed);
  FOR I := 0 TO 255 DO
  (* In case seed has less than 256 elements *)
    IF I > M THEN
      RandRsl[I] := 0
    ELSE
      (* Modula-2 strings are 0-based (at least, in this case). *)
      RandRsl[I] := ORD(Seed[I]);
    END;
  END;
  (* Initialize ISAAC with seed. *)
  RandInit(Flag);
END SeedIsaac;

(* Get a random 32-bit value 0..MAXINT *)
PROCEDURE GetRandom32Bit(): CARDINAL;
VAR
  Result: CARDINAL;
BEGIN
  Result := RandRsl[RandCnt];
  INC(RandCnt);
  IF RandCnt > 255 THEN
    Isaac();
    RandCnt := 0;
  END;
  RETURN Result;
END GetRandom32Bit;

(* Get a random character in printable ASCII range. *)
PROCEDURE GetRandomChar(): SHORTCARD;
BEGIN
  RETURN GetRandom32Bit() MOD 95 + 32;
END GetRandomChar;

(* Convert an ASCII string to a hexadecimal string. *)
PROCEDURE ASCII2Hex(Source: ARRAY OF CHAR; VAR OUT Destination: ARRAY OF CHAR);
VAR
  I: CARDINAL;
  NumbHex: ARRAY [0 .. 1] OF CHAR;
BEGIN
  Assign('', Destination);
  FOR I := 0 TO Length(Source) - 1 DO
    CardBaseToStr(ORD(Source[I]), 16, NumbHex);
    IF Length(NumbHex) <= 1 THEN
      Append('0', Destination);
    END;
    Append(NumbHex, Destination);
  END;
END ASCII2Hex;

(* XOR encrypt on random stream. *)
PROCEDURE Vernam(Msg: ARRAY OF CHAR; VAR OUT Destination: ARRAY OF CHAR);
VAR
  I: CARDINAL;
  OrdMsgI: SHORTCARD;
BEGIN
  Assign('', Destination);
  FOR I := 0 TO Length(Msg) - 1 DO
    OrdMsgI := ORD(Msg[I]);
    Append(CHR(GetRandomChar() BXOR OrdMsgI), Destination);
  END;
END Vernam;

(* Get position of the letter in chosen alphabet *)
PROCEDURE LetterNum(Letter, Start: CHAR): SHORTCARD;
BEGIN
  RETURN ORD(Letter) - ORD(Start);
END LetterNum;

(* Caesar-shift a character <Shift> places: Generalized Vigenere *)
PROCEDURE Caesar(M: TMode; Ch: CHAR; Shift, Modulo: INTEGER; Start: CHAR): CHAR;
VAR
  N, IntOrdStart: INTEGER;
BEGIN
  IF M = iDecrypt THEN
    Shift := -Shift;
  END;
  N := LetterNum(Ch, Start);
  N := N + Shift;
  N := N MOD Modulo;
  IF N < 0 THEN
    N := N + Modulo;
  END;
  IntOrdStart := ORD(Start);
  RETURN CHR(IntOrdStart + N);
END Caesar;

(* Vigenere mod 95 encryption & decryption. *)
PROCEDURE Vigenere(Msg: ARRAY OF CHAR; M: TMode; VAR OUT Destination: ARRAY OF CHAR);
VAR
  I: CARDINAL;
BEGIN
  Assign('', Destination);
  FOR I := 0 TO Length(Msg) - 1 DO
    Append(Caesar(M, Msg[I], GetRandomChar(), 95, ' '), Destination);
  END;
END Vigenere;

BEGIN
  (* (1) Seed ISAAC with the key *)
  SeedIsaac(Key, TRUE);
  (* (2) Encryption *)
  Mode := iEncrypt;
  (* (a) XOR (Vernam) *)
  Vernam(Msg, XorCipherText);
  (* (b) MOD (Vigenere) *)
  Vigenere(Msg, Mode, ModCipherText);
  (* (3) Decryption *)
  Mode := iDecrypt;
  SeedIsaac(Key, TRUE);
  (* (a) XOR (Vernam) *)
  Vernam(XorCipherText, XorPlainText);
  (* (b) MOD (Vigenere) *)
  Vigenere(ModCipherText, Mode, ModPlainText);
  (* program output *)
  WriteString('Message: '); WriteString(Msg); WriteLn;
  WriteString('Key    : '); WriteString(Key); WriteLn;
  ASCII2Hex(XorCipherText, HexText);
  WriteString('XOR    : '); WriteString(HexText); WriteLn;
  ASCII2Hex(ModCipherText, HexText);
  WriteString('MOD    : '); WriteString(HexText); WriteLn;
  WriteString('XOR dcr: '); WriteString(XorPlainText); WriteLn;
  WriteString('MOD dcr: '); WriteString(ModPlainText); WriteLn;
END RosettaIsaac.


#TASK="Text processing/1"
Define File$, InLine$, Part$, i, Out$, ErrEnds$, Errcnt, ErrMax
Define lsum.d, tsum.d, rejects, val.d, readings

File$=OpenFileRequester(#TASK,"readings.txt","",0)
If OpenConsole() And ReadFile(0,File$)
  While Not Eof(0)
    InLine$=ReadString(0)
    For i=1 To 1+2*24
      Part$=StringField(InLine$,i,#TAB$)
      If i=1        ; Date
        Out$=Part$: lsum=0: rejects=0
      ElseIf i%2=0  ; Recorded value
        val=ValD(Part$)
      Else          ; Status part
        If Val(Part$)>0
          Errcnt=0 : readings+1
          lsum+val : tsum+val
        Else
          rejects+1: Errcnt+1
          If Errcnt>ErrMax
            ErrMax=Errcnt
            ErrEnds$=Out$
          EndIf
        EndIf
      EndIf
    Next i
    Out$+" Rejects: " + Str(rejects)
    Out$+" Accepts: " + Str(24-rejects)
    Out$+" Line_tot: "+ StrD(lsum,3)
    If rejects<24
      Out$+" Line_avg: "+StrD(lsum/(24-rejects),3)
    Else
      Out$+" Line_avg: N/A"
    EndIf
    PrintN("Line: "+Out$)
  Wend
  PrintN(#CRLF$+"File     = "+GetFilePart(File$))
  PrintN("Total    = "+ StrD(tsum,3))
  PrintN("Readings = "+ Str(readings))
  PrintN("Average  = "+ StrD(tsum/readings,3))
  Print(#CRLF$+"Maximum of "+Str(ErrMax))
  PrintN(" consecutive false readings, ends at "+ErrEnds$)
  CloseFile(0)
  ;
  Print("Press ENTER to exit"): Input()
EndIf


   // the RegExp engine has a low limit on groups so
   // I can't use it to select all fields, only verify them
re:=RegExp(0'|^(\d+-\d+-\d+)| + 0'|\s+\d+\.\d+\s+-*\d+| * 24 + ".+$");
w:=[1..].zip(File("readings.txt"));  //-->lazy (line #,line)
reg datep,N, good=0, dd=0;
foreach n,line in (w){
   N=n;		// since n is local to this scope
   if (not re.search(line)){ println("Line %d: malformed".fmt(n)); continue; }
   date:=line[re.matchedNs[1].xplode()];  // I can group the date field
   if (datep==date){ dd+=1; println("Line %4d: dup date: %s".fmt(n,date)); }
   datep=date;
   if (line.replace("\t"," ").split(" ").filter()[1,*]  // blow fields apart, drop date
         .pump(Void,Void.Read, // get (reading,status)
            fcn(_,s){  // stop on first problem status and return True
               if(s.strip().toInt()<1) T(Void.Stop,True) else False
       })) continue;
   good+=1;
}
println("%d records read, %d duplicate dates, %d valid".fmt(N,dd,good));


import strutils

type

  IMode = enum iEncrypt, iDecrypt

  State = object
    # Internal.
    mm: array[256, uint32]
    aa, bb, cc: uint32
    # External.
    randrsl: array[256, uint32]
    randcnt: uint32

proc isaac(s: var State) =

  inc s.cc        # "cc" just gets incremented once per 256 results
  s.bb += s.cc    # then combined with "bb".

  for i in 0u32..255:
    let x = s.mm[i]
    case range[0..3](i and 3)
    of 0: s.aa = s.aa xor s.aa shl 13
    of 1: s.aa = s.aa xor s.aa shr 6
    of 2: s.aa = s.aa xor s.aa shl 2
    of 3: s.aa = s.aa xor s.aa shr 16
    s.aa += s.mm[(i + 128) and 255]
    let y = s.mm[(x shr 2) and 255] + s.aa + s.bb
    s.mm[i] = y
    s.bb = s.mm[(y shr 10) and 255] + x
    s.randrsl[i] = s.bb

  s.randcnt = 0

proc mix(a: var array[8, uint32]) =
  a[0] = a[0] xor a[1] shl 11; a[3] += a[0]; a[1] += a[2]
  a[1] = a[1] xor a[2] shr  2; a[4] += a[1]; a[2] += a[3]
  a[2] = a[2] xor a[3] shl  8; a[5] += a[2]; a[3] += a[4]
  a[3] = a[3] xor a[4] shr 16; a[6] += a[3]; a[4] += a[5]
  a[4] = a[4] xor a[5] shl 10; a[7] += a[4]; a[5] += a[6]
  a[5] = a[5] xor a[6] shr  4; a[0] += a[5]; a[6] += a[7]
  a[6] = a[6] xor a[7] shl  8; a[1] += a[6]; a[7] += a[0]
  a[7] = a[7] xor a[0] shr  9; a[2] += a[7]; a[0] += a[1]

proc iRandInit(s: var State; flag: bool) =

  s.aa = 0; s.bb = 0; s.cc = 0
  var a: array[8, uint32]
  for item in a.mitems: item = 0x9e3779b9u32  # The golden ratio.

  for i in 0..3:  # Scramble it.
    a.mix()

  var i = 0u32
  while true:   # Fill in "mm" with messy stuff.
    if flag:
      # Use all the information in the seed.
      for n in 0u32..7: a[n] += s.randrsl[n + i]
    a.mix()
    for n in 0u32..7: s.mm[n + i] = a[n]
    inc i, 8
    if i > 255: break

  if flag:
    # Do a second pass to make all of the seed affect all of "mm".
    i = 0
    while true:
      for n in 0u32..7: a[n] += s.mm[n + i]
      a.mix()
      for n in 0u32..7: s.mm[n + i] = a[n]
      inc i, 8
      if i > 255: break

  s.isaac()       # Fill in the first set of results.
  s.randcnt = 0   # Prepare to use the first set of results.

proc iSeed(s: var State; seed: string; flag: bool) =
  ## Seed ISAAC with a given string.
  ## The string can be any size. The first 256 values will be used.
  s.mm.reset()
  let m = seed.high
  for i in 0..255:
    s.randrsl[i] = if i > m: 0 else: ord(seed[i])
  # Initialize ISAAC with seed.
  s.iRandInit(flag)

proc iRandom(s: var State): uint32 =
  ## Get a random 32-bit value 0..int32.high.
  result = s.randrsl[s.randcnt]
  inc s.randcnt
  if s.randcnt > 255:
    s.isaac()
    s.randcnt = 0

proc iRandA(s: var State): byte =
  ## Get a random character in printable ASCII range.
  result = byte(s.iRandom() mod 95 + 32)

proc vernam(s: var State; msg: string): string =
  ## XOR encrypt on random stream. Output: ASCII string.
  result.setLen(msg.len)
  for i, c in msg:
    result[i] = chr(s.irandA() xor byte(c))

template letterNum(letter, start: char): int =
  ord(letter) - ord(start)

proc caesar(m: IMode; ch: char; shift, modulo: int; start: char): char =
  let shift = if m == iEncrypt: shift else: -shift
  var n = letterNum(ch, start) + shift
  n = n mod modulo
  if n < 0: inc n, modulo
  result = chr(ord(start) + n)

proc vigenere(s: var State; msg: string; m: IMode): string =
  ## Vigenere MOD 95 encryption & decryption. Output: ASCII string.
  result.setLen(msg.len)
  for i, c in msg:
    result[i] = caesar(m, c, s.iRanda().int, 95, ' ')

let
  msg = "a Top Secret secret"
  key = "this is my secret key"

var state: State

# 1) seed ISAAC with the key
state.iSeed(key, true)
# 2) Encryption
# a) XOR (Vernam)
let xctx = state.vernam(msg)                # XOR ciphertext.
# b) MOD (Vigenere)
let mctx = state.vigenere(msg, iEncrypt)    # MOD ciphertext.
# 3) Decryption
state.iSeed(key, true)
# a) XOR (Vernam)
let xptx = state.vernam(xctx)               # XOR decryption (plaintext).
# b) MOD (Vigenere)
let mptx = state.vigenere(mctx, iDecrypt)   # MOD decryption (plaintext).
# Program output
echo "Message: ", msg
echo "    Key: ", key
echo "    XOR: ", xctx.tohex
echo "    MOD: ", mctx.toHex
echo "XOR dcr: ", xptx
echo "MOD dcr: ", mptx


PROGRAM RosettaIsaac;
USES
  StrUtils;

TYPE
  iMode = (iEncrypt, iDecrypt);

// TASK globals
VAR
  msg : String = 'a Top Secret secret';
  key : String = 'this is my secret key';
  xctx: String = ''; // XOR ciphertext
  mctx: String = ''; // MOD ciphertext
  xptx: String = ''; // XOR decryption (plaintext)
  mptx: String = ''; // MOD decryption (plaintext)

// ISAAC globals
VAR
  // external results
  randrsl: ARRAY[0 .. 255] OF Cardinal;
  randcnt: Cardinal;

  // internal state
  mm: ARRAY[0 .. 255] OF Cardinal;
  aa: Cardinal = 0;
  bb: Cardinal = 0;
  cc: Cardinal = 0;

PROCEDURE Isaac;
VAR
  i, x, y: Cardinal;
BEGIN
  cc := cc + 1; // cc just gets incremented once per 256 results
  bb := bb + cc; // then combined with bb

  FOR i := 0 TO 255 DO
  BEGIN
    x := mm[i];
    CASE (i MOD 4) OF
      0: aa := aa XOR (aa SHL 13);
      1: aa := aa XOR (aa SHR 6);
      2: aa := aa XOR (aa SHL 2);
      3: aa := aa XOR (aa SHR 16);
    END;
    aa := mm[(i + 128) MOD 256] + aa;
    y  := mm[(x SHR 2) MOD 256] + aa + bb;
    mm[i] := y;
    bb := mm[(y SHR 10) MOD 256] + x;
    randrsl[i] := bb;
  END;
  randcnt := 0; // prepare to use the first set of results
END; // Isaac

PROCEDURE Mix(VAR a, b, c, d, e, f, g, h: Cardinal);
BEGIN
  a := a XOR b SHL 11; d := d + a; b := b + c;
  b := b XOR c SHR  2; e := e + b; c := c + d;
  c := c XOR d SHL  8; f := f + c; d := d + e;
  d := d XOR e SHR 16; g := g + d; e := e + f;
  e := e XOR f SHL 10; h := h + e; f := f + g;
  f := f XOR g SHR  4; a := a + f; g := g + h;
  g := g XOR h SHL  8; b := b + g; h := h + a;
  h := h XOR a SHR  9; c := c + h; a := a + b;
END; // Mix

PROCEDURE iRandInit(flag: Boolean);
VAR
  i, a, b, c, d, e, f, g, h: Cardinal;
BEGIN
  aa := 0; bb := 0; cc := 0;
  a := $9e3779b9; // the golden ratio
  b := a; c := a; d := a; e := a; f := a; g := a; h := a;

  FOR i := 0 TO 3 DO // scramble it
    Mix(a, b, c, d, e, f, g, h);

  i := 0;
  REPEAT // fill in mm[] with messy stuff
    IF flag THEN
    BEGIN // use all the information in the seed
      a += randrsl[i    ]; b += randrsl[i + 1];
      c += randrsl[i + 2]; d += randrsl[i + 3];
      e += randrsl[i + 4]; f += randrsl[i + 5];
      g += randrsl[i + 6]; h += randrsl[i + 7];
    END;

    Mix(a, b, c, d, e, f, g, h);
    mm[i    ] := a; mm[i + 1] := b; mm[i + 2] := c; mm[i + 3] := d;
    mm[i + 4] := e; mm[i + 5] := f; mm[i + 6] := g; mm[i + 7] := h;
    i += 8;
  UNTIL i > 255;

  IF flag THEN
  BEGIN
    // do a second pass to make all of the seed affect all of mm
    i := 0;
    REPEAT
      a += mm[i    ]; b += mm[i + 1]; c += mm[i + 2]; d += mm[i + 3];
      e += mm[i + 4]; f += mm[i + 5]; g += mm[i + 6]; h += mm[i + 7];
      Mix(a, b, c, d, e, f, g, h);
      mm[i    ] := a; mm[i + 1] := b; mm[i + 2] := c; mm[i + 3] := d;
      mm[i + 4] := e; mm[i + 5] := f; mm[i + 6] := g; mm[i + 7] := h;
      i += 8;
    UNTIL i > 255;
  END;
  Isaac(); // fill in the first set of results
  randcnt := 0; // prepare to use the first set of results
END; // iRandInit

// Seed ISAAC with a given string.
// The string can be any size. The first 256 values will be used.
PROCEDURE iSeed(seed: String; flag: Boolean);
VAR
  i, m: Cardinal;
BEGIN
  FOR i := 0 TO 255 DO
    mm[i] := 0;
  m := Length(seed) - 1;
  FOR i := 0 TO 255 DO
  BEGIN
    // in case seed has less than 256 elements
    IF i > m THEN
      randrsl[i] := 0
      // Pascal strings are 1-based
    ELSE
      randrsl[i] := Ord(seed[i + 1]);
  END;
  // initialize ISAAC with seed
  iRandInit(flag);
END; // iSeed

// Get a random 32-bit value 0..MAXINT
FUNCTION iRandom: Cardinal;
BEGIN
  iRandom := randrsl[randcnt];
  inc(randcnt);
  IF (randcnt > 255) THEN
  BEGIN
    Isaac;
    randcnt := 0;
  END;
END; // iRandom

// Get a random character in printable ASCII range
FUNCTION iRandA: Byte;
BEGIN
  iRandA := iRandom MOD 95 + 32;
END;

// Convert an ASCII string to a hexadecimal string
FUNCTION Ascii2Hex(s: String): String;
VAR
  i: Cardinal;
BEGIN
  Ascii2Hex := '';
  FOR i := 1 TO Length(s) DO
    Ascii2Hex += Dec2Numb(Ord(s[i]), 2, 16);
END; // Ascii2Hex

// XOR encrypt on random stream. Output: ASCII string
FUNCTION Vernam(msg: String): String;
VAR
  i: Cardinal;
BEGIN
  Vernam := '';
  FOR i := 1 to Length(msg) DO
    Vernam += Chr(iRandA XOR Ord(msg[i]));
END; // Vernam

// Get position of the letter in chosen alphabet
FUNCTION LetterNum(letter, start: Char): Byte;
BEGIN
  LetterNum := (Ord(letter) - Ord(start));
END; // LetterNum

// Caesar-shift a character <shift> places: Generalized Vigenere
FUNCTION Caesar(m: iMode; ch: Char; shift, modulo: Integer; start: Char): Char;
VAR
  n: Integer;
BEGIN
  IF m = iDecrypt THEN
    shift := -shift;
  n := LetterNum(ch, start) + shift;
  n := n MOD modulo;
  IF n < 0 THEN
    n += modulo;
  Caesar := Chr(Ord(start) + n);
END; // Caesar

// Vigenere MOD 95 encryption & decryption. Output: ASCII string
FUNCTION Vigenere(msg: String; m: iMode): String;
VAR
  i: Cardinal;
BEGIN
  Vigenere := '';
  FOR i := 1 to Length(msg) DO
    Vigenere += Caesar(m, msg[i], iRandA, 95, ' ');
END; // Vigenere

BEGIN
  // 1) seed ISAAC with the key
  iSeed(key, true);
  // 2) Encryption
  // a) XOR (Vernam)
  xctx := Vernam(msg);
  // b) MOD (Vigenere)
  mctx := Vigenere(msg, iEncrypt);
  // 3) Decryption
  iSeed(key, true);
  // a) XOR (Vernam)
  xptx := Vernam(xctx);
  // b) MOD (Vigenere)
  mptx := Vigenere(mctx, iDecrypt);
  // program output
  Writeln('Message: ', msg);
  Writeln('Key    : ', key);
  Writeln('XOR    : ', Ascii2Hex(xctx));
  Writeln('MOD    : ', Ascii2Hex(mctx));
  Writeln('XOR dcr: ', xptx);
  Writeln('MOD dcr: ', mptx);
END.


import fileinput
import sys

nodata = 0;             # Current run of consecutive flags<0 in lines of file
nodata_max=-1;          # Max consecutive flags<0 in lines of file
nodata_maxline=[];      # ... and line number(s) where it occurs

tot_file = 0            # Sum of file data
num_file = 0            # Number of file data items with flag>0

infiles = sys.argv[1:]

for line in fileinput.input():
  tot_line=0;             # sum of line data
  num_line=0;             # number of line data items with flag>0

  # extract field info
  field = line.split()
  date  = field[0]
  data  = [float(f) for f in field[1::2]]
  flags = [int(f)   for f in field[2::2]]

  for datum, flag in zip(data, flags):
    if flag<1:
      nodata += 1
    else:
      # check run of data-absent fields
      if nodata_max==nodata and nodata>0:
        nodata_maxline.append(date)
      if nodata_max<nodata and nodata>0:
        nodata_max=nodata
        nodata_maxline=[date]
      # re-initialise run of nodata counter
      nodata=0;
      # gather values for averaging
      tot_line += datum
      num_line += 1

  # totals for the file so far
  tot_file += tot_line
  num_file += num_line

  print "Line: %11s  Reject: %2i  Accept: %2i  Line_tot: %10.3f  Line_avg: %10.3f" % (
        date,
        len(data) -num_line,
        num_line, tot_line,
        tot_line/num_line if (num_line>0) else 0)

print ""
print "File(s)  = %s" % (", ".join(infiles),)
print "Total    = %10.3f" % (tot_file,)
print "Readings = %6i" % (num_file,)
print "Average  = %10.3f" % (tot_file / num_file,)

print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % (
    nodata_max, ", ".join(nodata_maxline))


use warnings;
use strict;
use Math::Random::ISAAC;

my $message = "a Top Secret secret";
my $key = "this is my secret key";

my $enc = xor_isaac($key, $message);
my $dec = xor_isaac($key, join "", pack "H*", $enc);

print "Message: $message\n";
print "Key    : $key\n";
print "XOR    : $enc\n";
print "XOR dcr: ", join("", pack "H*", $dec), "\n";

sub xor_isaac {
  my($key, $msg) = @_;

  # Make an ISAAC stream with the desired seed
  my $rng = Math::Random::ISAAC->new( map { ord } split "",$key );

  # Get ISAAC output in the order the task wants
  my @iranda = map { $_ % 95 + 32 }  # Alpha-tize as the task desires
               reverse               # MRI gives state from the end
               map { $rng->irand }   # Get random inputs...
               0..255;               # a state chunk at a time
  # Encode:
  join "", map { sprintf "%02X",$_ }         # join hex digits
           map { ord($_) ^ shift(@iranda) }  # xor it with rand char
           split "", $msg;                   # Take each character
}


#Read in data from file
dfr <- read.delim("readings.txt")
#Calculate daily means
flags <- as.matrix(dfr[,seq(3,49,2)])>0
vals <- as.matrix(dfr[,seq(2,49,2)])
daily.means <- rowSums(ifelse(flags, vals, 0))/rowSums(flags)
#Calculate time between good measurements
times <- strptime(dfr[1,1], "%Y-%m-%d", tz="GMT") + 3600*seq(1,24*nrow(dfr),1)
hours.between.good.measurements <- diff(times[t(flags)])/3600


#lang racket
;; Use SRFI 48 to make %n.nf formats convenient.
(require (prefix-in srfi/48: srfi/48)) ; SRFI 48: Intermediate Format Strings

;; Parameter allows us to used exact decimal strings
(read-decimal-as-inexact #f)

;; files to read is a sequence, so it could be either a list or vector of files
(define (text-processing/1 files-to-read)

  (define (print-line-info d r a t)
    (srfi/48:format #t "Line: ~11F  Reject: ~2F  Accept: ~2F  Line_tot: ~10,3F  Line_avg: ~10,3F~%"
                    d r a t (if (zero? a) +nan.0 (/ t a))))

  ;; returns something that can be used as args to an apply
  (define (handle-and-tag-max consecutive-false tag max-consecutive-false max-false-tags)
   (let ((consecutive-false+1 (add1 consecutive-false)))
     (list consecutive-false+1
           (max max-consecutive-false consecutive-false+1)
           (cond ((= consecutive-false+1 max-consecutive-false) (cons tag max-false-tags))
                 ((= consecutive-false max-consecutive-false) (list tag))
                 (else max-false-tags)))))

  (define (sub-t-p/1 N sum consecutive-false max-consecutive-false max-false-tags)
    (for/fold ((N N) (sum sum) (consecutive-false consecutive-false) (max-consecutive-false max-consecutive-false) (max-false-tags max-false-tags))
      ((l (in-lines)))
      (match l
        [(app string-split `(,tag ,(app string->number vs.ss) ...))
         (let get-line-pairs
           ((vs.ss vs.ss) (line-N 0) (reject 0) (line-sum 0) (consecutive-false consecutive-false)
            (max-consecutive-false max-consecutive-false) (max-false-tags max-false-tags))
           (match vs.ss
             ['()
              (print-line-info tag reject line-N line-sum)
              (values (+ N line-N) (+ sum line-sum) consecutive-false max-consecutive-false max-false-tags)]
             [(list-rest v (? positive?) tl)
              (get-line-pairs tl (add1 line-N) reject (+ line-sum v) 0 max-consecutive-false max-false-tags)]
             [(list-rest _ _ tl)
                (apply get-line-pairs tl line-N (add1 reject) line-sum
                       (handle-and-tag-max consecutive-false tag max-consecutive-false max-false-tags))]))]
        (x (fprintf (current-error-port) "mismatch ~s~%" x)
           (values N sum consecutive-false max-consecutive-false max-false-tags)))))

  (for/fold ((N 0) (sum 0) (consecutive-false 0) (max-consecutive-false 0) (max-false-tags null))
    ((f files-to-read))
    (with-input-from-file f
      (lambda () (sub-t-p/1 N sum consecutive-false max-consecutive-false max-false-tags)))))

(let ((files (vector->list (current-command-line-arguments))))
  (let-values (([N sum consecutive-false max-consecutive-false max-false-tags] (text-processing/1 files)))
    (srfi/48:format #t "~%File(s)  = ~a~%Total    = ~10,3F~%Readings = ~6F~%" (string-join files) sum N)
    (unless (zero? N) (srfi/48:format #t "Average  = ~10,3F~%" (/ sum N)))
    (srfi/48:format #t "~%Maximum run(s) of ~a consecutive false readings ends at line starting with date(s): ~a~%"
                    max-consecutive-false (string-join max-false-tags))))


my @gaps;
my $previous = 'valid';

for $*IN.lines -> $line {
    my ($date, @readings) = split /\s+/, $line;
    my @valid;
    my $hour = 0;
    for @readings -> $reading, $flag {
        if $flag > 0 {
            @valid.push($reading);
            if $previous eq 'invalid' {
                @gaps[*-1]{'end'} = "$date $hour:00";
                $previous = 'valid';
            }
        }
        else
        {
            if $previous eq 'valid' {
                @gaps.push( {start => "$date $hour:00"} );
            }
            @gaps[*-1]{'count'}++;
            $previous = 'invalid';
        }
        $hour++;
    }
    say "$date: { ( [email protected] ?? ( ( [+] @valid ) / [email protected] ).fmt("%.3f") !! 0 ).fmt("%8s") }",
        " mean from { ([email protected]).fmt("%2s") } valid.";
};

my $longest = @gaps.sort({-$^a<count>})[0];

say "Longest period of invalid readings was {$longest<count>} hours,\n",
    "from {$longest<start>} till {$longest<end>}."


--
-- demo\rosetta\ISAAC_Cipher.exw
--
with javascript_semantics
sequence randrsl = repeat(0,256)
integer randcnt

sequence mm
atom aa,bb,cc

function r32(object a)
    if sequence(a) then
        for i=1 to length(a) do
            a[i] = r32(a[i])
        end for
        return a
    end if
    if a<0 then a+=#100000000 end if
    return remainder(a,#100000000)
end function

function shl(atom word, integer bits)
    return r32(word*power(2,bits))
end function

function shr(atom v, integer bits)
    return floor(v/power(2,bits))
end function

procedure Isaac()
    cc += 1;    -- cc just gets incremented once per 256 results
    bb += cc;   -- then combined with bb
    for i=1 to 256 do
        atom x = mm[i]
        switch mod(i-1,4) do
            case 0: aa := xor_bits(aa,shl(aa,13))
            case 1: aa := xor_bits(aa,shr(aa, 6))
            case 2: aa := xor_bits(aa,shl(aa, 2))
            case 3: aa := xor_bits(aa,shr(aa,16))
        end switch
        aa = r32(mm[xor_bits(i-1,#80)+1]+aa)
        atom y := mm[and_bits(shr(x,2),#FF)+1]+aa+bb
        mm[i] := y;
        bb := r32(mm[and_bits(shr(y,10),#FF)+1] + x)
        randrsl[i]:= bb;
    end for
    randcnt = 1
end procedure

function mix(sequence a8)
    atom {a,b,c,d,e,f,g,h} = a8
    a = xor_bits(a,shl(b,11));  {d,b} = r32({d+a,b+c});
    b = xor_bits(b,shr(c, 2));  {e,c} = r32({e+b,c+d});
    c = xor_bits(c,shl(d, 8));  {f,d} = r32({f+c,d+e});
    d = xor_bits(d,shr(e,16));  {g,e} = r32({g+d,e+f});
    e = xor_bits(e,shl(f,10));  {h,f} = r32({h+e,f+g});
    f = xor_bits(f,shr(g, 4));  {a,g} = r32({a+f,g+h});
    g = xor_bits(g,shl(h, 8));  {b,h} = r32({b+g,h+a});
    h = xor_bits(h,shr(a, 9));  {c,a} = r32({c+h,a+b});
    a8 = {a,b,c,d,e,f,g,h}
    return a8
end function

procedure iRandInit()
    {aa,bb,cc} = {0,0,0}
    sequence a8 = repeat(#9e3779b9,8)   -- the golden ratio
    for i=1 to 4 do        -- scramble it
        a8 = mix(a8)
    end for
    for i=1 to 255 by 8 do
        a8 = mix(sq_add(a8,randrsl[i..i+7]))
        mm[i..i+7] = a8
    end for
    for i=1 to 255 by 8 do
        a8 = mix(r32(sq_add(a8,mm[i..i+7])))
        mm[i..i+7] = a8
    end for
    Isaac()         -- fill in the first set of results
end procedure

procedure iSeed(string seed)
    mm = repeat(0,256)
    randrsl = repeat(0,256)
    randrsl[1..min(length(seed),256)] = seed
    iRandInit()
end procedure

function randch()
    atom res = mod(randrsl[randcnt],95)+32
    randcnt += 1
    if randcnt>256 then
        Isaac()
    end if
    return res
end function

function Vernam(string msg)
    string res = ""
    for i=1 to length(msg) do
        res &= xor_bits(msg[i],randch())
    end for
    return res
end function

function Caesar(integer ch, shift)
    return ' '+mod(ch-' '+shift,95)
end function

enum ENCRYPT = +1,
     DECRYPT = -1

function Vigenere(string msg, integer mode)
    string res = ""
    for i=1 to length(msg) do
        res &= Caesar(msg[i],randch()*mode)
    end for
    return res
end function

constant string msg = "a Top Secret secret",
                key = "this is my secret key"

iSeed(key)
string xctx := Vernam(msg),
       mctx := Vigenere(msg,ENCRYPT)

iSeed(key)
string xptx := Vernam(xctx),
       mptx := Vigenere(mctx,DECRYPT)

function ascii2hex(string s)
    string res = ""
    for i=1 to length(s) do
        res &= sprintf("%02x",s[i])
    end for
    return res
end function

printf(1,"Message: %s\n",{msg})
printf(1,"Key    : %s\n",{key})
printf(1,"XOR    : %s\n",{ascii2hex(xctx)})
printf(1,"MOD    : %s\n",{ascii2hex(mctx)})
printf(1,"XOR dcr: %s\n",{xptx})
printf(1,"MOD dcr: %s\n",{mptx})

?"done"
{} = wait_key()


print("\033[?1049h\033[H")
print(‘Alternate buffer!’)

L(i) (5.<0).step(-1)
   print(‘Going back in: ’i)
   sleep(1)

print("\033[?1049l")


PROC Wait(BYTE frames)
  BYTE RTCLOK=$14
  frames==+RTCLOK
  WHILE frames#RTCLOK DO OD
RETURN

PROC Main()
  INT size=[960]
  BYTE ARRAY buffer(size)
  BYTE POINTER ptr

  Graphics(0)
  Position(2,10)
  Print("This is the original screen content.")
  Wait(200)

  ptr=PeekC(88)
  MoveBlock(buffer,ptr,size) ;copy screen content

  Put(125) ;clear screen
  Wait(50)
  Position(1,10)
  Print("This is an alternative screen content.")

  Wait(200)
  MoveBlock(ptr,buffer,size) ;restore screen content
RETURN


 10  LET FF = 255:FE = FF - 1
 11  LET FD = 253:FC = FD - 1
 12  POKE FC, 0 : POKE FE, 0
 13  LET R = 768:H =  PEEK (116)
 14  IF  PEEK (R) = 162 GOTO 40

 15  LET L = PEEK (115) > 0
 16  LET H = H - 4 - L
 17  HIMEM:H*256
 18  LET A = 10:B = 11:C = 12
 19  LET D = 13:E = 14:Z = 256
 20  POKE R + 0,162: REMLDX
 21  POKE R + 1,004: REM #$04
 22  POKE R + 2,160: REMLDY
 23  POKE R + 3,000: REM #$00
 24  LET L = R + 4: REMLOOP
 25  POKE L + 0,177: REMLDA
 26  POKE L + 1,FC:: REM($FC),Y
 27  POKE L + 2,145: REMSTA
 28  POKE L + 3,FE:: REM($FE),Y
 29  POKE L + 4,200: REMINY
 30  POKE L + 5,208: REMBNE
 31  POKE L + 6,Z - 7: REMLOOP
 32  POKE L + 7,230: REMINC
 33  POKE L + 8,FD:: REM  $FD
 34  POKE L + 9,230: REMINC
 35  POKE L + A,FF:: REM  $FF
 36  POKE L + B,202: REMDEX
 37  POKE L + C,208: REMBNE
 38  POKE L + D,Z - E: REMLOOP
 39  POKE L + E,096: REMRTS

 40  POKE FD, 4 : POKE FF, H
 41  CALL R : S = PEEK(241)
 42  LET V = PEEK(37)
 43  LET C = PEEK(36)
 44  LET M = PEEK(50)
 45  LET F = PEEK(243)

 50  HOME : INVERSE
 51  PRINT "ALTERNATE BUFFER"
 52  FLASH : SPEED = 125
 53  FOR I = 5 TO 1 STEP -1
 54      PRINT "GOING BACK IN: "I
 55  NEXT I

 60  POKE FD, H : POKE FF, 4
 61  CALL R : POKE 241, S
 62  VTAB V + 1 : HTAB C + 1
 63  POKE 50, M : POKE 243, F


canHandleUnicode?: function [][
    any? @[
        if key? env "LC_ALL"    -> contains? lower get env "LC_ALL" "utf-8"
        if key? env "LC_CTYPE"  -> contains? lower get env "LC_CTYPE" "utf-8"
        if key? env "LANG"      -> contains? lower get env "LANG" "utf-8"
    ]
]

if? canHandleUnicode? ->
    print "Terminal handle unicode and U+25B3 is: △"
else ->
    print "Unicode is not supported on this terminal"


DllCall("AllocConsole")
hConsole:=DllCall("GetConsoleWindow","UPtr")
Stdout:=FileOpen(DllCall("GetStdHandle", "int", -11, "ptr"), "h `n")
Stdin:=FileOpen(DllCall("GetStdHandle", "int", -10, "ptr"), "h `n")

;Full Unicode-support font needed
e:=SetConsoleOutputCP(65001)
if (e && A_IsUnicode)
{
	Print("△ - Unicode delta (U+25b3)")
	GetPos(x,y)
	if (x=0 && y=0) ;nothing prints if Non-Unicode font
		Print("Non-Unicode font")
}
else
	Print("Unicode not supported")
Pause()

Print(string=""){
	global Stdout
	if (!StrLen(string))
		return 1
	e:=DllCall("WriteConsole" . ((A_IsUnicode) ? "W" : "A")
			, "UPtr", Stdout.__Handle
			, "Str", string
			, "UInt", strlen(string)
			, "UInt*", Written
			, "uint", 0)
	if (!e) or (ErrorLevel)
		return 0 ;Failure
	Stdout.Read(0)
	return e
}

SetConsoleOutputCP(codepage) {
	e:=DllCall("SetConsoleOutputCP","UInt",codepage)
	if (!e) or (ErrorLevel)
		return 0 ;Failure
	return 1
}

GetPos(ByRef x, ByRef y) {
	global Stdout
	VarSetCapacity(struct,22,0)
	e:=DllCall("GetConsoleScreenBufferInfo","UPtr",Stdout.__Handle,"Ptr",&struct)
	if (!e) or (ErrorLevel)
			return 0 ;Failure
	x:=NumGet(&struct,4,"UShort")
	y:=NumGet(&struct,6,"UShort")
	return 1
}

Pause() {
	RunWait, %comspec% /c pause>NUL
}


/*REXX program to process  instrument data  from a  data file.                */
numeric digits 20                      /*allow for bigger (precision) numbers.*/
ifid='READINGS.TXT'                    /*the name of the    input    file.    */
ofid='READINGS.OUT'                    /* "    "   "  "     output     "      */
grandSum=0                             /*the grand sum of whole file.         */
grandFlg=0                             /*the grand number of flagged data.    */
grandOKs=0
Lflag=0                                /*the longest period of flagged data.  */
Cflag=0                                /*the longest continous flagged data.  */
w=16                                   /*the width of fields when displayed.  */

  do recs=1  while lines(ifid)\==0     /*keep reading records until finished. */
  rec=linein(ifid)                     /*read the next record (line) of file. */
  parse var rec datestamp Idata        /*pick off the dateStamp and the data. */
  sum=0
  flg=0
  OKs=0

    do j=1  until Idata=''             /*process the  instrument  data.       */
    parse var Idata data.j flag.j Idata

    if flag.j>0 then do                /*process good data ···                */
                     OKs=OKs+1
                     sum=sum+data.j
                     if Cflag>Lflag  then do
                                          Ldate=datestamp
                                          Lflag=Cflag
                                          end
                     Cflag=0
                     end
                else do                /*process flagged data ···             */
                     flg=flg+1
                     Cflag=Cflag+1
                     end
    end   /*j*/

  if OKs\==0  then avg=format(sum/OKs,,3)
              else avg='[n/a]'
  grandOKs=grandOKs+OKs
  _=right(commas(avg),w)
  grandSum=grandSum+sum
  grandFlg=grandFlg+flg
  if flg==0  then call sy datestamp ' average='_
             else call sy datestamp ' average='_ '  flagged='right(flg,2)
  end   /*recs*/

recs=recs-1                            /*adjust for reading the end─of─file.  */
if grandOKs\==0 then Gavg=format(grandSum/grandOKs,,3)
                else Gavg='[n/a]'
call sy
call sy copies('═',60)
call sy '      records read:'   right(commas(recs),     w)
call sy '     grand     sum:'   right(commas(grandSum), w+4)
call sy '     grand average:'   right(commas(Gavg),     w+4)
call sy '     grand OK data:'   right(commas(grandOKs), w)
call sy '     grand flagged:'   right(commas(grandFlg), w)
if Lflag\==0 then call sy '   longest flagged:' right(commas(Lflag),w) " ending at " Ldate
call sy copies('═',60)
exit                                   /*stick a fork in it,  we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
commas: procedure;  parse arg _;   n=_'.9';    #=123456789;    b=verify(n,#,"M")
        e=verify(n,#'0',,verify(n,#"0.",'M'))-4
           do j=e  to b  by -3;   _=insert(',',_,j);    end  /*j*/;     return _
/*────────────────────────────────────────────────────────────────────────────*/
sy:     say arg(1);               call lineout ofid,arg(1);             return


import random
import collections

INT_MASK = 0xFFFFFFFF       # we use this to emulate 32-bit overflow semantics by masking off higher bits after operations

class IsaacRandom(random.Random):
    """
    Random number generator using the ISAAC algorithm.
    """

    def seed(self, seed=None):
        """
        Initialize internal state.

        The seed, if given, can be a string, an integer, or an iterable that contains
        integers only. If no seed is given, a fixed default state is set up; unlike
        our superclass, this class will not attempt to randomize the seed from outside sources.
        """
        def mix():
            init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_state[1] &= INT_MASK
            init_state[1] ^=  (init_state[2]>>2)           ; init_state[4] += init_state[1]; init_state[4] &= INT_MASK; init_state[2] += init_state[3]; init_state[2] &= INT_MASK
            init_state[2] ^= ((init_state[3]<<8 )&INT_MASK); init_state[5] += init_state[2]; init_state[5] &= INT_MASK; init_state[3] += init_state[4]; init_state[3] &= INT_MASK
            init_state[3] ^=  (init_state[4]>>16)          ; init_state[6] += init_state[3]; init_state[6] &= INT_MASK; init_state[4] += init_state[5]; init_state[4] &= INT_MASK
            init_state[4] ^= ((init_state[5]<<10)&INT_MASK); init_state[7] += init_state[4]; init_state[7] &= INT_MASK; init_state[5] += init_state[6]; init_state[5] &= INT_MASK
            init_state[5] ^=  (init_state[6]>>4 )          ; init_state[0] += init_state[5]; init_state[0] &= INT_MASK; init_state[6] += init_state[7]; init_state[6] &= INT_MASK
            init_state[6] ^= ((init_state[7]<<8 )&INT_MASK); init_state[1] += init_state[6]; init_state[1] &= INT_MASK; init_state[7] += init_state[0]; init_state[7] &= INT_MASK
            init_state[7] ^=  (init_state[0]>>9 )          ; init_state[2] += init_state[7]; init_state[2] &= INT_MASK; init_state[0] += init_state[1]; init_state[0] &= INT_MASK

        super().seed(0) # give a chance for the superclass to reset its state - the actual seed given to it doesn't matter
        if seed is not None:
            if isinstance(seed, str):
                seed = [ord(x) for x in seed]
            elif isinstance(seed, collections.Iterable):
                seed = [x & INT_MASK for x in seed]
            elif isinstance(seed, int):
                val = abs(seed)
                seed = []
                while val:
                    seed.append(val & INT_MASK)
                    val >>= 32
            else:
                raise TypeError('Seed must be string, integer or iterable of integer')

            # make sure the seed list is exactly 256 elements long
            if len(seed)>256:
                del seed[256:]
            elif len(seed)<256:
                seed.extend([0]*(256-len(seed)))

        self.aa = self.bb = self.cc = 0
        self.mm = []
        init_state = [0x9e3779b9]*8

        for _ in range(4):
            mix()

        for i in range(0, 256, 8):
            if seed is not None:
                for j in range(8):
                    init_state[j] += seed[i+j]
                    init_state[j] &= INT_MASK
            mix()
            self.mm += init_state

        if seed is not None:
            for i in range(0, 256, 8):
                for j in range(8):
                    init_state[j] += self.mm[i+j]
                    init_state[j] &= INT_MASK
                mix()
                for j in range(8):
                    self.mm[i+j] = init_state[j]

        self.rand_count = 256
        self.rand_result = [0]*256

    def getstate(self):
        return super().getstate(), self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result

    def setstate(self, state):
        super().setstate(state[0])
        _, self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result = state

    def _generate(self):
        # Generate 256 random 32-bit values and save them in an internal field.
        # The actual random functions will dish out these values to callers.
        self.cc = (self.cc + 1) & INT_MASK
        self.bb = (self.bb + self.cc) & INT_MASK

        for i in range(256):
            x = self.mm[i]
            mod = i & 3
            if mod==0:
                self.aa ^= ((self.aa << 13) & INT_MASK)
            elif mod==1:
                self.aa ^= (self.aa >> 6)
            elif mod==2:
                self.aa ^= ((self.aa << 2) & INT_MASK)
            else: # mod == 3
                self.aa ^= (self.aa >> 16)
            self.aa = (self.mm[i^128] + self.aa) & INT_MASK
            y = self.mm[i] = (self.mm[(x>>2) & 0xFF] + self.aa + self.bb) & INT_MASK
            self.rand_result[i] = self.bb = (self.mm[(y>>10) & 0xFF] + x) & INT_MASK

        self.rand_count = 0

    def next_int(self):
        """Return a random integer between 0 (inclusive) and 2**32 (exclusive)."""
        if self.rand_count == 256:
            self._generate()
        result = self.rand_result[self.rand_count]
        self.rand_count += 1
        return result

    def getrandbits(self, k):
        """Return a random integer between 0 (inclusive) and 2**k (exclusive)."""
        result = 0
        ints_needed = (k+31)//32
        ints_used = 0
        while ints_used < ints_needed:
            if self.rand_count == 256:
                self._generate()
            ints_to_take = min(256-self.rand_count, ints_needed)
            for val in self.rand_result[self.rand_count : self.rand_count+ints_to_take]:
                result = (result << 32) | val
            self.rand_count += ints_to_take
            ints_used += ints_to_take
        result &= ((1<<k)-1)    # mask off extra bits, if any
        return result

    def random(self):
        """Return a random float between 0 (inclusive) and 1 (exclusive)."""
        # A double stores 53 significant bits, so scale a 53-bit integer into the [0..1) range.
        return self.getrandbits(53) * (2**-53)

    def rand_char(self):
        """Return a random integer from the printable ASCII range [32..126]."""
        return self.next_int() % 95 + 32

    def vernam(self, msg):
        """
        Encrypt/decrypt the given bytes object with the XOR algorithm, using the current generator state.

        To decrypt an encrypted string, restore the state of the generator to the state it had
        during encryption, then call this method with the encrypted string.
        """
        return bytes((self.rand_char() & 0xFF) ^ x for x in msg)

    # Constants for selecting Caesar operation modes.
    ENCIPHER = 'encipher'
    DECIPHER = 'decipher'

    @staticmethod
    def _caesar(ciphermode, ch, shift, modulo, start):
        if ciphermode == IsaacRandom.DECIPHER:
            shift = -shift
        n = ((ch-start)+shift) % modulo
        if n<0:
            n += modulo
        return start+n

    def caesar(self, ciphermode, msg, modulo, start):
        """
        Encrypt/decrypt a string using the Caesar algorithm.

        For decryption to work, the generator must be in the same state it was during encryption,
        and the same modulo and start parameters must be used.

        ciphermode must be one of IsaacRandom.ENCIPHER or IsaacRandom.DECIPHER.
        """
        return bytes(self._caesar(ciphermode, ch, self.rand_char(), modulo, start) for ch in msg)

if __name__=='__main__':
    import binascii

    def hexify(b):
        return binascii.hexlify(b).decode('ascii').upper()

    MOD = 95
    START = 32

    msg = 'a Top Secret secret'
    key = 'this is my secret key'
    isaac_random = IsaacRandom(key)
    vernam_encoded = isaac_random.vernam(msg.encode('ascii'))
    caesar_encoded = isaac_random.caesar(IsaacRandom.ENCIPHER, msg.encode('ascii'), MOD, START)
    isaac_random.seed(key)
    vernam_decoded = isaac_random.vernam(vernam_encoded).decode('ascii')
    caesar_decoded = isaac_random.caesar(IsaacRandom.DECIPHER, caesar_encoded, MOD, START).decode('ascii')

    print('Message:', msg)
    print('Key    :', key)
    print('XOR    :', hexify(vernam_encoded))
    print('XOR dcr:', vernam_decoded)
    print('MOD    :', hexify(caesar_encoded))
    print('MOD dcr:', caesar_decoded)


      PRINT "This is the original screen"
      OSCLI "GSAVE """ + @tmp$ + "bbcsave"""
      WAIT 200
      CLS
      PRINT "This is the new screen, following a CLS"
      WAIT 200
      OSCLI "DISPLAY """ + @tmp$ + "bbcsave"""


#include <stdio.h>
#include <unistd.h>

int main()
{
	int i;
	printf("\033[?1049h\033[H");
	printf("Alternate screen buffer\n");
	for (i = 5; i; i--) {
		printf("\rgoing back in %d...", i);
		fflush(stdout);
		sleep(1);
	}
	printf("\033[?1049l");

	return 0;
}


(format t "~C[?1049h~C[H" (code-char #O33) (code-char #O33))
(format t "Alternate screen buffer~%")
(loop for i from 5 downto 1 do (progn
                             (format t "~%going back in ~a" i)
                             (sleep 1)
                             ))
(format t "~C[?1049l" (code-char #O33))


#!/usr/local/bin/emacs --script
;; -*- lexical-binding: t; -*-

;; "ESC [ ? 1049 h" - Enable alternative screen buffer
(princ "\033[?1049h")
(princ "Alternate screen buffer\n")

(let ((i 5))
  (while (> i 0)
    (princ (format "\rgoing back in %d..." i))
    ;; flush stdout
    (set-binary-mode 'stdout t)
    (sleep-for 1)
    (setq i (1- i))))

;; "ESC [ ? 1049 l" - Disable alternative screen buffer
(princ "\033[?1049l")


.\" \033[?1049h\033[H"  \ preserve screen
." Press any key to return" ekey drop
.\" \033[?1049l"  \ restore screen


#!/usr/bin/awk -f
BEGIN {
  unicodeterm=1   # Assume Unicode support
  if (ENVIRON["LC_ALL"] !~ "UTF") {
    if (ENVIRON["LC_ALL"] != ""
      unicodeterm=0    # LC_ALL is the boss, and it says nay
    else {
      # Check other locale settings if LC_ALL override not set
      if (ENVIRON["LC_CTYPE"] !~ "UTF") {
        if (ENVIRON["LANG"] !~ "UTF")
          unicodeterm=0    # This terminal does not support Unicode
      }
    }
  }

  if (unicodeterm) {
      # This terminal supports Unicode
      # We need a Unicode compatible printf, so we source this externally
      # printf might not know \u or \x, so use octal.
      # U+25B3 => UTF-8 342 226 263
      "/usr/bin/printf \\342\\226\\263\\n"
  } else {
      print "HW65001 This program requires a Unicode compatible terminal"|"cat 1>&2"
    exit 252    # Incompatible hardware
  }


' Determine if the terminal supports Unicode
' if so display delta, if not display error message
LET lc$ = GETENVIRON$("LANG")
IF INSTR(LCASE$(lc$), "utf8") != 0 THEN
    PRINT UTF8$(0x25B3)
ELSE
    EPRINT "Sorry, terminal is not testing as unicode ready"
END IF


      VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 mode
      *FONT Arial Unicode MS,36
      PRINT CHR$(&E2)+CHR$(&96)+CHR$(&B3)


#include<stdlib.h>
#include<stdio.h>

int
main ()
{
  int i;
  char *str = getenv ("LANG");

  for (i = 0; str[i + 2] != 00; i++)
    {
      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
        {
          printf
            ("Unicode is supported on this terminal and U+25B3 is : \u25b3");
          i = -1;
          break;
        }
    }

  if (i != -1)
    printf ("Unicode is not supported on this terminal.");

  return 0;
}


filename = "readings.txt"
total = { "num_readings" => 0, "num_good_readings" => 0, "sum_readings" => 0.0 }
invalid_count = 0
max_invalid_count = 0
invalid_run_end = ""

File.new(filename).each do |line|
  num_readings = 0
  num_good_readings = 0
  sum_readings = 0.0

  fields = line.split
  fields[1..-1].each_slice(2) do |reading, flag|
    num_readings += 1
    if Integer(flag) > 0
      num_good_readings += 1
      sum_readings += Float(reading)
      invalid_count = 0
    else
      invalid_count += 1
      if invalid_count > max_invalid_count
        max_invalid_count = invalid_count
        invalid_run_end = fields[0]
      end
    end
  end

  printf "Line: %11s  Reject: %2d  Accept: %2d  Line_tot: %10.3f  Line_avg: %10.3f\n",
    fields[0], num_readings - num_good_readings, num_good_readings, sum_readings,
    num_good_readings > 0 ? sum_readings/num_good_readings : 0.0

  total["num_readings"] += num_readings
  total["num_good_readings"] += num_good_readings
  total["sum_readings"] += sum_readings
end

puts ""
puts "File(s)  = #{filename}"
printf "Total    = %.3f\n", total['sum_readings']
puts "Readings = #{total['num_good_readings']}"
printf "Average  = %.3f\n", total['sum_readings']/total['num_good_readings']
puts ""
puts "Maximum run(s) of #{max_invalid_count} consecutive false readings ends at #{invalid_run_end}"


object DataMunging {
  import scala.io.Source

  def spans[A](list: List[A]) = list.tail.foldLeft(List((list.head, 1))) {
    case ((a, n) :: tail, b) if a == b => (a, n + 1) :: tail
    case (l, b) => (b, 1) :: l
  }

  type Flag = ((Boolean, Int), String)
  type Flags = List[Flag]
  type LineIterator = Iterator[Option[(Double, Int, Flags)]]

  val pattern = """^(\d+-\d+-\d+)""" + """\s+(\d+\.\d+)\s+(-?\d+)""" * 24 + "$" r;

  def linesIterator(file: java.io.File) = Source.fromFile(file).getLines().map(
    pattern findFirstMatchIn _ map (
      _.subgroups match {
        case List(date, rawData @ _*) =>
          val dataset = (rawData map (_ toDouble) iterator) grouped 2 toList;
          val valid = dataset filter (_.last > 0) map (_.head)
          val validSize = valid length;
          val validSum = valid sum;
          val flags = spans(dataset map (_.last > 0)) map ((_, date))
          println("Line: %11s  Reject: %2d  Accept: %2d  Line_tot: %10.3f  Line_avg: %10.3f" format
                  (date, 24 - validSize, validSize, validSum, validSum / validSize))
          (validSum, validSize, flags)
      }
    )
  )

  def totalizeLines(fileIterator: LineIterator) =
    fileIterator.foldLeft(0.0, 0, List[Flag]()) {
      case ((totalSum, totalSize, ((flag, size), date) :: tail), Some((validSum, validSize, flags))) =>
        val ((firstFlag, firstSize), _) = flags.last
        if (firstFlag == flag) {
          (totalSum + validSum, totalSize + validSize, flags.init ::: ((flag, size + firstSize), date) :: tail)
        } else {
          (totalSum + validSum, totalSize + validSize, flags ::: ((flag, size), date) :: tail)
        }
      case ((_, _, Nil), Some(partials)) => partials
      case (totals, None) => totals
    }

  def main(args: Array[String]) {
    val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead)
    val lines =  files.iterator flatMap linesIterator
    val (totalSum, totalSize, flags) = totalizeLines(lines)
    val ((_, invalidCount), startDate) = flags.filter(!_._1._1).max
    val report = """|
                    |File(s)  = %s
                    |Total    = %10.3f
                    |Readings = %6d
                    |Average  = %10.3f
                    |
                    |Maximum run(s) of %d consecutive false readings began at %s""".stripMargin
    println(report format (files mkString " ", totalSum, totalSize, totalSum / totalSize, invalidCount, startDate))
  }
}


#lang racket
;; Imperative version: Translation of C
;; Vigenère:           Translation of Pascal
(module+ test (require tests/eli-tester))

;; ---------------------------------------------------------------------------------------------------
;; standard.h: Standard definitions and types, Bob Jenkins
(define UB4MAXVAL #xffffffff)
(define-syntax-rule (bit target mask) (bitwise-and target mask))
;; C-like operators
(define-syntax-rule (u4-truncate x) (bit x UB4MAXVAL))
(define-syntax-rule (u4<< a b)      (u4-truncate (arithmetic-shift a b)))
(define-syntax-rule (u4>> a b)      (u4-truncate (arithmetic-shift a (- b))))
(define-syntax-rule (_++ i)         (let ((rv i)) (set! i (u4-truncate (add1 i))) rv))
(define-syntax-rule (u4+= a b)      (begin (set! a (u4-truncate (+ a b))) a))
(define-syntax-rule (^= a b)        (begin (set! a (u4-truncate (bitwise-xor a b))) a))

;; ---------------------------------------------------------------------------------------------------
;; rand.h: definitions for a random number generator
(define RANDSIZL  8)
(define RANDSIZ   (u4<< 1 RANDSIZL))
(define RANDSIZ-1 (sub1 RANDSIZ))

(struct randctx
  (cnt
   rsl ; RANDSIZ*4 bytes (makes u4's)
   mem ; RANDSIZ*4 bytes (makes u4's)
   a b c) #:mutable)

(define (new-randctx)
  (randctx 0 (make-bytes (* 4 RANDSIZ) 0) (make-bytes (* 4 RANDSIZ) 0) 0 0 0))

(define (bytes->hex-string B (start 0) (end #f) #:join (join "") #:show-bytes? (show-bytes? #f))
  (define hexes
    (for/list ((b (in-bytes B start end)))
      (~a (number->string b 16) #:width 2 #:align 'right #:pad-string "0")))
  (string-join
   (append hexes (if show-bytes?
                     (list " \"" (bytes->string/utf-8 B #f start (or end (bytes-length B))) "\"")
                     null))
   join))

(define format-randctx
  (match-lambda
    [(randctx C (app bytes->hex-string R) (app bytes->hex-string M) a b c)
     (format "randctx: cnt:~a~%rsl:~s~%mem:~s~%a:~a b:~a c:~a" C R M a b c)]))

(define be? (system-big-endian?))

(define (bytes->u4 ary idx)
  (integer-bytes->integer ary #f be? (* idx 4) (* (add1 idx) 4)))

(define (u4->bytes! ary idx v)
  (integer->integer-bytes (bit v UB4MAXVAL) 4 #f be? ary (* idx 4)))

;; ---------------------------------------------------------------------------------------------------
;; rand.c: "By Bob Jenkins.  My random number generator, ISAAC.  Public Domain."
(define (ind mm x)
  (define idx (bitwise-and x (u4<< RANDSIZ-1 2)))
  (integer-bytes->integer mm #f be? idx (+ idx 4)))

(define (isaac C)
  (define M (randctx-mem C))
  (define R (randctx-rsl C))
  (define mm 0)
  (define r  0)
  (define-syntax-rule (rng-step mix)
    (begin
      (define x (bytes->u4 M m))
      (set! a (u4-truncate (+ (bitwise-xor a mix) (bytes->u4 M (_++ m2)))))
      (define y (+ (ind M x) a b))
      (u4->bytes! M (_++ m) y)
      (set! b (u4-truncate (+ (ind M (u4>> y RANDSIZL)) x)))
      (u4->bytes! R (_++ r) b)))

  (define a (randctx-a C))

  (set-randctx-c! C (add1 (randctx-c C)))

  (define b (u4-truncate (+ (randctx-b C) (randctx-c C))))

  (define m mm)
  (define m2 (+ m (/ RANDSIZ 2)))
  (define mend m2)

  (define-syntax-rule (4-step-loop variant)
    (let loop ()
      (when (< variant mend)
        (rng-step (u4<< a 13)) (rng-step (u4>> a 6))
        (rng-step (u4<< a  2)) (rng-step (u4>> a 16))
        (loop))))

  (4-step-loop m)
  (set! m2 mm)
  (4-step-loop m2)

  (set-randctx-b! C b)
  (set-randctx-a! C a))

;; dot infix notation because I'm too lazy to move the operators left!
(define-syntax-rule (mix-line<< A B N D C)
  (begin (A . ^= . (B . u4<< . N)) (D . u4+= . A) (B . u4+= . C)))
(define-syntax-rule (mix-line>> A B N D C)
  (begin (A . ^= . (B . u4>> . N)) (D . u4+= . A) (B . u4+= . C)))

(define-syntax-rule (mix a b c d e f g h)
  (begin (mix-line<< a b 11 d c) (mix-line>> b c  2 e d)
         (mix-line<< c d  8 f e) (mix-line>> d e 16 g f)
         (mix-line<< e f 10 h g) (mix-line>> f g  4 a h)
         (mix-line<< g h  8 b a) (mix-line>> h a  9 c b)))

;; if (flag==TRUE), then use the contents of randrsl[] to initialize mm[].
(define (rand-init C flag?)
  (set-randctx-a! C 0)
  (set-randctx-b! C 0)
  (set-randctx-c! C 0)

  ;; seed-ctx should set these up (with the seed!):
  ;;   (set-ctx-rsl! C (make-bytes (* 4 RANDSIZ) 0))
  ;;   (set-ctx-mem! C (make-bytes (* 4 RANDSIZ) 0))
  (define R (randctx-rsl C))
  (define M (randctx-mem C))

  (define φ #x9e3779b9) ; the golden ratio
  (match-define (list a b c d e f g h) (make-list 8 φ))

  (for ((_ 4)) (mix a b c d e f g h)) ; scramble it

  (define-syntax-rule (mix-and-assign i M2)
    (begin
      (mix a b c d e f g h)
      (u4->bytes! M2 (+ i 0) a) (u4->bytes! M2 (+ i 1) b)
      (u4->bytes! M2 (+ i 2) c) (u4->bytes! M2 (+ i 3) d)
      (u4->bytes! M2 (+ i 4) e) (u4->bytes! M2 (+ i 5) f)
      (u4->bytes! M2 (+ i 6) g) (u4->bytes! M2 (+ i 7) h)))

  (define-syntax-rule (mix-with-mem M1 M2)
    (for ((i (in-range 0 RANDSIZ 8)))
      (a . u4+= . (bytes->u4 M1 (+ i 0))) (b . u4+= . (bytes->u4 M1 (+ i 1)))
      (c . u4+= . (bytes->u4 M1 (+ i 2))) (d . u4+= . (bytes->u4 M1 (+ i 3)))
      (e . u4+= . (bytes->u4 M1 (+ i 4))) (f . u4+= . (bytes->u4 M1 (+ i 5)))
      (g . u4+= . (bytes->u4 M1 (+ i 6))) (h . u4+= . (bytes->u4 M1 (+ i 7)))
      (mix-and-assign i M2)))

  (cond
    [flag? ; initialize using the contents of r[] as the seed
     (mix-with-mem R M)
     (mix-with-mem M M)] ; do a second pass to make all of the seed affect all of m
    [else ; fill in m[] with messy stuff
     (for ((i (in-range 0 RANDSIZ 8))) (mix-and-assign i M))])

  (isaac C)  ; fill in the first set of results
  (set-randctx-cnt! C 0)) ; prepare to use the first set of results

(define (seed-ctx C key #:flag? (flag? #t))
  (bytes-fill! (randctx-mem C) 0)
  (define R (randctx-rsl C))
  (bytes-fill! (randctx-rsl C) 0)
  (for ((k (in-bytes key)) (i (in-range (quotient (bytes-length R) 4)))) (u4->bytes! R i k))
  (rand-init C flag?))

;; Get a random 32-bit value 0..MAXINT
(define (i-random C)
  (define cnt (randctx-cnt C))
  (define r (bytes->u4 (randctx-rsl C) cnt))
  (define cnt+1 (add1 cnt))
  (cond [(>= cnt+1 RANDSIZ) (isaac C) (set-randctx-cnt! C 0)]
        [else (set-randctx-cnt! C cnt+1)])
  r)

;; Get a random character in printable ASCII range
(define ((i-rand-a C))
  (+ 32 (modulo (i-random C) 95)))

(define (Vernham rnd-fn msg)
  (define gsm (make-bytes (bytes-length msg)))
  (for ((i (in-naturals)) (m (in-bytes msg)))
    (define r (rnd-fn))
    (define b (bitwise-xor m r))
    (bytes-set! gsm i b))
  gsm)

;; Get position of the letter in chosen alphabet
;; Caesar-shift a character <shift> places: Generalized Vigenere
(define ((Caesar mod-n start) encrypt? shift ch)
  (define (letter-num letter/byte)
    (- letter/byte (char->integer start)))

  (define shift-fn (if encrypt? + -))
  (+ (char->integer start) (modulo (shift-fn (letter-num ch) shift) mod-n)))

;; Vigenère mod 95 encryption & decryption. Output: bytes
(define Vigenère-Caeser (Caesar 95 #\space))
(define (Vigenère encrypt? rand-fn msg)
  (list->bytes
   (for/list ((b (in-bytes msg)))
     (Vigenère-Caeser encrypt? (rand-fn) b))))

{module+ main
  (define message #"a Top Secret secret")
  (define key     #"this is my secret key")
  (define C (new-randctx))
  (seed-ctx C key)
  (define vern.msg (Vernham (i-rand-a C) message))
  ;; Pascal doesn't reset the context betwen XOR and MOD
  ;; (seed-ctx C key)
  (define vigen.msg (Vigenère #t (i-rand-a C) message))
  (seed-ctx C key)
  (define vern2.msg (Vernham (i-rand-a C) vern.msg))
  ;; Pascal doesn't reset the context betwen XOR and MOD
  ;; (seed-ctx C key)
  (define unvigen.msg (Vigenère #f (i-rand-a C) vigen.msg))
  ;; This is what MOD looks like from the context as seeded with key
  (seed-ctx C key)
  (define vigen-at-seed.msg (Vigenère #t (i-rand-a C) message))
  (seed-ctx C key)
  (define unvigen-at-seed.msg (Vigenère #f (i-rand-a C) vigen-at-seed.msg))

  (printf #<<EOS
Message:            [~a]
Key:                [~a]

                    < context reseeded
Vernham (XOR):      [~a]
Vigenère (MOD):     [~a]

                    < context reseeded
Vernham (XOR(XOR)): [~a]
Vigenère (-MOD):    [~a]

                    < context reseeded (different to Pascal Vigenère encryption)
Vigenère (MOD):     [~a]
                    < context reseeded
Vigenère (-MOD):    [~a]
EOS
          message
          key
          (bytes->hex-string vern.msg)
          (bytes->hex-string vigen.msg #:show-bytes? #t)
          (bytes->hex-string vern2.msg #:show-bytes? #t)
          (bytes->hex-string unvigen.msg #:show-bytes? #t)
          (bytes->hex-string vigen-at-seed.msg #:show-bytes? #t)
          (bytes->hex-string unvigen-at-seed.msg #:show-bytes? #t)
          )}

{module+ test
  ;; "If the initial internal state is all zero, after ten calls the values of aa, bb, and cc in
  ;; hexadecimal will be d4d3f473, 902c0691, and 0000000a."
  (let ()
    (define C (new-randctx))
    (for ((_ 10)) (isaac C))
    (test (randctx-a C) => #xd4d3f473
          (randctx-b C) => #x902c0691
          (randctx-c C) => 10))
  }


my uint32 (@mm, @randrsl, $randcnt, $aa, $bb, $cc);
my \ϕ := 2654435769; constant MOD = 95; constant START = 32;

constant MAXINT = uint.Range.max;
enum CipherMode < ENCIPHER DECIPHER NONE >;

sub mix (\n) {
   sub mix1 (\i, \v) {
      n[i] +^= v;
      n[(i+3)%8] += n[i];
      n[(i+1)%8] += n[(i+2)%8];
   }
   mix1 0, n[1]+<11; mix1 1, n[2]+>2; mix1 2, n[3]+<8; mix1 3, n[4]+>16;
   mix1 4, n[5]+<10; mix1 5, n[6]+>4; mix1 6, n[7]+<8; mix1 7, n[0]+>9 ;
}

sub randinit(\flag) {
   $aa = $bb = $cc = 0;
   my uint32 @n = [^8].map({ ϕ });
   for ^4 { mix @n };
   for 0,8 … 255 -> $i {
      { for (0..7) { @n[$^j] += @randrsl[$i + $^j] } } if flag;
      mix @n;
      for (0..7) { @mm[$i + $^j] = @n[$^j] }
   }
   if flag {
      for 0,8 … 255 -> $i {
         for ^8 { @n[$^j] += @mm[$i + $^j] };
         mix @n;
         for ^8 { @mm[$i + $^j] = @n[$^j] };
      }
   }
   isaac;
   $randcnt = 0;
}

sub isaac() {
   $cc++;
   $bb += $cc;
   for ^256 -> $i {
      my $x = @mm[$i];
      given ($i % 4) {
         when 0 { $aa +^= ($aa +< 13) }
         when 1 { $aa +^= (($aa +& MAXINT) +>  6) }
         when 2 { $aa +^= ($aa +<  2) }
         when 3 { $aa +^= (($aa +& MAXINT) +> 16) }
      }
      $aa += @mm[($i + 128) % 256];
      my $y = @mm[(($x +& MAXINT) +> 2) % 256] + $aa + $bb;
      @mm[$i] = $y;
      $bb = @mm[(($y +& MAXINT) +> 10) % 256] + $x;
      @randrsl[$i] = $bb;
   }
   $randcnt = 0;
}

sub iRandom {
   my $result = @randrsl[$randcnt++];
   if ($randcnt > 255) {
      isaac;
      $randcnt = 0;
   }
   return $result;
}

sub iSeed(\seed, \flag) {
    @mm = [^256].race.map({0});
    my \m = seed.chars;
    @randrsl = [^256].hyper.map({ $^i ≥ m ?? 0 !! seed.substr($^i,1).ord });
    randinit(flag);
}

sub iRandA { return iRandom() % MOD + START };

sub vernam(\M) { ( map { (iRandA() +^ .ord ).chr }, M.comb ).join };

sub caesar(CipherMode \m, \ch, $shift is copy, \Modulo, \Start) {
    $shift = -$shift if m == DECIPHER;
    my $n = (ch.ord - Start) + $shift;
    $n %= Modulo;
    $n += Modulo if $n < 0;
    return (Start + $n).chr;
}

sub caesarStr(CipherMode \m, \msg, \Modulo, \Start) {
   my $sb = '';
   for msg.comb {
        $sb ~= caesar m, $^c, iRandA(), Modulo, Start;
   }
   return $sb;
}

multi MAIN () {
   my \msg = "a Top Secret secret";
   my \key = "this is my secret key";

   iSeed key, True ;
   my $vctx = vernam msg;
   my $cctx = caesarStr ENCIPHER, msg,  MOD, START;

   iSeed key, True ;
   my $vptx = vernam $vctx;
   my $cptx = caesarStr DECIPHER, $cctx, MOD, START;

   my $vctx2hex = ( map { .ord.fmt('%02X') }, $vctx.comb ).join('');
   my $cctx2hex = ( map { .ord.fmt('%02X') }, $cctx.comb ).join('');

   say "Message : ", msg;
   say "Key     : ", key;
   say "XOR     : ", $vctx2hex;
   say "XOR dcr : ", $vptx;
   say "MOD     : ", $cctx2hex;
   say "MOD dcr : ", $cptx;
}


'' 640x480x8, with 3 pages
Screen 12,,3
Windowtitle "Terminal control/Preserve screen"

'' text for working page #2 (visible page #0)
Screenset 2, 0
Cls
Print "This is the new screen, following a CLS"

'' text for working page #1 (visible page #0)
Screenset 1, 0
Cls
Print "This is the original screen"

' page #0 is the working page (visible page #0)
Screenset 0, 0

Screencopy 1, 0
Sleep 1000 '1 second
Screencopy 2, 0
Sleep 1000
Print
For i As Byte = 5 To 1 Step -1
    Print "Going back in: "; i
    Sleep 1000
Next i
Screencopy 1, 0
Sleep


package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Print("\033[?1049h\033[H")
    fmt.Println("Alternate screen buffer\n")
    s := "s"
    for i := 5; i > 0; i-- {
        if i == 1 {
            s = ""
        }
        fmt.Printf("\rgoing back in %d second%s...", i, s)
        time.Sleep(time.Second)
    }
    fmt.Print("\033[?1049l")
}


public class PreserveScreen
{
    public static void main(String[] args) throws InterruptedException {
        System.out.print("\033[?1049h\033[H");
        System.out.println("Alternate screen buffer\n");
        for (int i = 5; i > 0; i--) {
            String s = (i > 1) ? "s" : "";
            System.out.printf("\rgoing back in %d second%s...", i, s);
            Thread.sleep(1000);
        }
        System.out.print("\033[?1049l");
    }
}


(if-not (empty? (filter #(and (not (nil? %)) (.contains (.toUpperCase %) "UTF"))
  (map #(System/getenv %) ["LANG" "LC_ALL" "LC_CTYPE"])))
    "Unicode is supported on this terminal and U+25B3 is : \u25b3"
    "Unicode is not supported on this terminal.")


(defun my-getenv (name &optional default)
  #+CMU
  (let ((x (assoc name ext:*environment-list*
                  :test #'string=)))
    (if x (cdr x) default))
  #-CMU
  (or
    #+Allegro (sys:getenv name)
    #+CLISP (ext:getenv name)
    #+ECL (si:getenv name)
    #+SBCL (sb-unix::posix-getenv name)
    #+ABCL (getenv name)
    #+LISPWORKS (lispworks:environment-variable name)
    default))

(if (not ( null (remove-if #'null (mapcar #'my-getenv '("LANG" "LC_ALL" "LC_CTYPE")))))
  (format t "Unicode is supported on this terminal and U+25B3 is : ~a~&" (code-char #x25b3))
  (format t "Unicode is not supported on this terminal.~&")
  )


if ["LANG", "LC_CTYPE", "LC_ALL"]
     |> Enum.map(&System.get_env/1)
     |> Enum.any?(&(&1 != nil and String.contains?(&1, "UTF")))
do
  IO.puts "This terminal supports Unicode: \x{25b3}"
else
  raise "This terminal does not support Unicode."
end


Print "Terminal handle unicode and U+25B3 is: "; WChr(&H25B3)


if map( v -> System.getenv(v), ["LC_ALL", "LC_CTYPE", "LANG"]).filter( (!= null) ).exists( ('UTF' in) )
  println( '\u25b3' )
else
  println( 'Unicode not supported' )


var gaps = [];
var previous = :valid;

ARGF.each { |line|
    var (date, *readings) = line.words...;
    var valid = [];
    var hour = 0;
    readings.map{.to_n}.each_slice(2, { |slice|
        var(reading, flag) = slice...;
        if (flag > 0) {
            valid << reading;
            if (previous == :invalid) {
                gaps[-1]{:end} = "#{date} #{hour}:00";
                previous = :valid;
            }
        }
        else {
            if (previous == :valid) {
                gaps << Hash(start => "#{date} #{hour}:00");
            }
            gaps[-1]{:count} := 0 ++;
            previous = :invalid;
        }
        ++hour;
    })
    say ("#{date}: #{ '%8s' % (valid ? ('%.3f' % Math.avg(valid...)) : 0) }",
         " mean from #{ '%2s' % valid.len } valid.");
}

var longest = gaps.sort_by{|a| -a{:count} }.first;

say ("Longest period of invalid readings was #{longest{:count}} hours,\n",
    "from #{longest{:start}} till #{longest{:end}}.");


import Foundation

let fmtDbl = { String(format: "%10.3f", $0) }

Task.detached {
  let formatter = DateFormatter()

  formatter.dateFormat = "yyyy-MM-dd"

  let (data, _) = try await URLSession.shared.bytes(from: URL(fileURLWithPath: CommandLine.arguments[1]))
  var rowStats = [(Date, Double, Int)]()
  var invalidPeriods = 0
  var invalidStart: Date?
  var sumFile = 0.0
  var readings = 0
  var longestInvalid = 0
  var longestInvalidStart: Date?
  var longestInvalidEnd: Date?

  for try await line in data.lines {
    let lineSplit = line.components(separatedBy: "\t")

    guard !lineSplit.isEmpty, let date = formatter.date(from: lineSplit[0]) else {
      fatalError("Invalid date \(lineSplit[0])")
    }

    let data = Array(lineSplit.dropFirst())
    let parsed = stride(from: 0, to: data.endIndex, by: 2).map({idx -> (Double, Int) in
      let slice = data[idx..<idx+2]

      return (Double(slice[idx]) ?? 0, Int(slice[idx+1]) ?? 0)
    })

    var sum = 0.0
    var numValid = 0

    for (val, flag) in parsed {
      if flag <= 0 {
        if invalidStart == nil {
          invalidStart = date
        }

        invalidPeriods += 1
      } else {
        if invalidPeriods > longestInvalid {
          longestInvalid = invalidPeriods
          longestInvalidStart = invalidStart
          longestInvalidEnd = date
        }

        sumFile += val
        sum += val
        numValid += 1
        readings += 1
        invalidPeriods = 0
        invalidStart = nil
      }
    }

    if numValid != 0 {
      rowStats.append((date, sum / Double(numValid), parsed.count - numValid))
    }
  }

  for stat in rowStats.lazy.reversed().prefix(5) {
    print("\(stat.0): Average: \(fmtDbl(stat.1)); Valid Readings: \(24 - stat.2); Invalid Readings: \(stat.2)")
  }

  print("""

        Sum File: \(fmtDbl(sumFile))
        Average: \(fmtDbl(sumFile / Double(readings)))
        Readings: \(readings)
        Longest Invalid: \(longestInvalid) (\(longestInvalidStart!) - \(longestInvalidEnd!))
        """)

  exit(0)
}

dispatchMain()


set max_invalid_run 0
set max_invalid_run_end ""
set tot_file 0
set num_file 0

set linefmt "Line: %11s  Reject: %2d  Accept: %2d  Line_tot: %10.3f  Line_avg: %10.3f"

set filename readings.txt
set fh [open $filename]
while {[gets $fh line] != -1} {
    set tot_line [set count [set num_line 0]]
    set fields [regexp -all -inline {\S+} $line]
    set date [lindex $fields 0]
    foreach {val flag} [lrange $fields 1 end] {
        incr count
        if {$flag > 0} {
            incr num_line
            incr num_file
            set tot_line [expr {$tot_line + $val}]
            set invalid_run_count 0
        } else {
            incr invalid_run_count
            if {$invalid_run_count > $max_invalid_run} {
                set max_invalid_run $invalid_run_count
                set max_invalid_run_end $date
            }
        }
    }
    set tot_file [expr {$tot_file + $tot_line}]
    puts [format $linefmt $date [expr {$count - $num_line}] $num_line $tot_line \
                 [expr {$num_line > 0 ? $tot_line / $num_line : 0}]]
}
close $fh

puts ""
puts "File(s)  = $filename"
puts "Total    = [format %.3f $tot_file]"
puts "Readings = $num_file"
puts "Average  = [format %.3f [expr {$tot_file / $num_file}]]"
puts ""
puts "Maximum run(s) of $max_invalid_run consecutive false readings ends at $max_invalid_run_end"


/* REXX ---------------------------------------------------------------
* 24.07.2014 Walter Pachl translated from Pascal
*            extend with decryption (following Pascal)
* 25.07.2014 WP changed i+=8 to I=I+8 (courtesy GS)
* 26.07-2014 WP removed extraneous semicolons
*--------------------------------------------------------------------*/
Numeric Digits 32
aa=0
bb=0
cc=0
mm.=0
randcnt=0
randrsl.=0
msg='a Top Secret secret'
key='this is my secret key'
iMode='iEncrypt'

Call iSeed key,1          /* 1) seed ISAAC with the key */
xctx=Vernam(msg)          /* 2) Vernam XOR encryption   */
mode='iEncrypt'
mctx=Vigenere(msg,mode)   /* 3) MOD encryption          */
Call iSeed key,1
xptx=Vernam(xctx)         /* a) XOR (Vernam)            */
mode='iDecrypt'
mptx=Vigenere(mctx,mode)  /* b) MOD (Vigenere)          */
                          /* program output             */
Say 'Message: 'msg
Say 'Key    : 'key
Say 'XOR    : 'c2x(xctx)
Say 'MOD    : 'c2x(mctx)
Say 'XOR dcr: 'xptx
Say 'MOD dcr: 'mptx
Exit

isaac: Procedure      Expose mm. aa bb cc randrsl. randcnt
  cc=add(cc,1)
  bb=add(bb,cc)
  Do i=0 To 255
    x=mm.i
    im4=i//4
    Select
      When im4=0 Then aa=xor(aa,shl(aa,13))
      When im4=1 Then aa=xor(aa,shr(aa, 6))
      When im4=2 Then aa=xor(aa,shl(aa, 2))
      When im4=3 Then aa=xor(aa,shr(aa,16))
      End
    z=(i+128)//256
    aa=add(mm.z,aa)
    z=shr(x,2)//256
    y=add(mm.z,aa,bb)
    mm.i=y
    z=shr(y,10)//256
    bb=add(mm.z,x)
    randrsl.i=bb
    End
  randcnt=0
  Return

mix: Procedure        Expose a b c d e f g h mm. aa bb cc randrsl. randcnt
  a=xor(a,shl(b,11)); d=add(d,a); b=add(b,c)
  b=xor(b,shr(c, 2)); e=add(e,b); c=add(c,d)
  c=xor(c,shl(d, 8)); f=add(f,c); d=add(d,e)
  d=xor(d,shr(e,16)); g=add(g,d); e=add(e,f)
  e=xor(e,shl(f,10)); h=add(h,e); f=add(f,g)
  f=xor(f,shr(g, 4)); a=add(a,f); g=add(g,h)
  g=xor(g,shl(h, 8)); b=add(b,g); h=add(h,a)
  h=xor(h,shr(a, 9)); c=add(c,h); a=add(a,b)
  Return

iRandInit: Procedure  Expose mm. randrsl. randcnt
  Parse Arg flag
  aa=0; bb=0; cc=0
  a= 2654435769 /* $9e3779b9;        // the golden ratio */

  b=a; c=a; d=a; e=a; f=a; g=a; h=a

  do i=0 TO 3
    Call mix
    End

  i=0
  do until i>255    /* fill in mm[] with messy stuff */
    IF flag THEN Do /* use all the information in the seed */
      Call setix
      a=add(a,randrsl.i);  b=add(b,randrsl.i1)
      c=add(c,randrsl.i2); d=add(d,randrsl.i3)
      e=add(e,randrsl.i4); f=add(f,randrsl.i5)
      g=add(g,randrsl.i6); h=add(h,randrsl.i7)
      End
    Call mix
    mm.i=a;  mm.i1=b; mm.i2=c; mm.i3=d
    mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h
    i=i+8
    End

  IF flag THEN Do /* do a second pass to make all of the seed affect all of mm  */
    i=0
    do until i>255    /* fill in mm[] with messy stuff */
      Call setix
      a=add(a,mm.i);  b=add(b,mm.i1); c=add(c,mm.i2); d=add(d,mm.i3)
      e=add(e,mm.i4); f=add(f,mm.i5); g=add(g,mm.i6); h=add(h,mm.i7)
      Call mix
      mm.i=a;  mm.i1=b; mm.i2=c; mm.i3=d
      mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h
      i=i+8
      End
    End
  Call isaac       /* fill in the first set of results        */
  randcnt=0;       /* prepare to use the first set of results */
  Return

iseed: Procedure      Expose aa bb cc randcnt randrsl. mm.
/*---------------------------------------------------------------------
* Seed ISAAC with a given string.
*  The string can be any size. The first 256 values will be used.
*--------------------------------------------------------------------*/
  Parse Arg seed,flag
  mm.=0
  m=Length(seed)-1
  Do i=0 TO 255
    IF i>m THEN   /* in case seed has less than 256 elements */
      randrsl.i=0
    ELSE
      randrsl.i=c2d(substr(seed,i+1,1))
    end
  Call iRandInit flag   /* initialize ISAAC with seed */
  Return

iRandom: Procedure    Expose aa bb cc randcnt randrsl. mm.
/* Get a random 32-bit value 0..MAXINT */
  iRandom=randrsl.randcnt
  randcnt=randcnt+1
  If randcnt>255 Then Do
    Call isaac
    randcnt=0
    End
  Return irandom

iRandA: Procedure     Expose aa bb cc randcnt randrsl. mm.
/* Get a random character in printable ASCII range */
  iRandA=iRandom()//95+32
  Return iRandA

xor: Procedure        Expose aa bb cc randcnt randrsl. mm.
  Parse Arg a,b
  ac=d2c(a,4)
  bc=d2c(b,4)
  res=c2d(bitxor(ac,bc))
  return res//4294967296

Vernam: Procedure     Expose aa bb cc randcnt randrsl. mm.
/* XOR encrypt on random stream. Output: string of hex chars */
  Parse Arg msg
  Vernam=''
  Do i=1 to length(msg)
    Vernam=Vernam||d2c(xor(iRandA(),c2d(substr(msg,i,1))))
    End
  Return Vernam

letternum: Procedure  Expose aa bb cc randcnt randrsl. mm.
/* Get position of the letter in chosen alphabet */
  Parse Arg letter,start
  letternum=c2d(letter)-c2d(start)
  Return letternum

Caesar: Procedure     Expose aa bb cc randcnt randrsl. mm.
/* Caesar-shift a character <shift> places: Generalized Vigenere */
  Parse Arg m,ch,shift,modulo,start
  IF m='iDecrypt' TheN shift=-shift
  n=letternum(ch,start)+shift
  n=n//modulo
  IF n<0 Then n=n+modulo
  Caesar=d2c(c2d(start)+n)
  Return Caesar

Vigenere: Procedure   Expose aa bb cc randcnt randrsl. mm.
/* Vigenere mod 95 encryption. Output: string of hex chars */
  Parse Arg msg,m
  Vigenere=''
  Do i=1 to length(msg)
    Vigenere=Vigenere||Caesar(m,substr(msg,i,1),iRandA(),95,' ')
    End
  Return Vigenere

shl: Procedure
  res=arg(1)*(2**arg(2))
  return res//4294967296

shr: Procedure
  res=arg(1)%(2**arg(2))
  return res//4294967296

setix:
  i1=i+1
  i2=i+2
  i3=i+3
  i4=i+4
  i5=i+5
  i6=i+6
  i7=i+7
  Return

add: Procedure
/* add argumemnts modulo 4294967296 */
  res=arg(1)+arg(2)
  If arg(3)<>'' Then
    res=res+arg(3)
  return res//4294967296


(function() {
	var orig= document.body.innerHTML
	document.body.innerHTML= '';
	setTimeout(function() {
		document.body.innerHTML= 'something';
		setTimeout(function() {
			document.body.innerHTML= orig;
		}, 1000);
	}, 1000);
})();


const ESC = "\u001B" # escape code

print("$ESC[?1049h$ESC[H")
print("\n\nNow using an alternate screen buffer. Returning after count of: ")
foreach(x -> (sleep(1); print("  $x")), 5:-1:0)
print("$ESC[?1049l\n\n\n")


// version 1.1.2

const val ESC = "\u001B"

fun main(args: Array<String>) {
    print("$ESC[?1049h$ESC[H")
    println("Alternate screen buffer")
    for(i in 5 downTo 1) {
        print("\rGoing back in $i second${if (i != 1) "s" else ""}...")
        Thread.sleep(1000)
    }
    print("$ESC[?1049l")
}


Module PreserveScreen {
      Bold 1
      Font "Arial"
      Paper=#225511
      SplitScreenRow=0
      Cls Paper, SplitScreenRow
      Print "Test"
      Gosub GetState
      Font "Tahoma"
      Bold 1 : Italic 1: Pen 15
      cls 0, 5
      For i=1 to 100 : Print i: Next i
      Move 6000,6000
      For i=1000 to 6000 step 1000 : Circle i : Next i
      WaitKey$=Key$
      Gosub RestoreState
      Print "End"
      End

      GetState:
            prevfont$=fontname$
            prevbold=bold
            previtalic=italic
            prevpen=pen
            posx=pos
            posy=row
            graphicx=pos.x
            graphicy=pos.y
            OldPaper=Paper
            OldSplit=SplitScreenRow
            Hold
      Return
      RestoreState:
            Paper=OldPaper
            SplitScreenRow=OldSplit
            Cls Paper, SplitScreenRow
            Release
            font prevfont$
            bold prevbold
            italic previtalic
            pen prevpen
            cursor posx, posy
            move graphicx, graphicy
      Return
}
PreserveScreen


Run["tput smcup"]    (* Save the display *)
Run["echo Hello"]
Pause[5]       (* Wait five seconds *)
Run["tput rmcup"]


import os

echo "\e[?1049h\e[H"
echo "Alternate buffer!"

for i in countdown(5, 1):
  echo "Going back in: ", i
  sleep 1000

echo "\e[?1049l"


print "\033[?1049h\033[H";
print "Alternate screen buffer\n";

for (my $i = 5; $i > 0; --$i) {
    print "going back in $i...\n";
    sleep(1);
}

print "\033[?1049l";


package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    lang := strings.ToUpper(os.Getenv("LANG"))
    if strings.Contains(lang, "UTF") {
        fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
    } else {
        fmt.Println("This terminal does not support unicode")
    }
}


import System.Environment
import Data.List
import Data.Char
import Data.Maybe

main = do
        x <- mapM lookupEnv ["LANG", "LC_ALL", "LC_CTYPE"]
        if any (isInfixOf "UTF". map toUpper) $ catMaybes x
         then putStrLn "UTF supported: \x25b3"
         else putStrLn "UTF not supported"


def has_unicode_support:
  def utf: if . == null then false else contains("UTF") or contains("utf") end;
  env.LC_ALL
  | if utf then true
    elif . != null and . != "" then false
    elif env.LC_CTYPE | utf then true
    else env.LANG | utf
    end ;

def task:
  if has_unicode_support then "\u25b3"
  else error("HW65001 This program requires a Unicode-compatible terminal")
  end ;

task


/* Terminal Control/Unicode, in Jsish */

var utf = false;
for (var envar of ['LC_ALL', 'LC_CTYPE', 'LANG']) {
    var val = Util.getenv(envar);
    if (val && (val.search(/utf/i) > 0)) {
        utf = true;
        break;
    }
}

puts((utf) ? '\u25b3' : 'Unicode support not detected');

/*
=!EXPECTSTART!=
△
=!EXPECTEND!=
*/


#import std
#import nat
#import flo

parsed_data = ^|A(~&,* ^|/%[email protected] ~&h==`1)*htK27K28pPCS (sep 9%cOi&)*FyS readings_dot_txt

daily_stats =

* ^|A(~&,@rFlS ^/length ^/plus:-0. ||0.! ~&i&& mean); mat` + <.
   ~&n,
   'accept: '--+ @ml printf/'%7.0f'+ float,
   'total: '--+ @mrl printf/'%10.1f',
   'average: '--+ @mrr printf/'%7.3f'>

long_run =

-+
   ~&i&& ^|TNC('maximum of '[email protected]+ %nP,' consecutive false readings ending on line '--),
   @nmrSPDSL -&~&,leql$^; ^/length ~&zn&[email protected]+ rlc both ~&rZ+-

main = ^T(daily_stats^lrNCT/~& @mSL 'summary   ':,long_run) parsed_data


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
			"\data.txt",1)

bad_readings_total = 0
good_readings_total = 0
data_gap = 0
start_date = ""
end_date = ""
tmp_datax_gap = 0
tmp_start_date = ""

Do Until objFile.AtEndOfStream
	bad_readings = 0
	good_readings = 0
	line_total = 0
	line = objFile.ReadLine
	token = Split(line,vbTab)
	n = 1
	Do While n <= UBound(token)
		If n + 1 <= UBound(token) Then
			If CInt(token(n+1)) < 1 Then
				bad_readings = bad_readings + 1
				bad_readings_total = bad_readings_total + 1
				'Account for bad readings.
				If tmp_start_date = "" Then
					tmp_start_date = token(0)
				End If
				tmp_data_gap = tmp_data_gap + 1
			Else
				good_readings = good_readings + 1
				line_total = line_total + CInt(token(n))
				good_readings_total = good_readings_total + 1
				'Sum up the bad readings.
				If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then
					start_date = tmp_start_date
					end_date = token(0)
					data_gap = tmp_data_gap
					tmp_start_date = ""
					tmp_data_gap = 0
				Else
					tmp_start_date = ""
					tmp_data_gap = 0
				End If
			End If
		End If
		n = n + 2
	Loop
	line_avg = line_total/good_readings
	WScript.StdOut.Write "Date: " & token(0) & vbTab &_
		"Bad Reads: " & bad_readings & vbTab &_
		"Good Reads: " & good_readings & vbTab &_
		"Line Total: " & FormatNumber(line_total,3) & vbTab &_
		"Line Avg: " & FormatNumber(line_avg,3)
	WScript.StdOut.WriteLine
Loop
WScript.StdOut.WriteLine
WScript.StdOut.Write "Maximum run of " & data_gap &_
	" consecutive bad readings from " & start_date & " to " &_
	end_date & "."
WScript.StdOut.WriteLine
objFile.Close
Set objFSO = Nothing


#50 = Buf_Num		// Current edit buffer (source data)
File_Open("output.txt")
#51 = Buf_Num		// Edit buffer for output file
Buf_Switch(#50)
#10 = 0			// total sum of file data
#11 = 0			// number of valid data items in file
#12 = 0			// Current run of consecutive flags<0 in lines of file
#13 = -1		// Max consecutive flags<0 in lines of file
Reg_Empty(15)		// ... and date tag(s) at line(s) where it occurs

While(!At_EOF) {
    #20 = 0		// sum of line data
    #21 = 0		// number of line data items with flag>0
    #22 = 0		// number of line data items with flag<0
    Reg_Copy_Block(14, Cur_Pos, Cur_Pos+10)	// date field

    // extract field info, skipping initial date field
    Repeat(ALL) {
	Search("|{|T,|N}", ADVANCE+ERRBREAK)	// next Tab or Newline
	if (Match_Item==2) { Break }		// end of line
	#30 = Num_Eval(ADVANCE) * 1000		// #30 = value
	Char					//  fixed point, 3 decimal digits
	#30 += Num_Eval(ADVANCE+SUPPRESS)
	#31 = Num_Eval(ADVANCE)			// #31 = flag
	if (#31 < 1) {				// not valid field?
	    #12++
	    #22++
	} else {				// valid field
	    // check run of data-absent fields
	    if(#13 == #12 && #12 > 0) {
	        Reg_Set(15, ", ", APPEND)
	        Reg_Set(15, @14, APPEND)
	    }
	    if(#13 < #12 && #12 > 0) {
	        #13 = #12
	        Reg_Set(15, @14)
	    }

	    // re-initialise run of nodata counter
	    #12 = 0
	    // gather values for averaging
	    #20 += #30
	    #21++
	}
    }

    // totals for the file so far
    #10 += #20
    #11 += #21

    Buf_Switch(#51)	// buffer for output data
    IT("Line: ") Reg_Ins(14)
    IT("  Reject:") Num_Ins(#22, COUNT, 3)
    IT("  Accept:") Num_Ins(#21, COUNT, 3)
    IT("  Line tot:") Num_Ins(#20, COUNT, 8) Char(-3) IC('.') EOL
    IT("  Line avg:") Num_Ins((#20+#21/2)/#21, COUNT, 7) Char(-3) IC('.') EOL IN
    Buf_Switch(#50)	// buffer for input data
}

Buf_Switch(#51)		// buffer for output data
IN
IT("Total:   ") Num_Ins(#10, FORCE+NOCR) Char(-3) IC('.') EOL IN
IT("Readings: ") Num_Ins(#11, FORCE)
IT("Average: ") Num_Ins((#10+#11/2)/#11, FORCE+NOCR) Char(-3) IC('.') EOL IN
IN
IT("Maximum run(s) of ") Num_Ins(#13, LEFT+NOCR)
IT(" consecutive false readings ends at line starting with date(s): ") Reg_Ins(15)
IN


require('Math::Random::ISAAC')

func xor_isaac(key, msg) {
  var rng = %O<Math::Random::ISAAC>.new(unpack('C*', key))

  msg.chars»ord()»                                          \
    -> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).flip \
    -> «%« '%02X' -> join
}

var msg = 'a Top Secret secret'
var key = 'this is my secret key'

var enc = xor_isaac(key, msg)
var dec = xor_isaac(key, pack('H*', enc))

say "Message: #{msg}"
say "Key    : #{key}"
say "XOR    : #{enc}"
say "XOR dcr: #{pack('H*', dec)}"


without js -- (save_text_image, sleep, display_text_image)
sequence s = save_text_image({1,1}, {25,80})
clear_screen()
puts(1,"\n\n *** hello ***\n")
sleep(5)
display_text_image({1,1}, s)
sleep(3)


#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(call 'tput "smcup")
(prinl "something")
(wait 3000)
(call 'tput "rmcup")

(bye)


#!/usr/bin/env python

import time

print "\033[?1049h\033[H"
print "Alternate buffer!"

for i in xrange(5, 0, -1):
    print "Going back in:", i
    time.sleep(1)

print "\033[?1049l"


#lang racket

(require racket/system)
(define (flash str)
  (system "tput smcup")
  (displayln str)
  (sleep 2)
  (system "tput rmcup")
  (void))

(flash "Hello world.")


print "\e[?1049h\e[H";
say "Alternate buffer!";

for 5,4...1 {
    print "\rGoing back in: $_";
    sleep 1;
}

print "\e[?1049l";


/*REXX program saves the screen contents and also the cursor location,  then clears the */
/*──── screen, writes a half screen of ~~~ lines, and then restores the original screen.*/

parse value  scrsize()   with  sd  sw  .         /*determine the size of terminal screen*/
parse value cursor(1,1)  with  curRow  curCol .  /*also, find the location of the cursor*/

          do original=1  for sd                  /*obtain the original screen contents. */
          @line.original=scrRead(original,1, sw) /*obtain a line of the terminal screen.*/
          end   /*original*/                     /* [↑]  obtains  SD  number of lines.  */
'CLS'                                            /*start with a clean slate on terminal.*/
          do sd % 2                              /*write a line of ~~~ for half of scr. */
          say '~~~'                              /*writes ~~~ starting at top of screen.*/
          end   /*sd % 2*/                       /* [↑]  this shows ~~~ will be overlaid*/
                                                 /*no need to clear the screen here.    */
          do restore=1  for sd                   /*restore original screen from  @line. */
          call scrWrite restore,1, @line.restore /*write to terminal the original lines.*/
          end   /*restore*/                      /* [↑]  writes (restores)  SD  lines.  */
                                                 /*stick a fork in it,  we're all done. */
call cursor  curRow, curCol                      /*restore the original cursor position.*/


c = '\u25b3'

if ismatch(r"UTF", get(ENV, "LANG", ""))
    println("This output device supports Unicode: ", c)
else
    println("This output device does not support Unicode.")
end


// version 1.1.2

fun main(args: Array<String>) {
    val supportsUnicode = "UTF" in System.getenv("LANG").toUpperCase()
    if (supportsUnicode)
        println("This terminal supports unicode and U+25b3 is : \u25b3")
    else
        println("This terminal does not support unicode")
}


local(env_vars = sys_environ -> join('###'))
if(#env_vars >> regexp(`(LANG|LC_ALL|LC_CTYPE).*?UTF.*?###`)) => {
	stdout('UTF supported \u25b3')
else
	stdout('This terminal does not support UTF')
}


Module CheckIt {
      If IsWine then Font "DejaVu Sans"
      Cls
      Report format$("\u25B3")
      Keyboard 0x25B3, format$("\u25B3")
      \\ report use kerning
      Report Key$+"T"+Key$
      Keyboard 0x25B3, format$("\u25B3")
      Print Key$;"T";Key$
}
Checkit


If[StringMatchQ[$CharacterEncoding, "UTF*"], Print[FromCharacterCode[30000]], Print["UTF-8 capable terminal required"]]
->田


:- module unicode_output.
:- interface.

:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.

:- import_module list.
:- import_module maybe.
:- import_module string.

main(!IO) :-
    list.map_foldl(io.get_environment_var, ["LANG", "LC_ALL", "LC_CTYPE"], EnvValues, !IO),
    ( if
        list.member(EnvValue, EnvValues),
        EnvValue = yes(Lang),
        string.sub_string_search(Lang, "UTF-8", _)
    then
        io.write_string("Unicode is supported on this terminal and U+25B3 is : \u25b3\n", !IO)
    else
        io.write_string("Unicode is not supported on this terminal.\n", !IO)
    ).


using System.Console;

module UnicodeOut
{
    Main() : void
    {
        if (OutputEncoding.ToString() == "System.Text.UTF8Encoding") Write("Δ")
        else Write("Console encoding may not support Unicode characters.");
    }
}


import os, strutils

if "utf" in getEnv("LANG").toLower:
  echo "Unicode is supported on this terminal and U+25B3 is: △"
else:
  echo "Unicode is not supported on this terminal."