program topologicalsortrosetta;

{*
Topological sorter to parse e.g. dependencies.
Written for FreePascal 2.4.x/2.5.1. Probably works in Delphi, but you'd have to
change some units.
*}
{$IFDEF FPC}
// FreePascal-specific setup
{$mode objfpc}
uses {$IFDEF UNIX}
  cwstring, {* widestring support for unix *} {$IFDEF UseCThreads}
  cthreads, {$ENDIF UseCThreads} {$ENDIF UNIX}
  Classes,
  SysUtils;
{$ENDIF}

type
  RNodeIndex = record
    NodeName: WideString; //Name of the node
    //Index: integer; //Index number used in DepGraph. For now, we can distill the index from the array index. If we want to use a TList or similar, we'd need an index property
    Order: integer;  //Order when sorted
  end;

  RDepGraph = record
    Node: integer;  //Refers to Index in NodeIndex
    DependsOn: integer; //The Node depends on this other Node.
  end;

  { TTopologicalSort }

  TTopologicalSort = class(TObject)
  private
    Nodes: array of RNodeIndex;
    DependencyGraph: array of RDepGraph;
    FCanBeSorted: boolean;
    function SearchNode(NodeName: WideString): integer;
    function SearchIndex(NodeID: integer): WideString;
    function DepFromNodeID(NodeID: integer): integer;
    function DepFromDepID(DepID: integer): integer;
    function DepFromNodeIDDepID(NodeID, DepID: integer): integer;
    procedure DelDependency(const Index: integer);
  public
    constructor Create;
    destructor Destroy; override;
    procedure SortOrder(var Output: TStringList);
    procedure AddNode(NodeName: WideString);
    procedure AddDependency(NodeName, DependsOn: WideString);
    procedure AddNodeDependencies(NodeAndDependencies: TStringList);
    //Each string has node, and the nodes it depends on. This allows insertion of an entire dependency graph at once
    //procedure DelNode(NodeName: Widestring);
    procedure DelDependency(NodeName, DependsOn: WideString);

    property CanBeSorted: boolean read FCanBeSorted;

  end;

const
  INVALID = -1;
  // index not found for index search functions, no sort order defined, or record invalid/deleted

  function TTopologicalSort.SearchNode(NodeName: WideString): integer;
  var
    Counter: integer;
  begin
    // Return -1 if node not found. If node found, return index in array
    Result := INVALID;
    for Counter := 0 to High(Nodes) do
    begin
      if Nodes[Counter].NodeName = NodeName then
      begin
        Result := Counter;
        break;
      end;
    end;
  end;

  function TTopologicalSort.SearchIndex(NodeID: integer): WideString;
    //Look up name for the index
  begin
    if (NodeID > 0) and (NodeID <= High(Nodes)) then
    begin
      Result := Nodes[NodeID].NodeName;
    end
    else
    begin
      Result := 'ERROR'; //something's fishy, this shouldn't happen
    end;
  end;

  function TTopologicalSort.DepFromNodeID(NodeID: integer): integer;
    // Look for Node index number in the dependency graph
    // and return the first node found. If nothing found, return -1
  var
    Counter: integer;
  begin
    Result := INVALID;
    for Counter := 0 to High(DependencyGraph) do
    begin
      if DependencyGraph[Counter].Node = NodeID then
      begin
        Result := Counter;
        break;
      end;
    end;
  end;

  function TTopologicalSort.DepFromDepID(DepID: integer): integer;
    // Look for dependency index number in the dependency graph
    // and return the index for the first one found. If nothing found, return -1
  var
    Counter: integer;
  begin
    Result := INVALID;
    for Counter := 0 to High(DependencyGraph) do
    begin
      if DependencyGraph[Counter].DependsOn = DepID then
      begin
        Result := Counter;
        break;
      end;
    end;
  end;

  function TTopologicalSort.DepFromNodeIDDepID(NodeID, DepID: integer): integer;
    // Shows index for the dependency from NodeID on DepID, or INVALID if not found
  var
    Counter: integer;
  begin
    Result := INVALID;
    for Counter := 0 to High(DependencyGraph) do
    begin
      if DependencyGraph[Counter].Node = NodeID then
        if DependencyGraph[Counter].DependsOn = DepID then
        begin
          Result := Counter;
          break;
        end;
    end;
  end;

  procedure TTopologicalSort.DelDependency(const Index: integer);
  // Removes dependency from array.
  // Is fastest when the dependency is near the top of the array
  // as we're copying the remaining elements.
  var
    Counter: integer;
    OriginalLength: integer;
  begin
    OriginalLength := Length(DependencyGraph);
    if Index = OriginalLength - 1 then
    begin
      SetLength(DependencyGraph, OriginalLength - 1);
    end;
    if Index < OriginalLength - 1 then
    begin
      for Counter := Index to OriginalLength - 2 do
      begin
        DependencyGraph[Counter] := DependencyGraph[Counter + 1];
      end;
      SetLength(DependencyGraph, OriginalLength - 1);
    end;
    if Index > OriginalLength - 1 then
    begin
      // This could happen when deleting on an empty array:
      raise Exception.Create('Tried to delete index ' + IntToStr(Index) +
        ' while the maximum index was ' + IntToStr(OriginalLength - 1));
    end;
  end;

  constructor TTopologicalSort.Create;
  begin
    inherited Create;
  end;

  destructor TTopologicalSort.Destroy;
  begin
    // Clear up data just to make sure:
    Finalize(DependencyGraph);
    Finalize(Nodes);
    inherited;
  end;

  procedure TTopologicalSort.SortOrder(var Output: TStringList);
  var
    Counter: integer;
    NodeCounter: integer;
    OutputSortOrder: integer;
    DidSomething: boolean; //used to detect cycles (circular references)
    Node: integer;
  begin
    OutputSortOrder := 0;
    DidSomething := True; // prime the loop below
    FCanBeSorted := True; //hope for the best.
    while (DidSomething = True) do
    begin
      // 1. Find all nodes (now) without dependencies, output them first and remove the dependencies:
      // 1.1 Nodes that are not present in the dependency graph at all:
      for Counter := 0 to High(Nodes) do
      begin
        if DepFromNodeID(Counter) = INVALID then
        begin
          if DepFromDepID(Counter) = INVALID then
          begin
            // Node doesn't occur in either side of the dependency graph, so it has sort order 0:
            DidSomething := True;
            if (Nodes[Counter].Order = INVALID) or
              (Nodes[Counter].Order > OutputSortOrder) then
            begin
              // Enter sort order if the node doesn't have a lower valid order already.
              Nodes[Counter].Order := OutputSortOrder;
            end;
          end; //Invalid Dep
        end; //Invalid Node
      end; //Count
      // Done with the first batch, so we can increase the sort order:
      OutputSortOrder := OutputSortOrder + 1;
      // 1.2 Nodes that are only present on the right hand side of the dep graph:
      DidSomething := False;
      // reverse order so we can delete dependencies without passing upper array
      for Counter := High(DependencyGraph) downto 0 do
      begin
        Node := DependencyGraph[Counter].DependsOn; //the depended node
        if (DepFromNodeID(Node) = INVALID) then
        begin
          DidSomething := True;
          //Delete dependency so we don't hit it again:
          DelDependency(Counter);
          if (Nodes[Node].Order = INVALID) or (Nodes[Node].Order > OutputSortOrder) then
          begin
            // Enter sort order if the node doesn't have a lower valid order already.
            Nodes[Node].Order := OutputSortOrder;
          end;
        end;
        OutputSortOrder := OutputSortOrder + 1; //next iteration
      end;
      // 2. Go back to 1 until we can't do more work, and do some bookkeeping:
      OutputSortOrder := OutputSortOrder + 1;
    end; //outer loop for 1 to 2
    OutputSortOrder := OutputSortOrder - 1; //fix unused last loop.

    // 2. If we have dependencies left, we have a cycle; exit.
    if (High(DependencyGraph) > 0) then
    begin
      FCanBeSorted := False; //indicate we have a cycle
      Output.Add('Cycle (circular dependency) detected, cannot sort further. Dependencies left:');
      for Counter := 0 to High(DependencyGraph) do
      begin
        Output.Add(SearchIndex(DependencyGraph[Counter].Node) +
          ' depends on: ' + SearchIndex(DependencyGraph[Counter].DependsOn));
      end;
    end
    else
    begin
      // No cycle:
      // Now parse results, if we have them
      for Counter := 0 to OutputSortOrder do
      begin
        for NodeCounter := 0 to High(Nodes) do
        begin
          if Nodes[NodeCounter].Order = Counter then
          begin
            Output.Add(Nodes[NodeCounter].NodeName);
          end;
        end; //output each result
      end; //order iteration
    end; //cycle detection
  end;

  procedure TTopologicalSort.AddNode(NodeName: WideString);
  var
    NodesNewLength: integer;
  begin
    // Adds node; make sure we don't add duplicate entries
    if SearchNode(NodeName) = INVALID then
    begin
      NodesNewLength := Length(Nodes) + 1;
      SetLength(Nodes, NodesNewLength);
      Nodes[NodesNewLength - 1].NodeName := NodeName; //Arrays are 0 based
      //Nodes[NodesNewLength -1].Index :=  //If we change the object to a tlist or something, we already have an index property
      Nodes[NodesNewLength - 1].Order := INVALID; //default value
    end;
  end;

  procedure TTopologicalSort.AddDependency(NodeName, DependsOn: WideString);
  begin
    // Make sure both nodes in the dependency exist as a node
    if SearchNode(NodeName) = INVALID then
    begin
      Self.AddNode(NodeName);
    end;
    if SearchNode(DependsOn) = INVALID then
    begin
      Self.AddNode(DependsOn);
    end;
    // Add the dependency, only if we don't depend on ourselves:
    if NodeName <> DependsOn then
    begin
      SetLength(DependencyGraph, Length(DependencyGraph) + 1);
      DependencyGraph[High(DependencyGraph)].Node := SearchNode(NodeName);
      DependencyGraph[High(DependencyGraph)].DependsOn := SearchNode(DependsOn);
    end;
  end;

  procedure TTopologicalSort.AddNodeDependencies(NodeAndDependencies: TStringList);
  // Takes a stringlist containing a list of strings. Each string contains node names
  // separated by spaces. The first node depends on the others. It is permissible to have
  // only one node name, which doesn't depend on anything.
  // This procedure will add the dependencies and the nodes in one go.
  var
    Deplist: TStringList;
    StringCounter: integer;
    NodeCounter: integer;
  begin
    if Assigned(NodeAndDependencies) then
    begin
      DepList := TStringList.Create;
      try
        for StringCounter := 0 to NodeAndDependencies.Count - 1 do
        begin
          // For each string in the argument: split into names, and process:
          DepList.Delimiter := ' '; //use space to separate the entries
          DepList.StrictDelimiter := False; //allows us to ignore double spaces in input.
          DepList.DelimitedText := NodeAndDependencies[StringCounter];
          for NodeCounter := 0 to DepList.Count - 1 do
          begin
            if NodeCounter = 0 then
            begin
              // Add the first node, which might be the only one.
              Self.AddNode(Deplist[0]);
            end;

            if NodeCounter > 0 then
            begin
              // Only add dependency from the second item onwards
              // The AddDependency code will automatically add Deplist[0] to the Nodes, if required
              Self.AddDependency(DepList[0], DepList[NodeCounter]);
            end;
          end;
        end;
      finally
        DepList.Free;
      end;
    end;
  end;

  procedure TTopologicalSort.DelDependency(NodeName, DependsOn: WideString);
  // Delete the record.
  var
    NodeID: integer;
    DependsID: integer;
    Dependency: integer;
  begin
    NodeID := Self.SearchNode(NodeName);
    DependsID := Self.SearchNode(DependsOn);
    if (NodeID <> INVALID) and (DependsID <> INVALID) then
    begin
      // Look up dependency and delete it.
      Dependency := Self.DepFromNodeIDDepID(NodeID, DependsID);
      if (Dependency <> INVALID) then
      begin
        Self.DelDependency(Dependency);
      end;
    end;
  end;

  // Main program:
var
  InputList: TStringList; //Lines of dependencies
  TopSort: TTopologicalSort; //Topological sort object
  OutputList: TStringList; //Sorted dependencies
  Counter: integer;
begin

  //Actual sort
  InputList := TStringList.Create;
  // Add rosetta code sample input separated by at least one space in the lines
  InputList.Add(
    'des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee');
  InputList.Add('dw01             ieee dw01 dware gtech');
  InputList.Add('dw02             ieee dw02 dware');
  InputList.Add('dw03             std synopsys dware dw03 dw02 dw01 ieee gtech');
  InputList.Add('dw04             dw04 ieee dw01 dware gtech');
  InputList.Add('dw05             dw05 ieee dware');
  InputList.Add('dw06             dw06 ieee dware');
  InputList.Add('dw07             ieee dware');
  InputList.Add('dware            ieee dware');
  InputList.Add('gtech            ieee gtech');
  InputList.Add('ramlib           std ieee');
  InputList.Add('std_cell_lib     ieee std_cell_lib');
  InputList.Add('synopsys');
  TopSort := TTopologicalSort.Create;
  OutputList := TStringList.Create;
  try
    TopSort.AddNodeDependencies(InputList); //read in nodes
    TopSort.SortOrder(OutputList); //perform the sort
    for Counter := 0 to OutputList.Count - 1 do
    begin
      writeln(OutputList[Counter]);
    end;
  except
    on E: Exception do
    begin
      Writeln(stderr, 'Error: ', DateTimeToStr(Now),
        ': Error sorting. Technical details: ',
        E.ClassName, '/', E.Message);
    end;
  end; //try
  OutputList.Free;
  TopSort.Free;
  InputList.Free;
end.


F do_work(x)
   V n = x
   L(i) 10000000
      n += i
   R n

F time_func(f)
   V start = time:perf_counter()
   f()
   R time:perf_counter() - start

print(time_func(() -> do_work(100)))


USING: accessors combinators deques dlists fry io kernel
math.parser ;
IN: rosetta.tree-traversal

TUPLE: node data left right ;

CONSTANT: example-tree
    T{ node f 1
        T{ node f 2
            T{ node f 4
                T{ node f 7 f f }
                f
            }
            T{ node f 5 f f }
        }
        T{ node f 3
            T{ node f 6
                T{ node f 8 f f }
                T{ node f 9 f f }
            }
            f
        }
    }

: preorder ( node quot: ( data -- ) -- )
    [ [ data>> ] dip call ]
    [ [ left>> ] dip over [ preorder ] [ 2drop ] if ]
    [ [ right>> ] dip over [ preorder ] [ 2drop ] if ]
    2tri ; inline recursive

: inorder ( node quot: ( data -- ) -- )
    [ [ left>> ] dip over [ inorder ] [ 2drop ] if ]
    [ [ data>> ] dip call ]
    [ [ right>> ] dip over [ inorder ] [ 2drop ] if ]
    2tri ; inline recursive

: postorder ( node quot: ( data -- ) -- )
    [ [ left>> ] dip over [ postorder ] [ 2drop ] if ]
    [ [ right>> ] dip over [ postorder ] [ 2drop ] if ]
    [ [ data>> ] dip call ]
    2tri ; inline recursive

: (levelorder) ( dlist quot: ( data -- ) -- )
    over deque-empty? [ 2drop ] [
        [ dup pop-front ] dip {
            [ [ data>> ] dip call drop ]
            [ drop left>> [ swap push-back ] [ drop ] if* ]
            [ drop right>> [ swap push-back ] [ drop ] if* ]
            [ nip (levelorder) ]
        } 3cleave
    ] if ; inline recursive

: levelorder ( node quot: ( data -- ) -- )
    [ 1dlist ] dip (levelorder) ; inline

: levelorder2 ( node quot: ( data -- ) -- )
    [ 1dlist ] dip
    [ dup deque-empty? not ] swap '[
        dup pop-front
        [ data>> @ ]
        [ left>> [ over push-back ] when* ]
        [ right>> [ over push-back ] when* ] tri
    ] while drop ; inline

: main ( -- )
    example-tree [ number>string write " " write ] {
        [ "preorder:    " write preorder    nl ]
        [ "inorder:     " write inorder     nl ]
        [ "postorder:   " write postorder   nl ]
        [ "levelorder:  " write levelorder  nl ]
        [ "levelorder2: " write levelorder2 nl ]
    } 2cleave ;


let dep_libs = [
  ("des_system_lib", ["std"; "synopsys"; "std_cell_lib"; "des_system_lib"; "dw02"; "dw01"; "ramlib"; "ieee"]);
  ("dw01",           (*"dw04"::*)["ieee"; "dw01"; "dware"; "gtech"]);
  ("dw02",           ["ieee"; "dw02"; "dware"]);
  ("dw03",           ["std"; "synopsys"; "dware"; "dw03"; "dw02"; "dw01"; "ieee"; "gtech"]);
  ("dw04",           ["dw04"; "ieee"; "dw01"; "dware"; "gtech"]);
  ("dw05",           ["dw05"; "ieee"; "dware"]);
  ("dw06",           ["dw06"; "ieee"; "dware"]);
  ("dw07",           ["ieee"; "dware"]);
  ("dware",          ["ieee"; "dware"]);
  ("gtech",          ["ieee"; "gtech"]);
  ("ramlib",         ["std"; "ieee"]);
  ("std_cell_lib",   ["ieee"; "std_cell_lib"]);
  ("synopsys",       []);
]

let dep_libs =
  let f (lib, deps) =  (* remove self dependency *)
    (lib,
     List.filter (fun d -> d <> lib) deps) in
  List.map f dep_libs

let rev_unique =
  List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []

let libs =  (* list items, each being unique *)
  rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))

let get_deps lib =
  try (List.assoc lib dep_libs)
  with Not_found -> []

let res =
  let rec aux acc later todo progress =
  match todo, later with
  | [], [] -> (List.rev acc)
  | [], _ ->
      if progress
      then aux acc [] later false
      else invalid_arg "un-orderable data"
  | x::xs, _ ->
      let deps = get_deps x in
      let ok = List.for_all (fun dep -> List.mem dep acc) deps in
      if ok
      then aux (x::acc) later xs true
      else aux acc (x::later) xs progress
  in
  let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
  aux starts [] todo false

let () =
  print_string "result: \n ";
  print_endline (String.concat ", " res);
;;


with javascript_semantics
include mpfr.e

function ts(string ns, ps)
    mpz n = mpz_init(ns),
        p = mpz_init(ps),
        t = mpz_init(),
        r = mpz_init(),
        pm1 = mpz_init(),
        pm2 = mpz_init()
    mpz_sub_ui(pm1,p,1)                 -- pm1 = p-1
    mpz_fdiv_q_2exp(pm2,pm1,1)          -- pm2 = pm1/2
    mpz_powm(t,n,pm2,p)                 -- t = mod(n^pm2,p)
    if mpz_cmp_si(t,1)!=0 then
        return "No solution exists"
    end if
    mpz q = mpz_init_set(pm1)
    integer ss = 0
    while mpz_even(q) do
        ss += 1
        mpz_fdiv_q_2exp(q,q,1)          -- q/=2
    end while
    if ss=1 then
        mpz_add_ui(t,p,1)
        mpz_fdiv_q_2exp(t,t,2)
        mpz_powm(r,n,t,p)               -- r = mod(n^((p+1)/4),p)
    else
        mpz z = mpz_init(2)
        while true do
            mpz_powm(t,z,pm2,p)         -- t = mod(z^pm2,p)
            if mpz_cmp(t,pm1)=0 then exit end if
            mpz_add_ui(z,z,1)           -- z+= 1
        end while
        mpz {b,c,zz} = mpz_inits(3)
        mpz_powm(c,z,q,p)               -- c = mod(z^q,p)
        mpz_add_ui(t,q,1)
        mpz_fdiv_q_2exp(t,t,1)
        mpz_powm(r,n,t,p)               -- r = mod(n^((q+1)/2),p)
        mpz_powm(t,n,q,p)               -- t = mod(n^q,p)
        integer m = ss
        while mpz_cmp_si(t,1) do        -- t!=1
            integer i = 0
            mpz_set(zz,t)
            while mpz_cmp_si(zz,1)!=0 and i<m-1 do
                mpz_powm_ui(zz,zz,2,p)  -- zz = mod(zz^2,p)
                i += 1
            end while
            mpz_set(b,c)
            integer e = m-i-1
            while e>0 do
                mpz_powm_ui(b,b,2,p)    -- b = mod(b^2,p)
                e -= 1
            end while
            mpz_mul(r,r,b)
            mpz_mod(r,r,p)              -- r = mod(r*b,p)
            mpz_powm_ui(c,b,2,p)        -- c = mod(b^2,p)
            mpz_mul(t,t,c)
            mpz_mod(t,t,p)              -- t = mod(t*c,p)
            m = i
        end while
    end if
    mpz_sub(p,p,r)
    return mpz_get_str(r)&" and "&mpz_get_str(p)
end function

constant tests = {{"10","13"},
                  {"56","101"},
                  {"1030","10009"},
                  {"1032","10009"},
                  {"44402","100049"},
                  {"665820697","1000000009"},
                  {"881398088036","1000000000039"},
                  {"41660815127637347468140745042827704103445750172002",
                   sprintf("1%s577",repeat('0',47))}} -- 10^50+577

for i=1 to length(tests) do
    string {p1,p2} = tests[i]
    printf(1,"For n = %s and p = %s, %s\n",{p1,p2,ts(p1,p2)})
end for


TC	EQU	8 ; number of counter registers
TSTART	EQU	08h ; first register of timer counter
TEND	EQU	TSTART + TC - 1 ; end register of timer counter
; Note: The multi-byte value is stored in Big-endian

; Some timer reloads
_6H	EQU	085h ; 6MHz
_6L	EQU	0edh
_12H	EQU	00bh ; 12MHz
_12L	EQU	0dbh
_110592H	EQU	01eh ; 11.0592MHz
_110592L	EQU	0ffh

; How to calculate timer reload (e.g. for 11.0592MHz):
; Note: 1 machine cycle takes 12 oscillator periods
; 11.0592MHz / 12 * 0.0625 seconds = 57,600 cycles = e100h
; ffffh - e100h = NOT e100h = 1effh

; assuming a 11.0592MHz crystal
TIMERH	EQU	_110592H
TIMERL	EQU	_110592L

;; some timer macros (using timer0)
start_timer macro
	setb tr0
endm
stop_timer macro
	clr tr0
endm
reset_timer macro
	mov tl0, #TIMERL
	mov th0, #TIMERH
endm

increment_counter macro ;; increment counter (multi-byte increment)
	push psw
	push acc
	push 0 ; r0
	mov r0, #TEND+1
	setb c
inc_reg:
	dec r0
	clr a
	addc a, @r0
	mov @r0, a
	jnc inc_reg_	; end prematurally if the higher bytes are unchanged
	cjne r0, #TSTART, inc_reg
inc_reg_:
	; if the carry is set here then the multi byte value has overflowed
	pop 0
	pop acc
	pop psw
endm

ORG RESET
	jmp init
ORG TIMER0
	jmp timer_0

timer_0: ; interrupt every 6.25ms
	stop_timer		; we only want to time the function
	reset_timer
	increment_counter
	start_timer
	reti

init:
	mov sp, #TEND
	setb ea			; enable interrupts
	setb et0		; enable timer0 interrupt
	mov tmod, #01h		; timer0 16-bit mode
	reset_timer

	; reset timer counter registers
	clr a
	mov r0, #TSTART
clear:
	mov @r0, a
	inc r0
	cjne r0, #TEND, clear

	start_timer
	call function		; the function to time
	stop_timer

	; at this point the registers from TSTART
	; through TEND indicate the current time
	; multiplying the 8/16/24/etc length value by 0.0625 (2^-4) gives
	; the elapsed number of seconds
	; e.g. if the three registers were 02a0f2h then the elapsed time is:
	; 02a0f2h = 172,274 and 172,274 * 0.0625 = 10,767.125 seconds
	;
	; Or alternatively:
	; (high byte) 02h = 2 and 2 * 2^(16-4) = 8192
	; (mid byte) a0h = 160 and 160 * 2^(8-4) = 2560
	; (low byte) f2h = 242 and 242 * 2^(0-4) = 15.125
	; 8192 + 2560 + 15.125 = 10,767.125 seconds

	jmp $

function:
	; do whatever here
	ret

END


class Tree
{
  readonly Int label
  readonly Tree? left
  readonly Tree? right

  new make (Int label, Tree? left := null, Tree? right := null)
  {
    this.label = label
    this.left = left
    this.right = right
  }

  Void preorder(|Int->Void| func)
  {
    func(label)
    left?.preorder(func) // ?. will not call method if 'left' is null
    right?.preorder(func)
  }

  Void postorder(|Int->Void| func)
  {
    left?.postorder(func)
    right?.postorder(func)
    func(label)
  }

  Void inorder(|Int->Void| func)
  {
    left?.inorder(func)
    func(label)
    right?.inorder(func)
  }

  Void levelorder(|Int->Void| func)
  {
    Tree[] nodes := [this]
    while (nodes.size > 0)
    {
      Tree cur := nodes.removeAt(0)
      func(cur.label)
      if (cur.left != null) nodes.add (cur.left)
      if (cur.right != null) nodes.add (cur.right)
    }
  }
}

class Main
{
  public static Void main ()
  {
    tree := Tree(1,
              Tree(2, Tree(4, Tree(7)), Tree(5)),
              Tree(3, Tree(6, Tree(8), Tree(9))))
    List result := [,]
    collect := |Int a -> Void| { result.add(a) }
    tree.preorder(collect)
    echo ("preorder:    " + result.join(" "))
    result = [,]
    tree.inorder(collect)
    echo ("inorder:     " + result.join(" "))
    result = [,]
    tree.postorder(collect)
    echo ("postorder:   " + result.join(" "))
    result = [,]
    tree.levelorder(collect)
    echo ("levelorder:  " + result.join(" "))
  }
}


'TOPOLOGICAL SORT

uses parseutil 'getword() lenw
uses console

string dat="
LIBRARY          LIBRARY DEPENDENCIES
=======          ====================
des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01             ieee dw01 dware gtech
dw02             ieee dw02 dware
dw03             std synopsys dware dw03 dw02 dw01 ieee gtech
dw04             dw04 ieee dw01 dware gtech
dw05             dw05 ieee dware
dw06             dw06 ieee dware
dw07             ieee dware
dware            ieee dware
gtech            ieee gtech
ramlib           std ieee
std_cell_lib     ieee std_cell_lib
synopsys
"
gosub Dims
gosub CaptureData
gosub GetSystemLibs
gosub RemoveSelfReference
gosub OrderByDependency
gosub DisplayResults
end

/*RESULTS:
  libraries in dependency order
  -----------------------------
  std
  ieee
  dware
  gtech
  ramlib
  std_cell_lib
  synopsys
  dw01
  dw02
  des_system_lib
  dw03
  dw04
  dw05
  dw06
  dw07
<<

  remainder:
  ----------
  <<
*/

Dims:
=====
'VARIABLES
int p           'width of first column
int h           'length of each line
int i           'iterator / counter
int j           'main iterator
int b           'table char offset
int e           'end of each line
int bd          'each offset of dependencises line
int le          'length of each lib name
int lend        'size of table
int k           'character indexer
int m           'iterator
int n           'iterator
int cw          'presence flag
int lw          'length of keyword
int a           'iinstr result
int dc          'new lib list indexer / counter
string wr       'keyword
string wn       'keyword
'--arrays--
string datl[64] 'list of lib names
string datd[64] 'lists of lib dependencies
string datn[64] 'new list in dependency ordert
ret

CaptureData:
============
dat=lcase dat
'GET HEADING POSITION
p=instr dat,"library depend"
p-=3 'crlf -1
'REMOVE HEADING
h=instr 3,dat,cr
h+=2
h=instr h,dat,cr 'to remove underlines
'print h cr
h+=2
dat=mid dat,h
'print dat "<" cr
b=1
'PREPARE DATA
lend=len dat
do
  i++
  datl[i]=rtrim(mid(dat,b,p))
  le=len datl[i]
  e=instr b+le,dat,cr
  bd=b+p
  datd[i]=" "+mid(dat,bd,e-bd)+" "
  'print datl[i] "," datd[i] cr
  b=e+2
  if b>lend-2
    exit do
  endif
loop
ret

GetSystemLibs:
==============
'SCAN DEPENDENCIES
'GET SYSTEM LIBS NOT LISTED
for j=1 to i
  k=1
  do
    wr=getword datd[j],k
    if not wr
      exit do
    endif
    cw=0
    for m=1 to i
      if wr=datl[m] 'on lib list
        cw=m
      endif
    next
    if cw=0 'lib not on library list
      'add wr to new lib list
      dc++ : datn[dc]=wr
      'remove lib names from dependency lists
      gosub BlankOutNames
    endif
  loop
next 'j group of dependencies
ret

RemoveSelfReference:
====================
'REMOVE SELF REFERENCE + NO DEPENDENCIES
for j=1 to i
  wr=" "+datl[j]+" "
  lw=len(wr)
  a=instr(datd[j],wr)
  if a
    mid(datd[j],a,space(lw)) 'blank out self
  endif
  gosub RemoveLibFromLists
next
ret
'
OrderByDependency:
==================
'
for j=1 to i
  if datl[j]
    gosub RemoveLibFromLists
    if cw then j=0 'repeat cycle
  endif
next
ret
'
DisplayResults:
===============
print cr cr
print "libraries in dependency order" cr
print "-----------------------------" cr
for j=1 to dc
  print datn[j] cr
next
print "<<" cr cr
print "remainder:" cr
print "----------" cr
for j=1 to i
  if datl[j]
    print datl[j] " , " datd[j] cr
  endif
next
print "<<" cr

pause
end

RemoveLibFromLists:
===================
cw=0
k=1 : wr=getword datd[j],k
if lenw=0
  dc++ : datn[dc]=datl[j] 'add to new lib list
  datl[j]="" : datd[j]="" 'eliminate frecord rom further checks
  gosub BlankOutNames     'eliminate all lib references from table
  cw=1                    'flag alteration
endif
ret

BlankOutNames:
==============
wn=" "+datn[dc]+" " 'add word boundaries
lw=len wn
for n=1 to i
  if datd[n]
    a=instr(datd[n],wn)
    if a
      mid datd[n],a,space(lw) 'blank out
      endif
  endif
next
ret


declare
  Deps = unit(
            des_system_lib: [std synopsys std_cell_lib des_system_lib
                             dw02 dw01 ramlib ieee]
            dw01: [ieee dw01 dware gtech]
            dw02: [ieee dw02 dware]
            dw03: [std synopsys dware dw03 dw02 dw01 ieee gtech]
            dw04: [dw04 ieee dw01 dware gtech]
            dw05: [dw05 ieee dware]
            dw06: [dw06 ieee dware]
            dw07: [ieee dware]
            dware: [ieee dware]
            gtech: [ieee gtech]
            ramlib: [std ieee]
            std_cell_lib: [ieee std_cell_lib]
            synopsys:nil
            )

  %% Describe possible solutions
  proc {TopologicalOrder Solution}
     FullDeps = {Complete Deps}
  in
     %% The solution is a record that maps library names
     %% to finite domain variables.
     %% The smaller the value, the earlier it must be compiled
     Solution = {FD.record sol {Arity FullDeps} 1#{Width FullDeps}}
     %% for every lib on the left side
     {Record.forAllInd FullDeps
      proc {$ LibName Dependants}
         %% ... and every dependant on the right side
         for Dependant in Dependants do
            %% propagate compilation order
            if Dependant \= LibName then
               Solution.LibName >: Solution.Dependant
            end
         end
      end
     }
     %% enumerate solutions
     {FD.distribute naive Solution}
  end

  %% adds empty list of dependencies for libs that only occur on the right side
  fun {Complete Dep}
     AllLibs = {Nub {Record.foldL Dep Append nil}}
  in
     {Adjoin
      {List.toRecord unit {Map AllLibs fun {$ L} L#nil end}}
      Dep}
  end

  %% removes duplicates
  fun {Nub Xs}
     D = {Dictionary.new}
  in
     for X in Xs do D.X := unit end
     {Dictionary.keys D}
  end

  %% print grouped by parallelizable jobs
  proc {PrintSolution Sol}
     for I in 1..{Record.foldL Sol Value.max 1} do
        for Lib in {Arity {Record.filter Sol fun {$ X} X == I end}} do
           {System.printInfo Lib#" "}
        end
        {System.printInfo "\n"}
     end
  end

  fun {GetOrderedLibs Sol}
     {Map
      {Sort {Record.toListInd Sol} CompareSecond}
      SelectFirst}
  end
  fun {CompareSecond A B} A.2 < B.2 end
  fun {SelectFirst X} X.1 end
in
  case {SearchOne TopologicalOrder}
  of nil then {System.showInfo "Un-orderable."}
  [] [Sol] then
     {System.showInfo "A possible topological ordering: "}
     {ForAll {GetOrderedLibs Sol} System.showInfo}

     {System.showInfo "\nBONUS - grouped by parallelizable compile jobs:"}
     {PrintSolution Sol}
  end


BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014

PROC Count(CARD max)
  CARD i

  FOR i=1 TO max DO OD
RETURN

CARD FUNC GetFrame()
  CARD res
  BYTE lsb=res,msb=res+1

  lsb=RTCLOK2
  msb=RTCLOK1
RETURN (res)

CARD FUNC FramesToMs(CARD frames)
  CARD res

  IF PALNTSC=15 THEN
    res=frames*60
  ELSE
    res=frames*50
  FI
RETURN (res)

PROC Main()
  CARD ARRAY c=[1000 2000 5000 10000 20000 50000]
  CARD beg,end,diff,diffMs
  BYTE i

  FOR i=0 TO 5
  DO
    PrintF("Count to %U takes ",c(i))
    beg=GetFrame()
    Count(c(i))
    end=GetFrame()
    diff=end-beg
    diffMs=FramesToMs(diff)
    PrintF("%U ms%E",diffMs)
  OD
RETURN


with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;

procedure Query_Performance is
   type Proc_Access is access procedure(X : in out Integer);
   function Time_It(Action : Proc_Access; Arg : Integer) return Duration is
      Start_Time : Time := Clock;
      Finis_Time : Time;
      Func_Arg : Integer := Arg;
   begin
      Action(Func_Arg);
      Finis_Time := Clock;
      return Finis_Time - Start_Time;
   end Time_It;
   procedure Identity(X : in out Integer) is
   begin
      X := X;
   end Identity;
   procedure Sum (Num : in out Integer) is
   begin
      for I in 1..1000 loop
         Num := Num + I;
      end loop;
   end Sum;
   Id_Access : Proc_Access := Identity'access;
   Sum_Access : Proc_Access := Sum'access;

begin
   Put_Line("Identity(4) takes" & Duration'Image(Time_It(Id_Access, 4)) & " seconds.");
   Put_Line("Sum(4) takes:" & Duration'Image(Time_It(Sum_Access, 4)) & " seconds.");
end Query_Performance;


integer
identity(integer x)
{
    x;
}

integer
sum(integer c)
{
    integer s;

    s = 0;
    while (c) {
	s += c;
	c -= 1;
    }

    s;
}

real
time_f(integer (*fp)(integer), integer fa)
{
    date f, s;
    time t;

    s.now;

    fp(fa);

    f.now;

    t.ddiff(f, s);

    t.microsecond / 1000000r;
}

integer
main(void)
{
    o_real(6, time_f(identity, 1));
    o_text(" seconds\n");
    o_real(6, time_f(sum, 1000000));
    o_text(" seconds\n");

    0;
}


\ binary tree (dictionary)
: node ( l r data -- node ) here >r , , , r> ;
: leaf ( data -- node ) 0 0 rot node ;

: >data  ( node -- ) @ ;
: >right ( node -- ) cell+ @ ;
: >left  ( node -- ) cell+ cell+ @ ;

: preorder ( xt tree -- )
  dup 0= if 2drop exit then
  2dup >data swap execute
  2dup >left recurse
       >right recurse ;

: inorder ( xt tree -- )
  dup 0= if 2drop exit then
  2dup >left recurse
  2dup >data swap execute
       >right recurse ;

: postorder ( xt tree -- )
  dup 0= if 2drop exit then
  2dup >left recurse
  2dup >right recurse
       >data swap execute ;

: max-depth ( tree -- n )
  dup 0= if exit then
  dup  >left recurse
  swap >right recurse max 1+ ;

defer depthaction
: depthorder ( depth tree -- )
  dup 0= if 2drop exit then
  over 0=
  if   >data depthaction drop
  else over 1- over >left  recurse
       swap 1- swap >right recurse
  then ;

: levelorder ( xt tree -- )
  swap is depthaction
  dup max-depth 0 ?do
    i over depthorder
  loop drop ;

7 leaf 0      4 node
              5 leaf 2 node
8 leaf 9 leaf 6 node
              0      3 node 1 node value tree

cr ' . tree preorder    \ 1 2 4 7 5 3 6 8 9
cr ' . tree inorder     \ 7 4 2 5 1 8 6 9 3
cr ' . tree postorder   \ 7 4 5 2 8 9 6 3 1
cr tree max-depth .     \ 4
cr ' . tree levelorder  \ 1 2 3 4 5 6 7 8 9


sub print_topo_sort {
    my %deps = @_;

    my %ba;
    while ( my ( $before, $afters_aref ) = each %deps ) {
        for my $after ( @{ $afters_aref } ) {
            $ba{$before}{$after} = 1 if $before ne $after;
            $ba{$after} ||= {};
        }
    }

    while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
        print "@afters\n";
        delete @ba{@afters};
        delete @{$_}{@afters} for values %ba;
    }

    print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}

my %deps = (
    des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
                                                        dw01 ramlib ieee )],
    dw01           => [qw( ieee dw01 dware gtech                         )],
    dw02           => [qw( ieee dw02 dware                               )],
    dw03           => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech  )],
    dw04           => [qw( dw04 ieee dw01 dware gtech                    )],
    dw05           => [qw( dw05 ieee dware                               )],
    dw06           => [qw( dw06 ieee dware                               )],
    dw07           => [qw( ieee dware                                    )],
    dware          => [qw( ieee dware                                    )],
    gtech          => [qw( ieee gtech                                    )],
    ramlib         => [qw( std ieee                                      )],
    std_cell_lib   => [qw( ieee std_cell_lib                             )],
    synopsys       => [qw(                                               )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04'; # Add unresolvable dependency
print_topo_sort(%deps);


#lang racket

(require math/number-theory)

(define (Legendre a p)
  (modexpt a (quotient (sub1 p) 2)))

(define (Tonelli n p (err (λ (n p) (error "not a square (mod p)" (list n p)))))
  (with-modulus p
    (unless (= 1 (Legendre n p)) (err n p))

    (define-values (q s)
      (let even?-q-loop ((q (sub1 p)) (s 0))
        (if (even? q)
            (even?-q-loop (quotient q 2) (add1 s))
            (values q s))))

    (cond
      [(= s 1)
       (modexpt n (/ (add1 p) 4))]
      [else
       (define z (for/first ((z (in-range 2 p)) #:when (= (sub1 p) (Legendre z p))) z))
       (let loop ((c (modexpt z q))
                  (r (modexpt n (quotient (add1 q) 2)))
                  (t (modexpt n q))
                  (m s))
         (cond
           [(mod= 1 t)
            r]
           [else
            (define-values (t2 m′) (for/fold ((t2 (modsqr t)) (i 1))
                                             ((j (in-range 1 m)) #:final (mod= t2 1))
                                     (values (modsqr t2) j)))
            (define b (modexpt c (expt 2 (- m m′ 1))))
            (define c′ (modsqr b))
            (loop c′ (mod* r b) (mod* t c′) m′)]))])))

(module+ test
  (require rackunit)

  (define ttest
    `((10 13)
      (56 101)
      (1030 10009)
      (44402 100049)
      (665820697 1000000009)
      (881398088036  1000000000039)
      (41660815127637347468140745042827704103445750172002
       ,(+ #e1e50 577))))

  (define (task ttest)
    (for ((test ttest))
      (define n (first test))
      (define p (second test))
      (define r (Tonelli n p))
      (printf "n = ~a p = ~a~%  roots : ~a ~a~%" n p r (- p r))))

  (task ttest)

  (check-exn exn:fail? (λ () (Tonelli 1032 1009))))


/* ARM assembly Raspberry PI  */
/*  program fcttime.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall

.equ N1, 1000000   @ loop number
.equ NBMEASURE, 10 @ measure number

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessError:       .asciz "Error detected !!!!. \n"
szMessSep:         .asciz "****************************\n"
szMessTemps:       .ascii "Function time : "
sSecondes:         .fill 10,1,' '
                   .ascii " s "
sMicroS:           .fill 10,1,' '
                   .asciz " micros\n"

szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4
dwDebut:           .skip 8
dwFin:             .skip 8
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                     @ entry of program
    adr r0,mult                           @ function address to measure
    mov r1,#1                             @ parameter 1 function
    mov r2,#2                             @ parameter 2 function
    bl timeMesure
    cmp r0,#0
    blt 99f
    adr r0,sum                            @ function address to measure
    mov r1,#1
    mov r2,#2
    bl timeMesure
    cmp r0,#0
    blt 99f
    b 100f
99:
    @ error
    ldr r0,iAdrszMessError
    bl affichageMess
100:                                       @ standard end of the program
    mov r0, #0                             @ return code
    mov r7, #EXIT                          @ request to exit program
    svc #0                                 @ perform the system call

iAdrszMessError:          .int szMessError
iAdrszCarriageReturn:     .int szCarriageReturn
/**************************************************************/
/*   examble function sum                                     */
/**************************************************************/
/* r0 contains op 1     */
/* r1 contains op 2     */
sum:
    push {lr}                  @ save registres
    add r0,r1
100:
    pop {lr}                   @ restaur registers
    bx lr                      @ function return

/**************************************************************/
/*   exemple execution multiplication                         */
/**************************************************************/
/* r0 contains op 1     */
/* r1 contains op 2     */
mult:
    push {lr}                  @ save registres
    mul r0,r1,r0
100:
    pop {lr}                   @ restaur registers
    bx lr                      @ function return

/**************************************************************/
/*   Procedure for measuring the execution time of a routine  */
/**************************************************************/
/* r0 contains the function address     */
timeMesure:
    push {r1-r8,lr}                      @ save registres
    mov r4,r0                            @ save function address
    mov r5,r1                            @ save param 1
    mov r6,r2                            @ save param 2
    mov r8,#0
1:
    ldr r0,iAdrdwDebut                   @ start time area
    mov r1,#0
    mov r7, #0x4e                        @ call system gettimeofday
    svc #0
    cmp r0,#0                            @ error ?
    blt 100f                             @ return error
    ldr r7,iMax                          @ run number
    mov r0,r5                            @ param function 1
    mov r1,r6                            @ param function 2
2:                                       @ loop
    blx r4                               @ call of the function to be measured
    subs r7,#1                           @ decrement run
    bge 2b                               @ loop if not zero
    @
    ldr r0,iAdrdwFin                     @ end time area
    mov r1,#0
    mov r7, #0x4e                        @ call system gettimeofday
    svc #0
    cmp r0,#0                            @ error ?
    blt 100f                             @ return error
                                         @ compute time
    ldr r0,iAdrdwDebut                   @ start time area
    //vidmemtit mesure r0 2
    ldr r2,[r0]                          @ secondes
    ldr r3,[r0,#4]                       @ micro secondes
    ldr r0,iAdrdwFin                     @ end time area
    ldr r1,[r0]                          @ secondes
    ldr r0,[r0,#4]                       @ micro secondes
    sub r2,r1,r2                         @ secondes number
    subs r3,r0,r3                        @ microsecondes number
    sublt r2,#1                          @ if negative sub 1 seconde to secondes
    ldr r1,iSecMicro
    addlt r3,r1                          @ and add 1000000 to microsecondes number
    mov r0,r2                            @ conversion secondes
    ldr r1,iAdrsSecondes
    bl conversion10
    mov r0,r3                            @ conversion microsecondes
    ldr r1,iAdrsMicroS
    bl conversion10
    ldr r0,iAdrszMessTemps
    bl affichageMess                     @ display message
    add r8,#1
    cmp r8,#NBMEASURE
    ble 1b
    ldr r0,iAdrszMessSep                 @ display separator
    bl affichageMess
100:
    pop {r1-r8,lr}                       @ restaur registers
    bx lr                                @ function return
iMax:                 .int N1
iAdrdwDebut:          .int dwDebut
iAdrdwFin:            .int dwFin
iSecMicro:            .int 1000000
iAdrsSecondes:        .int sSecondes
iAdrsMicroS:          .int sMicroS
iAdrszMessTemps:      .int szMessTemps
iAdrszMessSep:        .int szMessSep

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                   @ save  registres
    mov r2,#0                               @ counter length
1:                                          @ loop length calculation
    ldrb r1,[r0,r2]                         @ read octet start position + index
    cmp r1,#0                               @ if 0 its over
    addne r2,r2,#1                          @ else add 1 in the length
    bne 1b                                  @ and loop
                                            @ so here r2 contains the length of the message
    mov r1,r0                               @ address message in r1
    mov r0,#STDOUT                          @ code to write to the standard output Linux
    mov r7, #WRITE                          @ code call system "write"
    svc #0                                  @ call systeme
    pop {r0,r1,r2,r7,lr}                    @ restaur registers */
    bx lr                                   @ return
/******************************************************************/
/*     Converting a register to a decimal                                 */
/******************************************************************/
/* r0 contains value and r1 address area   */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                         @ save registers
    mov r3,r1
    mov r2,#LGZONECAL
1:                                          @ start loop
    bl divisionpar10                        @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                              @ digit
    strb r1,[r3,r2]                         @ store digit on area
    cmp r0,#0                               @ stop if quotient = 0
    subne r2,#1                               @ previous position
    bne 1b                                  @ else loop
                                            @ end replaces digit in front of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]                         @ store in area begin
    add r4,#1
    add r2,#1                               @ previous position
    cmp r2,#LGZONECAL                       @ end
    ble 2b                                  @ loop
    mov r1,#' '
3:
    strb r1,[r3,r4]
    add r4,#1
    cmp r4,#LGZONECAL                       @ end
    ble 3b
100:
    pop {r1-r4,lr}                          @ restaur registres
    bx lr                                   @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
    push {r2-r4}                           @ save registers  */
    mov r4,r0
    mov r3,#0x6667                         @ r3 <- magic_number  lower
    movt r3,#0x6666                        @ r3 <- magic_number  upper
    smull r1, r2, r3, r0                   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
    mov r2, r2, ASR #2                     @ r2 <- r2 >> 2
    mov r1, r0, LSR #31                    @ r1 <- r0 >> 31
    add r0, r2, r1                         @ r0 <- r2 + r1
    add r2,r0,r0, lsl #2                   @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                   @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2-r4}
    bx lr                                  @ return


      IF (STYLE.EQ."PRE")  CALL OUT(HAS)
      IF (LINKL(HAS).GT.0) CALL TARZAN(LINKL(HAS),STYLE)
      IF (STYLE.EQ."IN")   CALL OUT(HAS)
      IF (LINKR(HAS).GT.0) CALL TARZAN(LINKR(HAS),STYLE)
      IF (STYLE.EQ."POST") CALL OUT(HAS)


/* REXX (required by some interpreters) */
Numeric Digits 1000000
ttest ='[(10, 13), (56, 101), (1030, 10009), (44402, 100049)]'
Do While pos('(',ttest)>0
  Parse Var ttest '(' n ',' p ')' ttest
  r = tonelli(n, p)
  Say "n =" n "p =" p
  Say "          roots :" r (p - r)
  End
Exit

legendre: Procedure
  Parse Arg a, p
  return pow(a, (p - 1) % 2, p)

tonelli: Procedure
  Parse Arg n, p
  q = p - 1
  s = 0
  Do while q // 2 == 0
    q = q % 2
    s = s+1
    End
  if s == 1 Then
    return pow(n, (p + 1) % 4, p)
  Do z=2 To p
    if p - 1 == legendre(z, p) Then
      Leave
    End
  c = pow(z, q, p)
  r = pow(n, (q + 1) / 2, p)
  t = pow(n, q, p)
  m = s
  t2 = 0
  Do while (t - 1) // p <> 0
    t2 = (t * t) // p
    Do i=1 To m
      if (t2 - 1) // p == 0 Then
        Leave
      t2 = (t2 * t2) // p
      End
    y=2**(m - i - 1)
    b = pow(c, y, p)
    If b=10008 Then Trace ?R
    r = (r * b) // p
    c = (b * b) // p
    t = (t * c) // p
    m = i
    End
  return r
pow: Procedure
  Parse Arg x,y,z
  If y>0 Then
    p=x**y
  Else p=x
  If z>'' Then
    p=p//z
  Return p


benchmark [
    print "starting function"
    pause 2000
    print "function ended"
]


MsgBox % time("fx")
Return

fx()
{
  Sleep, 1000
}

time(function, parameter=0)
{
  SetBatchLines -1  ; don't sleep for other green threads
  StartTime := A_TickCount
  %function%(parameter)
  Return ElapsedTime := A_TickCount - StartTime . " milliseconds"
}


' Time a function
SUB timed()
    SLEEP 7000
END SUB

st = TIMER
timed()
et = TIMER
PRINT st, ", ", et


DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE

timestart = TIMER
SLEEP 1 'code or function to execute goes here
timedone = TIMER

'midnight check:
IF timedone < timestart THEN timedone = timedone + 86400
timeelapsed = timedone - timestart


#define NULL 0

Dim Shared As Byte maxnodos = 100
Dim Shared As Byte raiz = 0
Dim Shared As Byte izda = 1
Dim Shared As Byte dcha = 2
Dim Shared As Byte arbol(maxnodos, 3)

Sub crear_arbol()
    arbol(1, raiz) = 1
    arbol(1, izda) = 2 : arbol(1, dcha) = 3
    arbol(2, raiz) = 2
    arbol(2, izda) = 4 : arbol(2, dcha) = 5
    arbol(3, raiz) = 3
    arbol(3, izda) = 6 : arbol(3, dcha) = NULL
    arbol(4, raiz) = 4
    arbol(4, izda) = 7 : arbol(4, dcha) = NULL
    arbol(5, raiz) = 5
    arbol(5, izda) = NULL : arbol(5, dcha) = NULL
    arbol(6, raiz) = 6
    arbol(6, izda) = 8 : arbol(6, dcha) = 9
    arbol(7, raiz) = 7
    arbol(7, izda) = NULL : arbol(7, dcha) = NULL
    arbol(8, raiz) = 8
    arbol(8, izda) = NULL : arbol(8, dcha) = NULL
    arbol(9, raiz) = 9
    arbol(9, izda) = NULL : arbol(9, dcha) = NULL
End Sub

Sub recorrido_preorder(nodo As Byte)
    If nodo <> NULL Then
        Print arbol(nodo, raiz);
        recorrido_preorder(arbol(nodo, izda))
        recorrido_preorder(arbol(nodo, dcha))
    End If
End Sub

Sub recorrido_postorder(nodo As Byte)
    If nodo <> NULL Then
        recorrido_postorder(arbol(nodo, izda))
        recorrido_postorder(arbol(nodo, dcha))
        Print arbol(nodo, raiz);
    End If
End Sub

Sub recorrido_inorden(nodo As Byte)
    If nodo <> NULL Then
        recorrido_inorden(arbol(nodo, izda))
        Print arbol(nodo, raiz);
        recorrido_inorden(arbol(nodo, dcha))
    End If
End Sub

Sub recorrido_ordenXnivel(nodo As Byte)
    Dim As Byte actual = 1
    Dim As Byte primero_libre = actual + 1
    Dim As Byte cola(maxnodos)
    cola(actual) = nodo

    While cola(actual) <> NULL
        If arbol(cola(actual), izda) <> NULL Then
            cola(primero_libre) = arbol(cola(actual), izda)
            primero_libre += 1
        End If
        If arbol(cola(actual), dcha) <> NULL Then
            cola(primero_libre) = arbol(cola(actual), dcha)
            primero_libre += 1
        End If
        Print arbol(cola(actual), raiz);
        actual += 1
    Wend
End Sub


sequence names
enum RANK, NAME, DEP    -- content of names
-- rank is 1 for items to compile first, then 2, etc,
--      or 0 if cyclic dependencies prevent compilation.
-- name is handy, and makes the result order alphabetic!
-- dep is a list of dependencies (indexes to other names)

function add_dependency(string name)
    integer k = find(name,vslice(names,NAME))
    if k=0 then
        names = append(names,{0,name,{}})
        k = length(names)
    end if
    return k
end function

procedure topsort(string input)
    names = {}
    sequence lines = split(input,'\n')
    for i=1 to length(lines) do
        sequence line = split(lines[i]),
                 dependencies = {}
        integer k = add_dependency(line[1])
        for j=2 to length(line) do
            integer l = add_dependency(line[j])
            if l!=k then -- ignore self-references
                dependencies &= l
            end if
        end for
        names[k][DEP] = dependencies
    end for

    -- Now populate names[RANK] iteratively:
    bool more = true
    integer rank = 0
    while more do
        more = false
        rank += 1
        for i=1 to length(names) do
            if names[i][RANK]=0 then
                bool ok = true
                for j=1 to length(names[i][DEP]) do
                    integer ji = names[i][DEP][j],
                            nr = names[ji][RANK]
                    if nr=0 or nr=rank then
                        -- not yet compiled, or same pass
                        ok = false
                        exit
                    end if
                end for
                if ok then
                    names[i][RANK] = rank
                    more = true
                end if
            end if
        end for
    end while

    names = sort(names) -- (ie by [RANK=1] then [NAME=2])
    integer prank = names[1][RANK]
    if prank=0 then puts(1,"** CYCLIC **:") end if
    for i=1 to length(names) do
        rank = names[i][RANK]
        if i>1 then
            puts(1,iff(rank=prank?" ":"\n"))
        end if
        puts(1,names[i][NAME])
        prank = rank
    end for
    puts(1,"\n")
end procedure

constant input = """
des_system_lib  std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01            ieee dw01 dware gtech
dw02            ieee dw02 dware
dw03            std synopsys dware dw03 dw02 dw01 ieee gtech
dw04            dw04 ieee dw01 dware gtech
dw05            dw05 ieee dware
dw06            dw06 ieee dware
dw07            ieee dware
dware           ieee dware
gtech           ieee gtech
ramlib          std ieee
std_cell_lib    ieee std_cell_lib
synopsys"""

topsort(input)
puts(1,"\nbad input:\n")
topsort(input&"\ndw01 dw04")


Imports System.Numerics

Module Module1

    Class Solution
        ReadOnly root1 As BigInteger
        ReadOnly root2 As BigInteger
        ReadOnly exists As Boolean

        Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean)
            root1 = r1
            root2 = r2
            exists = e
        End Sub

        Public Function GetRoot1() As BigInteger
            Return root1
        End Function

        Public Function GetRoot2() As BigInteger
            Return root2
        End Function

        Public Function GetExists() As Boolean
            Return exists
        End Function
    End Class

    Function Ts(n As BigInteger, p As BigInteger) As Solution
        If BigInteger.ModPow(n, (p - 1) / 2, p) <> 1 Then
            Return New Solution(0, 0, False)
        End If

        Dim q As BigInteger = p - 1
        Dim ss = BigInteger.Zero
        While (q Mod 2) = 0
            ss += 1
            q >>= 1
        End While

        If ss = 1 Then
            Dim r1 = BigInteger.ModPow(n, (p + 1) / 4, p)
            Return New Solution(r1, p - r1, True)
        End If

        Dim z As BigInteger = 2
        While BigInteger.ModPow(z, (p - 1) / 2, p) <> p - 1
            z += 1
        End While
        Dim c = BigInteger.ModPow(z, q, p)
        Dim r = BigInteger.ModPow(n, (q + 1) / 2, p)
        Dim t = BigInteger.ModPow(n, q, p)
        Dim m = ss

        Do
            If t = 1 Then
                Return New Solution(r, p - r, True)
            End If
            Dim i = BigInteger.Zero
            Dim zz = t
            While zz <> 1 AndAlso i < (m - 1)
                zz = zz * zz Mod p
                i += 1
            End While
            Dim b = c
            Dim e = m - i - 1
            While e > 0
                b = b * b Mod p
                e = e - 1
            End While
            r = r * b Mod p
            c = b * b Mod p
            t = t * c Mod p
            m = i
        Loop
    End Function

    Sub Main()
        Dim pairs = New List(Of Tuple(Of Long, Long)) From {
            New Tuple(Of Long, Long)(10, 13),
            New Tuple(Of Long, Long)(56, 101),
            New Tuple(Of Long, Long)(1030, 10009),
            New Tuple(Of Long, Long)(1032, 10009),
            New Tuple(Of Long, Long)(44402, 100049),
            New Tuple(Of Long, Long)(665820697, 1000000009),
            New Tuple(Of Long, Long)(881398088036, 1000000000039)
        }

        For Each pair In pairs
            Dim sol = Ts(pair.Item1, pair.Item2)
            Console.WriteLine("n = {0}", pair.Item1)
            Console.WriteLine("p = {0}", pair.Item2)
            If sol.GetExists() Then
                Console.WriteLine("root1 = {0}", sol.GetRoot1())
                Console.WriteLine("root2 = {0}", sol.GetRoot2())
            Else
                Console.WriteLine("No solution exists")
            End If
            Console.WriteLine()
        Next

        Dim bn = BigInteger.Parse("41660815127637347468140745042827704103445750172002")
        Dim bp = BigInteger.Pow(10, 50) + 577
        Dim bsol = Ts(bn, bp)
        Console.WriteLine("n = {0}", bn)
        Console.WriteLine("p = {0}", bp)
        If bsol.GetExists() Then
            Console.WriteLine("root1 = {0}", bsol.GetRoot1())
            Console.WriteLine("root2 = {0}", bsol.GetRoot2())
        Else
            Console.WriteLine("No solution exists")
        End If
    End Sub

End Module


call cont(10000000)
print msec; " milliseconds"

t0 = msec
call cont(10000000)
print msec+t0; " milliseconds"
end

subroutine cont(n)
	sum = 0
	for i = 1 to n
		sum += 1
	next i
end subroutine


@echo off
Setlocal EnableDelayedExpansion

call :clock

::timed function:fibonacci series.....................................
set /a a=0 ,b=1,c=1
:loop
if %c% lss 2000000000 echo %c% & set /a c=a+b,a=b, b=c & goto loop
::....................................................................

call :clock

echo  Function executed in %timed% hundredths of second
goto:eof

:clock
if not defined timed set timed=0
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
set /A timed = "(((1%%a - 100) * 60 + (1%%b - 100)) * 60 + (1%%c - 100))  * 100 + (1%%d - 100)- %timed%"
)
goto:eof


start%=TIME:REM centi-second timer
REM perform processing
lapsed%=TIME-start%


( ( time
  =   fun funarg t0 ret
    .   !arg:(?fun.?funarg)
      & clk$:?t0
      & !fun$!funarg:?ret
      & (!ret.flt$(clk$+-1*!t0,3) s)
  )
& ( fib
  =
    .   !arg:<2&1
      | fib$(!arg+-1)+fib$(!arg+-2)
  )
& time$(fib.30)
)


#include <stdio.h>
#include <time.h>

int identity(int x) { return x; }

int sum(int s)
{
  int i;
  for(i=0; i < 1000000; i++) s += i;
  return s;
}

#ifdef CLOCK_PROCESS_CPUTIME_ID
/* cpu time in the current process */
#define CLOCKTYPE  CLOCK_PROCESS_CPUTIME_ID
#else
/* this one should be appropriate to avoid errors on multiprocessors systems */
#define CLOCKTYPE  CLOCK_MONOTONIC
#endif

double time_it(int (*action)(int), int arg)
{
  struct timespec tsi, tsf;

  clock_gettime(CLOCKTYPE, &tsi);
  action(arg);
  clock_gettime(CLOCKTYPE, &tsf);

  double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
  long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
  return elaps_s + ((double)elaps_ns) / 1.0e9;
}

int main()
{
  printf("identity (4) takes %lf s\n", time_it(identity, 4));
  printf("sum      (4) takes %lf s\n", time_it(sum, 4));
  return 0;
}


data Tree = Empty | Node( value, left, right )

def
  preorder( Empty )          =  []
  preorder( Node(v, l, r) )  =  [v] + preorder( l ) + preorder( r )

  inorder( Empty )           =  []
  inorder( Node(v, l, r) )   =  inorder( l ) + [v] + inorder( r )

  postorder( Empty )         =  []
  postorder( Node(v, l, r) ) =  postorder( l ) + postorder( r ) + [v]

  levelorder( x ) =
    def
      order( [] )                 =  []
      order( Empty         : xs ) =  order( xs )
      order( Node(v, l, r) : xs ) =  v : order( xs + [l, r] )

    order( [x] )

tree =    Node( 1,
            Node( 2,
              Node( 4,
                Node( 7, Empty, Empty ),
                Empty ),
              Node( 5, Empty, Empty ) ),
            Node( 3,
              Node( 6,
                Node( 8, Empty, Empty ),
                Node( 9, Empty, Empty ) ),
              Empty ) )

println( preorder(tree) )
println( inorder(tree) )
println( postorder(tree) )
println( levelorder(tree) )


topological_sort(Precedences, Sorted) =>

  Edges = [K=V : [K,V] in Precedences],
  Nodes = (domain(Edges) ++ range(Edges)).remove_dups(),
  Sorted1 = [],
  while (member(X,Nodes), not membchk(X,range(Edges)))
      Sorted1 := Sorted1 ++ [X],
      Nodes := Nodes.delete(X),
      Edges := Edges.delete_key(X)
  end,
  % detect and remove a cycle
  if Nodes.length > 0 then
    println("\nThe graph is cyclic. Here's the detected cycle."),
    println(nodes_in_cycle=Nodes),
    println(edges_in_cycle=Edges),
    Sorted = [without_cycle=Sorted1,cycle=Nodes]
  else
    Sorted = Sorted1
  end,
  nl.

% domain are the keys in L
domain(L) = [K : K=_V in L].

% range are the values of L
range(L) = [V : _K=V in L].

% deletes all pairs in L where a key is X
% (this is lessf on a multi-map in GNU SETL)
delete_key(L,X) = [K=V : K=V in L, K!=X].


(de sortDependencies (Lst)
   (setq Lst                              # Build a flat list
      (uniq
         (mapcan
            '((L)
               (put (car L) 'dep (cdr L)) # Store dependencies in 'dep' properties
               (copy L) )
            (mapcar uniq Lst) ) ) )       # without self-dependencies
   (make
      (while Lst
         (ifn (find '((This) (not (: dep))) Lst)   # Found non-depending lib?
            (quit "Can't resolve dependencies" Lst)
            (del (link @) 'Lst)                    # Yes: Store in result
            (for This Lst                          # and remove from 'dep's
               (=: dep (delete @ (: dep))) ) ) ) ) )


import "/dynamic" for Tuple
import "/big" for BigInt

var Solution = Tuple.create("Solution", ["root1", "root2", "exists"])

var ts = Fn.new { |n, p|
    if (n is Num) n = BigInt.new(n)
    if (p is Num) p = BigInt.new(p)

    var powModP = Fn.new { |a, e| a.modPow(e, p) }

    var ls = Fn.new { |a| powModP.call(a, p.dec / BigInt.two) }

    if (ls.call(n) != BigInt.one) return Solution.new(BigInt.zero, BigInt.zero, false)
    var q = p.dec
    var ss = BigInt.zero
    while (q & BigInt.one == BigInt.zero) {
        ss = ss.inc
        q = q >> 1
    }
    if (ss == BigInt.one) {
        var r1 = powModP.call(n, p.inc / BigInt.four)
        return Solution.new(r1, p - r1, true)
    }
    var z = BigInt.two
    while (ls.call(z) != p.dec) z = z.inc
    var c = powModP.call(z, q)
    var r = powModP.call(n, q.inc/BigInt.two)
    var t = powModP.call(n, q)
    var m = ss
    while (true) {
        if (t == BigInt.one) return Solution.new(r, p - r, true)
        var i = BigInt.zero
        var zz = t
        while (zz != BigInt.one && i < m.dec) {
            zz = zz * zz % p
            i = i.inc
        }
        var b = c
        var e = m - i.inc
        while (e > BigInt.zero) {
            b = b * b % p
            e = e.dec
        }
        r = r * b % p
        c = b * b % p
        t = t * c % p
        m = i
    }
}

var pairs = [
    [10, 13], [56, 101], [1030, 10009], [1032, 10009], [44402, 100049],
    [665820697, 1000000009], [881398088036, 1000000000039]
]

for (pair in pairs) {
    var n = pair[0]
    var p = pair[1]
    var sol = ts.call(n, p)
    System.print("n     = %(n)")
    System.print("p     = %(p)")
    if (sol.exists) {
        System.print("root1 = %(sol.root1)")
        System.print("root2 = %(sol.root2)")
    } else {
        System.print("No solution exists")
    }
    System.print()
}

var bn = BigInt.new("41660815127637347468140745042827704103445750172002")
var bp = BigInt.ten.pow(50) + BigInt.new(577)
var bsol = ts.call(bn, bp)
System.print("n     = %(bn)")
System.print("p     = %(bp)")
if (bsol.exists) {
    System.print("root1 = %(bsol.root1)")
    System.print("root2 = %(bsol.root2)")
} else {
    System.print("No solution exists")
}


using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        Stopwatch sw = new Stopwatch();

        sw.Start();
        DoSomething();
        sw.Stop();

        Console.WriteLine("DoSomething() took {0}ms.", sw.Elapsed.TotalMilliseconds);
    }

    static void DoSomething() {
        Thread.Sleep(1000);

        Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum();  // Sum even numers from 1 to 10000
    }
}


#include <ctime>
#include <iostream>
using namespace std;

int identity(int x) { return x; }
int sum(int num) {
  for (int i = 0; i < 1000000; i++)
    num += i;
  return num;
}

double time_it(int (*action)(int), int arg) {
  clock_t start_time = clock();
  action(arg);
  clock_t finis_time = clock();
  return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}

int main() {
  cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
  cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
  return 0;
}


maxnodes%=100 ! set a limit to size of tree
content%=0 ! index of content field
left%=1 ! index of left tree
right%=2 ! index of right tree
DIM tree%(maxnodes%,3) ! create space for tree
'
OPENW 1
CLEARW 1
'
@create_tree
PRINT "Preorder:   ";
@preorder_traversal(1)
PRINT ""
PRINT "Inorder:    ";
@inorder_traversal(1)
PRINT ""
PRINT "Postorder:  ";
@postorder_traversal(1)
PRINT ""
PRINT "Levelorder: ";
@levelorder_traversal(1)
PRINT ""
'
~INP(2)
CLOSEW 1
'
' Define the example tree
'
PROCEDURE create_tree
  tree%(1,content%)=1
  tree%(1,left%)=2
  tree%(1,right%)=3
  tree%(2,content%)=2
  tree%(2,left%)=4
  tree%(2,right%)=5
  tree%(3,content%)=3
  tree%(3,left%)=6
  tree%(3,right%)=0 ! 0 is used for no subtree
  tree%(4,content%)=4
  tree%(4,left%)=7
  tree%(4,right%)=0
  tree%(5,content%)=5
  tree%(5,left%)=0
  tree%(5,right%)=0
  tree%(6,content%)=6
  tree%(6,left%)=8
  tree%(6,right%)=9
  tree%(7,content%)=7
  tree%(7,left%)=0
  tree%(7,right%)=0
  tree%(8,content%)=8
  tree%(8,left%)=0
  tree%(8,right%)=0
  tree%(9,content%)=9
  tree%(9,left%)=0
  tree%(9,right%)=0
RETURN
'
' Preorder traversal from given node
'
PROCEDURE preorder_traversal(node%)
  IF node%<>0 ! 0 means there is no node
    PRINT tree%(node%,content%);
    preorder_traversal(tree%(node%,left%))
    preorder_traversal(tree%(node%,right%))
  ENDIF
RETURN
'
' Postorder traversal from given node
'
PROCEDURE postorder_traversal(node%)
  IF node%<>0 ! 0 means there is no node
    postorder_traversal(tree%(node%,left%))
    postorder_traversal(tree%(node%,right%))
    PRINT tree%(node%,content%);
  ENDIF
RETURN
'
' Inorder traversal from given node
'
PROCEDURE inorder_traversal(node%)
  IF node%<>0 ! 0 means there is no node
    inorder_traversal(tree%(node%,left%))
    PRINT tree%(node%,content%);
    inorder_traversal(tree%(node%,right%))
  ENDIF
RETURN
'
' Level order traversal from given node
'
PROCEDURE levelorder_traversal(node%)
  LOCAL nodes%,first_free%,current%
  '
  ' Set up initial queue of nodes
  '
  DIM nodes%(maxnodes%) ! some working space to store queue of nodes
  current%=1
  nodes%(current%)=node%
  first_free%=current%+1
  '
  WHILE nodes%(current%)<>0
    ' add the children of current node onto queue
    IF tree%(nodes%(current%),left%)<>0
      nodes%(first_free%)=tree%(nodes%(current%),left%)
      first_free%=first_free%+1
    ENDIF
    IF tree%(nodes%(current%),right%)<>0
      nodes%(first_free%)=tree%(nodes%(current%),right%)
      first_free%=first_free%+1
    ENDIF
    ' print the current node content
    PRINT tree%(nodes%(current%),content%);
    ' advance to next node
    current%=current%+1
  WEND
RETURN


#Input Data
$a[email protected]"
des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01             ieee dw01 dware gtech
dw02             ieee dw02 dware
dw03             std synopsys dware dw03 dw02 dw01 ieee gtech
dw04             dw04 ieee dw01 dware gtech
dw05             dw05 ieee dware
dw06             dw06 ieee dware
dw07             ieee dware
dware            ieee dware
gtech            ieee gtech
ramlib           std ieee
std_cell_lib     ieee std_cell_lib
synopsys
"@
#Convert to Object[]
$c = switch ( $a.split([char] 10) ) {
    $_ {
        $b=$_.split(' ')
        New-Object PSObject -Property @{
            Library = $b[0]
            "Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
        }
    }
}
#Add pure dependencies
$c | ForEach-Object {
    $_."Library Dependencies" | Where-Object {
        $d=$_
        $(:andl foreach($i in $c) {
            if($d -match $i.Library) {
                $false
                break andl
            }
        }) -eq $null
    } | ForEach-Object {
        $c+=New-Object PSObject -Property @{
            Library=$_
            "Library Dependencies"[email protected]()
        }
    }
}
#Associate with a dependency value
##Initial Dependency Value
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
    Name="Dep Value"
    Expression={
        1
    }
}
##Modify Dependency Value, perform check for incorrect dependency
##Dep Value is determined by a parent child relationship, if a library is a parent, all libraries dependant on it are children
for( $i=0; $i -lt $d.count; $i++ ) {
    $errmsg=""
    foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
        #Foreach other Child Library where this is a dependency, increase the Dep Value of the Child
        if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
            if( $k -match $d[$i].Library ) {
                foreach( $n in $d[$i]."Library Dependencies" ) {
                    if( $n -match $d[$j].Library ) {
                        $errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
                        break
                    }
                }
                $true
                break orl
            }
        } ) ) {
            #If the child has already been processed, increase the Dep Value of its children
            if( $j -lt $i ) {
                foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
                    if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
                        if( $m -match $d[$j].Library ) {
                            $true
                            break orl2
                        }
                    } ) ) {
                        $d[$l]."Dep Value"+=$d[$i]."Dep Value"
                    }
                }
            }
            $d[$j]."Dep Value"+=$d[$i]."Dep Value"
        }
        if( $errmsg -ne "" ) {
            $errmsg
            $d=$null
            break
        }
    }
}
#Sort and Display
if( $d ) {
    $d | Sort "Dep Value",Library | ForEach-Object {
        "{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
    } {
        "{0,-14} $($_."Library Dependencies")" -f $_.Library
    }
}


var BN=Import("zklBigNum");
fcn modEq(a,b,p) { (a-b)%p==0 }
fcn legendre(a,p){ a.powm((p - 1)/2,p) }

fcn tonelli(n,p){ //(BigInt,Int|BigInt)
   _assert_(legendre(n,p)==1, "not a square (mod p)"+vm.arglist);
   q,s:=p-1,0;
   while(q.isEven){ q/=2; s+=1; }
   if(s==1) return(n.powm((p+1)/4,p));
   z:=[BN(2)..p].filter1('wrap(z){ legendre(z,p)==(p-1) });
   c,r,t,m,t2:=z.powm(q,p), n.powm((q+1)/2,p), n.powm(q,p), s, 0;
   while(not modEq(t,1,p)){
      t2=(t*t)%p;
      i:=1; while(not modEq(t2,1,p)){ i+=1; t2=(t2*t2)%p; } // assert(i<m)
      b:=c.powm(BN(1).shiftLeft(m-i-1), p);
      r,c,t,m = (r*b)%p, (b*b)%p, (t*c)%p, i;
   }
   r
}


  (defn fib []
    (map first
      (iterate
        (fn [[a b]] [b (+ a b)])
        [0 1])))

  (time (take 100 (fib)))


CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1)))
Evaluation took:
  0.151 seconds of real time
  0.019035 seconds of user run time
  0.01807 seconds of system run time
  0 calls to %EVAL
  0 page faults and
  2,400,256 bytes consed.


import std.stdio, std.datetime;

int identity(int x) {
    return x;
}

int sum(int num) {
    foreach (i; 0 .. 100_000_000)
        num += i;
    return num;
}

double timeIt(int function(int) func, int arg) {
    StopWatch sw;
    sw.start();
    func(arg);
    sw.stop();
    return sw.peek().usecs / 1_000_000.0;
}

void main() {
    writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
    writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));
}


#EndOfDataMarker$ = "::EndOfData::"
DataSection
  ;"LIBRARY: [LIBRARY_DEPENDENCY_1 LIBRARY_DEPENDENCY_2 ... LIBRARY_DEPENDENCY_N]
  Data.s "des_system_lib: [std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]"
  Data.s "dw01: [ieee dw01 dware gtech]"
  ;Data.s "dw01: [ieee dw01 dware gtech dw04]" ;comment the previous line and uncomment this one for cyclic dependency
  Data.s "dw02: [ieee dw02 dware]"
  Data.s "dw03: [std synopsys dware dw03 dw02 dw01 ieee gtech]"
  Data.s "dw04: [dw04 ieee dw01 dware gtech]"
  Data.s "dw05: [dw05 ieee dware]"
  Data.s "dw06: [dw06 ieee dware]"
  Data.s "dw07: [ieee dware]"
  Data.s "dware: [ieee dware]"
  Data.s "gtech: [ieee gtech]"
  Data.s "ramlib: [std ieee]"
  Data.s "std_cell_lib: [ieee std_cell_lib]"
  Data.s "synopsys: nil"
  Data.s #EndOfDataMarker$
EndDataSection

Structure DAG_node
  Value.s
  forRemoval.i ;flag marks elements that should be removed the next time they are accessed
  List dependencies.s()
EndStructure

If Not OpenConsole()
  MessageRequester("Error","Unable to open console")
  End
EndIf

;// initialize Directed Acyclic Graph //
Define i, itemData.s, firstBracketPos
NewList DAG.DAG_node()
Repeat
  Read.s itemData
  itemData = Trim(itemData)
  If itemData <> #EndOfDataMarker$
    AddElement(DAG())
    ;add library
    DAG()\Value = Trim(Left(itemData, FindString(itemData, ":", 1) - 1))
    ;parse library dependencies
    firstBracketPos = FindString(itemData, "[", 1)
    If firstBracketPos
      itemData = Trim(Mid(itemData, firstBracketPos + 1, FindString(itemData, "]", 1) - firstBracketPos - 1))
      For i = (CountString(itemData, " ") + 1) To 1 Step -1
        AddElement(DAG()\dependencies())
        DAG()\dependencies() = StringField(itemData, i, " ")
      Next
    EndIf
  EndIf
Until itemData = #EndOfDataMarker$

;// process DAG //
;create DAG entry for nodes listed in dependencies but without their own entry
NewMap libraries()
ForEach DAG()
  ForEach DAG()\dependencies()
    libraries(DAG()\dependencies()) = #True
    If DAG()\dependencies() = DAG()\Value
      DeleteElement(DAG()\dependencies()) ;remove self-dependencies
    EndIf
  Next
Next

ForEach DAG()
  If FindMapElement(libraries(),DAG()\Value)
    DeleteMapElement(libraries(),DAG()\Value)
  EndIf
Next

ResetList(DAG())
ForEach libraries()
  AddElement(DAG())
  DAG()\Value = MapKey(libraries())
Next
ClearMap(libraries())

;process DAG() repeatedly until no changes occur
NewList compileOrder.s()
Repeat
  noChangesMade = #True
  ForEach DAG()
    If DAG()\forRemoval
      DeleteElement(DAG())
    Else
      ;remove dependencies that have been placed in the compileOrder
      ForEach DAG()\dependencies()
        If FindMapElement(libraries(),DAG()\dependencies())
          DeleteElement(DAG()\dependencies())
        EndIf
      Next
      ;add DAG() entry to compileOrder if it has no more dependencies
      If ListSize(DAG()\dependencies()) = 0
        AddElement(compileOrder())
        compileOrder() = DAG()\Value
        libraries(DAG()\Value) = #True ;mark the library for removal as a dependency
        DAG()\forRemoval = #True
        noChangesMade = #False
      EndIf
    EndIf
  Next
Until noChangesMade

If ListSize(DAG())
  PrintN("Cyclic dependencies detected in:" + #CRLF$)
  ForEach DAG()
    PrintN(" " + DAG()\Value)
  Next
Else
  PrintN("Compile order:" + #CRLF$)
  ForEach compileOrder()
    PrintN(" " + compileOrder())
  Next
EndIf

Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()


def countTo(x) {
	println("Counting...")
	for _ in 1..x {}
	println("Done!")
}

def MX := <unsafe:java.lang.management.makeManagementFactory>
def threadMX := MX.getThreadMXBean()
require(threadMX.isCurrentThreadCpuTimeSupported())
threadMX.setThreadCpuTimeEnabled(true)

for count in [10000, 100000] {
	def start := threadMX.getCurrentThreadCpuTime()
	countTo(count)
	def finish := threadMX.getCurrentThreadCpuTime()
	println(`Counting to $count takes ${(finish-start)//1000000}ms`)
}


import system'calendar;
import system'routines;
import system'threading;
import system'math;
import extensions;

someProcess()
{
    threadControl.sleep(1000);

    new Range(0,10000).filterBy:(x => x.mod:2 == 0).summarize();
}

public program()
{
    var start := now;

    someProcess();

    var end := now;

    console.printLine("Time elapsed in msec:",(end - start).Milliseconds)
}


5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end).
{226391,ok}
6> Time/1000000. % Time is in microseconds.
0.226391
7> % Time is in microseconds.


package main

import "fmt"

type node struct {
    value       int
    left, right *node
}

func (n *node) iterPreorder(visit func(int)) {
    if n == nil {
        return
    }
    visit(n.value)
    n.left.iterPreorder(visit)
    n.right.iterPreorder(visit)
}

func (n *node) iterInorder(visit func(int)) {
    if n == nil {
        return
    }
    n.left.iterInorder(visit)
    visit(n.value)
    n.right.iterInorder(visit)
}

func (n *node) iterPostorder(visit func(int)) {
    if n == nil {
        return
    }
    n.left.iterPostorder(visit)
    n.right.iterPostorder(visit)
    visit(n.value)
}

func (n *node) iterLevelorder(visit func(int)) {
    if n == nil {
        return
    }
    for queue := []*node{n}; ; {
        n = queue[0]
        visit(n.value)
        copy(queue, queue[1:])
        queue = queue[:len(queue)-1]
        if n.left != nil {
            queue = append(queue, n.left)
        }
        if n.right != nil {
            queue = append(queue, n.right)
        }
        if len(queue) == 0 {
            return
        }
    }
}

func main() {
    tree := &node{1,
        &node{2,
            &node{4,
                &node{7, nil, nil},
                nil},
            &node{5, nil, nil}},
        &node{3,
            &node{6,
                &node{8, nil, nil},
                &node{9, nil, nil}},
            nil}}
    fmt.Print("preorder:    ")
    tree.iterPreorder(visitor)
    fmt.Println()
    fmt.Print("inorder:     ")
    tree.iterInorder(visitor)
    fmt.Println()
    fmt.Print("postorder:   ")
    tree.iterPostorder(visitor)
    fmt.Println()
    fmt.Print("level-order: ")
    tree.iterLevelorder(visitor)
    fmt.Println()
}

func visitor(value int) {
    fmt.Print(value, " ")
}


try:
    from functools import reduce
except:
    pass

data = {
    'des_system_lib':   set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()),
    'dw01':             set('ieee dw01 dware gtech'.split()),
    'dw02':             set('ieee dw02 dware'.split()),
    'dw03':             set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
    'dw04':             set('dw04 ieee dw01 dware gtech'.split()),
    'dw05':             set('dw05 ieee dware'.split()),
    'dw06':             set('dw06 ieee dware'.split()),
    'dw07':             set('ieee dware'.split()),
    'dware':            set('ieee dware'.split()),
    'gtech':            set('ieee gtech'.split()),
    'ramlib':           set('std ieee'.split()),
    'std_cell_lib':     set('ieee std_cell_lib'.split()),
    'synopsys':         set(),
    }

def toposort2(data):
    for k, v in data.items():
        v.discard(k) # Ignore self dependencies
    extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
    data.update({item:set() for item in extra_items_in_deps})
    while True:
        ordered = set(item for item,dep in data.items() if not dep)
        if not ordered:
            break
        yield ' '.join(sorted(ordered))
        data = {item: (dep - ordered) for item,dep in data.items()
                if item not in ordered}
    assert not data, "A cyclic dependency exists amongst %r" % data

print ('\n'.join( toposort2(data) ))


atom t
t = time()
some_procedure()
t = time() - t
printf(1,"Elapsed %f seconds.\n",t)


open System.Diagnostics
let myfunc data =
    let timer = new Stopwatch()
    timer.Start()
    let result = data |> expensive_processing
    timer.Stop()
    printf "elapsed %d ms" timer.ElapsedMilliseconds
    result


def preorder;
preorder = { Node node ->
    ([node] + node.children().collect { preorder(it) }).flatten()
}

def postorder;
postorder = { Node node ->
    (node.children().collect { postorder(it) } + [node]).flatten()
}

def inorder;
inorder = { Node node ->
    def kids = node.children()
    if (kids.empty) [node]
    else if (kids.size() == 1 &&  kids[0].'@right') [node] + inorder(kids[0])
    else inorder(kids[0]) + [node] + (kids.size()>1 ? inorder(kids[1]) : [])
}

def levelorder = { Node node ->
    def nodeList = []
    def level = [node]
    while (!level.empty) {
        nodeList += level
        def nextLevel = level.collect { it.children() }.flatten()
        level = nextLevel
    }
    nodeList
}

class BinaryNodeBuilder extends NodeBuilder {
    protected Object postNodeCompletion(Object parent, Object node) {
        assert node.children().size() < 3
        node
    }
}


deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())


USING: kernel sequences tools.time ;

[ 10000 <iota> sum drop ] time


: time: ( "word" -- )
  utime 2>R ' EXECUTE
  utime 2R> D-
  <# # # # # # # [CHAR] . HOLD #S #> TYPE ."  seconds" ;

1000 time: MS  \ 1.000081 seconds ok


c The subroutine to analyze
      subroutine do_something()
c For testing we just do nothing for 3 seconds
      call sleep(3)
      return
      end

c Main Program
      program timing
      integer(kind=8) start,finish,rate
      call system_clock(count_rate=rate)
      call system_clock(start)
c Here comes the function we want to time
      call do_something()
      call system_clock(finish)
      write(6,*) 'Elapsed Time in seconds:',float(finish-start)/rate
      return
      end


' FB 1.05.0 Win64

Function sumToLimit(limit As UInteger) As UInteger
  Dim sum As UInteger = 0
  For i As UInteger = 1 To limit
    sum += i
  Next
  Return sum
End Function

Dim As Double start = timer
Dim limit As UInteger = 100000000
Dim result As UInteger = sumToLimit(limit)
Dim ms As UInteger = Int(1000 * (timer - start) + 0.5)
Print "sumToLimit("; Str(limit); ") = "; result
Print "took ";  ms; " milliseconds to calculate"
Print
Print "Press any key to quit"
Sleep


---------------------- TREE TRAVERSAL --------------------

data Tree a
  = Empty
  | Node
      { value :: a,
        left :: Tree a,
        right :: Tree a
      }

preorder, inorder, postorder, levelorder :: Tree a -> [a]
preorder Empty = []
preorder (Node v l r) = v : preorder l <> preorder r

inorder Empty = []
inorder (Node v l r) = inorder l <> (v : inorder r)

postorder Empty = []
postorder (Node v l r) = postorder l <> postorder r <> [v]

levelorder x = loop [x]
  where
    loop [] = []
    loop (Empty : xs) = loop xs
    loop (Node v l r : xs) = v : loop (xs <> [l, r])

--------------------------- TEST -------------------------
tree :: Tree Int
tree =
  Node
    1
    ( Node
        2
        (Node 4 (Node 7 Empty Empty) Empty)
        (Node 5 Empty Empty)
    )
    ( Node
        3
        (Node 6 (Node 8 Empty Empty) (Node 9 Empty Empty))
        Empty
    )

asciiTree :: String
asciiTree =
  unlines
    [ "         1",
      "        / \\",
      "       /   \\",
      "      /     \\",
      "     2       3",
      "    / \\     /",
      "   4   5   6",
      "  /       / \\",
      " 7       8   9"
    ]

-------------------------- OUTPUT ------------------------
main :: IO ()
main = do
  putStrLn asciiTree
  mapM_ putStrLn $
    zipWith
      ( \s xs ->
          justifyLeft 14 ' ' (s <> ":")
            <> unwords (show <$> xs)
      )
      ["preorder", "inorder", "postorder", "level-order"]
      ([preorder, inorder, postorder, levelorder] <*> [tree])
  where
    justifyLeft n c s = take n (s <> replicate n c)


#lang racket

(define G
  (make-hash
   '((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02
                            dw01 ramlib ieee))
     (dw01           . (ieee dw01 dware gtech))
     (dw02           . (ieee dw02 dware))
     (dw03           . (std synopsys dware dw03 dw02 dw01 ieee gtech))
     (dw04           . (dw04 ieee dw01 dware gtech))
     (dw05           . (dw05 ieee dware))
     (dw06           . (dw06 ieee dware))
     (dw07           . (ieee dware))
     (dware          . (ieee dware))
     (gtech          . (ieee gtech))
     (ramlib         . (std ieee))
     (std_cell_lib   . (ieee std_cell_lib))
     (synopsys       . ()))))

(define (clean G)
  (define G* (hash-copy G))
  (for ([(from tos) G])
    ; remove self dependencies
    (hash-set! G* from (remove from tos))
    ; make sure all nodes are present in the ht
    (for ([to tos]) (hash-update! G* to (λ(_)_) '())))
  G*)

(define (incoming G)
  (define in (make-hash))
  (for* ([(from tos) G] [to tos])
    (hash-update! in to (λ(fs) (cons from fs)) '()))
  in)

(define (nodes G)       (hash-keys G))
(define (out G n)       (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))

(define (topo-sort G)
  (define n (length (nodes G)))
  (define in (incoming G))
  (define (no-incoming? n) (empty? (hash-ref in n '())))
  (let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
    (cond [(set-empty? S)
           (if (= (length L) n)
               L
               (error 'topo-sort (~a "cycle detected" G)))]
          [else
           (define n   (set-first S))
           (define S\n (set-rest S))
           (for ([m (out G n)])
             (remove! G n m)
             (remove! in m n)
             (when (no-incoming? m)
               (set! S\n (set-add S\n m))))
           (loop (cons n L) S\n)])))

(topo-sort (clean G))


sub print_topo_sort ( %deps ) {
    my %ba;
    for %deps.kv -> $before, @afters {
        for @afters -> $after {
            %ba{$before}{$after} = 1 if $before ne $after;
            %ba{$after} //= {};
        }
    }

    while %ba.grep( not *.value )».key -> @afters {
        say ~@afters.sort;
        %ba{@afters}:delete;
        for %ba.values { .{@afters}:delete }
    }

    say %ba ?? "Cycle found! {%ba.keys.sort}" !! '---';
}

my %deps =
    des_system_lib => < std synopsys std_cell_lib des_system_lib dw02
                                                     dw01 ramlib ieee >,
    dw01           => < ieee dw01 dware gtech                         >,
    dw02           => < ieee dw02 dware                               >,
    dw03           => < std synopsys dware dw03 dw02 dw01 ieee gtech  >,
    dw04           => < dw04 ieee dw01 dware gtech                    >,
    dw05           => < dw05 ieee dware                               >,
    dw06           => < dw06 ieee dware                               >,
    dw07           => < ieee dware                                    >,
    dware          => < ieee dware                                    >,
    gtech          => < ieee gtech                                    >,
    ramlib         => < std ieee                                      >,
    std_cell_lib   => < ieee std_cell_lib                             >,
    synopsys       => <                                               >;

print_topo_sort(%deps);
%deps<dw01> = <ieee dw01 dware gtech dw04>; # Add unresolvable dependency
print_topo_sort(%deps);


# Return the time passed in last function
time;


package empty

func Empty() {}

func Count() {
    // count to a million
    for i := 0; i < 1e6; i++ {
    }
}


import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean

def threadMX = ManagementFactory.threadMXBean
assert threadMX.currentThreadCpuTimeSupported
threadMX.threadCpuTimeEnabled = true

def clockCpuTime = { Closure c ->
    def start = threadMX.currentThreadCpuTime
    c.call()
    (threadMX.currentThreadCpuTime - start)/1000000
}


$t = uptime();

sleep(1);

echo uptime() - $t;


import System.CPUTime (getCPUTime)

-- We assume the function we are timing is an IO monad computation
timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c
timeIt action arg = do
  startTime <- getCPUTime
  action arg
  finishTime <- getCPUTime
  return $ fromIntegral (finishTime - startTime) / 1000000000000

-- Version for use with evaluating regular non-monadic functions
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ f = timeIt ((`seq` return ()) . f)


procedure main()
    bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
    showTree(bTree, preorder|inorder|postorder|levelorder)
end

procedure showTree(tree, f)
    writes(image(f),":\t")
    every writes(" ",f(tree)[1])
    write()
end

procedure preorder(L)
    if \L then suspend L | preorder(L[2|3])
end

procedure inorder(L)
    if \L then suspend inorder(L[2]) | L | inorder(L[3])
end

procedure postorder(L)
    if \L then suspend postorder(L[2|3]) | L
end

procedure levelorder(L)
    if \L then {
        queue := [L]
        while nextnode := get(queue) do {
            every put(queue, \nextnode[2|3])
            suspend nextnode
            }
        }
end


/*REXX pgm does a topological sort (orders such that no item precedes a dependent item).*/
iDep.=  0;      iPos.=  0;         iOrd.=  0     /*initialize some stemmed arrays to  0.*/
   nL= 15;         nd= 44;            nc= 69     /*     "       "  "parms"  and indices.*/
label= 'DES_SYSTEM_LIB   DW01     DW02    DW03   DW04   DW05   DW06   DW07'  ,
       'DWARE    GTECH   RAMLIB   STD_CELL_LIB   SYNOPSYS      STD    IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
      2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
             do i=1
             iL= word(iCode, i);          if iL==0  then leave
                do forever;               i= i+1
                iR= word(iCode, i);       if iR==0  then leave
                j= j+1;                   iDep.j.1= iL
                                          iDep.j.2= iR
                end   /*forever*/
             end      /*i*/
call tSort
say '═══compile order═══'
@=  'libraries found.)'
#=0;                            do o=nO  by -1  for nO;   #= #+1;  say word(label, iOrd.o)
                                end   /*o*/;              if #==0  then #= 'no'
say '   ('#   @;        say
say '═══unordered libraries═══'
#=0;                            do u=nO+1  to nL;         #= #+1;  say word(label, iOrd.u)
                                end   /*u*/;              if #==0  then #= 'no'
say '   ('#   "unordered"  @
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
                                do i=1  for nL;  iOrd.i= i;  iPos.i= i
                                end   /*i*/
       k= 1
                                do  until k<=j;              j  = k;            k= nL+1
                                    do i=1  for nd;          iL = iDep.i.1;    iR= iPos.iL
                                    ipL= iPos.iL;            ipR= iPos.iR
                                    if iL==iR | ipL>.k | ipL<j | ipR<j  then iterate
                                    k= k-1
                                    _= iOrd.k;               iPos._ = ipL
                                                             iPos.iL= k
                                    iOrd.ipL= iOrd.k;        iOrd.k = iL
                                    end   /*i*/
                                end       /*until*/
       nO= j-1;     return


t_start = TIME()    ! returns seconds since midnight
SYSTEM(WAIT = 1234) ! wait 1234 milliseconds
t_end = TIME()

WRITE(StatusBar) t_end - t_start, " seconds"


procedure timef(f)                               #: time a function f
local gcol,alloc,used,size,runtime,header,x,i

title := ["","total","static","string","block"]  # headings
collect()                                        # start with collected memory (before baseline)
every put(gcol  := [], -&collections)            # baseline collections count
every put(alloc := [], -&allocated)              # . total allocated space by region
every put(used  := [], -&storage)                # . currently used space by region - no total
every put(size  := [], -&regions)                # . current size of regions        - no total

write("Performance and Timing measurement for ",image(f),":")
runtime := &time                                 # base time
f()
write("Execution time=",&time-runtime," ms.")

every (i := 0, x := &collections) do  gcol[i +:= 1] +:= x
every (i := 0, x := &allocated  ) do alloc[i +:= 1] +:= x
every (i := 0, x := &storage    ) do  used[i +:= 1] +:= x
every (i := 0, x := &regions    ) do  size[i +:= 1] +:= x

push(gcol,"garbage collections:")
push(alloc,"memory allocated:")
push(used,"N/A","currently used:")
push(size,"N/A","current size:")

write("Memory Region and Garbage Collection Summary (delta):")
every (i := 0) <:= *!(title|gcol|alloc|used|size)
every x := (title|gcol|alloc|used|size) do {
   f := left
   every writes(f(!x,i + 3)) do f := right
   write()
   }
write("Note: static region values should be zero and may not be meaningful.")
return
end


theory Tree
imports Main
begin

datatype 'a tree = Leaf | Node "'a tree" 'a "'a tree"

definition example :: "int tree" where
  "example ≡
     Node
     (Node
        (Node
          (Node Leaf 7 Leaf)
          4
          Leaf
        )
        2
        (Node Leaf 5 Leaf)
     )
     1
     (Node
       (Node
         (Node Leaf 8 Leaf)
         6
         (Node Leaf 9 Leaf)
       )
       3
       Leaf
     )"

fun preorder :: "'a tree ⇒ 'a list" where
  "preorder Leaf = []"
| "preorder (Node l a r) = a # preorder l @ preorder r"

lemma "preorder example = [1, 2, 4, 7, 5, 3, 6, 8, 9]" by code_simp

fun inorder :: "'a tree ⇒ 'a list" where
  "inorder Leaf = []"
| "inorder (Node l a r) = inorder l @ [a] @ inorder r"

lemma "inorder example = [7, 4, 2, 5, 1, 8, 6, 9, 3]" by code_simp

fun postorder :: "'a tree ⇒ 'a list" where
  "postorder Leaf = []"
| "postorder (Node l a r) = postorder l @ postorder r @ [a]"

lemma "postorder example = [7, 4, 5, 2, 8, 9, 6, 3, 1]" by code_simp

lemma
  "set (inorder t) = set (preorder t)"
  "set (preorder t) = set (postorder t)"
  "set (inorder t) = set (postorder t)"
  by(induction t, simp, simp)+

text‹
For a breadth first search, we will have a queue of the nodes we still
want to visit. The type of the queue is \<^typ>‹'a tree list›.
With each step, summing the sizes of the subtrees in the queue,
the queue gets smaller. Thus, the breadth first search terminates.
Isabelle cannot figure out this termination argument automatically,
so we provide some help by defining what the size of a tree is.
›
fun tree_size :: "'a tree ⇒ nat" where
  "tree_size Leaf = 1"
| "tree_size (Node l _ r) = 1 + tree_size l + tree_size r"

function (sequential) bfs :: "'a tree list ⇒ 'a list" where
  "bfs [] = []"
| "bfs (Leaf#q) = bfs q"
| "bfs ((Node l a r)#q) = a # bfs (q @ [l,r])"
  by pat_completeness auto
termination bfs
  by(relation "measure (λqs. sum_list (map tree_size qs))") simp+

fun levelorder :: "'a tree ⇒ 'a list" where
  "levelorder t = bfs [t]"

lemma "levelorder example = [1, 2, 3, 4, 5, 6, 7, 8, 9]" by code_simp

end


require 'tsort'
class Hash
  include TSort
  alias tsort_each_node each_key
  def tsort_each_child(node, &block)
    fetch(node).each(&block)
  end
end

depends = {}
DATA.each do |line|
  key, *libs = line.split
  depends[key] = libs
  libs.each {|lib| depends[lib] ||= []}
end

begin
  p depends.tsort
  depends["dw01"] << "dw04"
  p depends.tsort
rescue TSort::Cyclic => e
  puts "\ncycle detected: #{e}"
end

__END__
des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01             ieee dw01 dware gtech
dw02             ieee dw02 dware
dw03             std synopsys dware dw03 dw02 dw01 ieee gtech
dw04             dw04 ieee dw01 dware gtech
dw05             dw05 ieee dware
dw06             dw06 ieee dware
dw07             ieee dware
dware            ieee dware
gtech            ieee gtech
ramlib           std ieee
std_cell_lib     ieee std_cell_lib
synopsys


use("benchmark")

func = method((1..50000) reduce(+))

Benchmark report(1, 1, func)


(defmacro time
  "Print the time it takes to evaluate body to stderr.\n
  Evaluates to body."
  [body]
  (with-syms [$start $val]
    ~(let [,$start (os/clock)
           ,$val ,body]
       (eprint (- (os/clock) ,$start))
       ,$val)))

(time (os/sleep 0.5))


import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class TimeIt {
	public static void main(String[] args) {
		final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
		assert threadMX.isCurrentThreadCpuTimeSupported();
		threadMX.setThreadCpuTimeEnabled(true);

		long start, end;
		start = threadMX.getCurrentThreadCpuTime();
		countTo(100000000);
		end = threadMX.getCurrentThreadCpuTime();
		System.out.println("Counting to 100000000 takes "+(end-start)/1000000+"ms");
		start = threadMX.getCurrentThreadCpuTime();
		countTo(1000000000L);
		end = threadMX.getCurrentThreadCpuTime();
		System.out.println("Counting to 1000000000 takes "+(end-start)/1000000+"ms");

	}

	public static void countTo(long x){
		System.out.println("Counting...");
		for(long i=0;i<x;i++);
		System.out.println("Done!");
	}
}


F token_with_escape(a, escape = ‘^’, separator = ‘|’)
   [String] result
   V token = ‘’
   V state = 0
   L(c) a
      I state == 0
         I c == escape
            state = 1
         E I c == separator
            result.append(token)
            token = ‘’
         E
            token ‘’= c
      E I state == 1
         token ‘’= c
         state = 0
   result.append(token)
   R result

print(token_with_escape(‘one^|uno||three^^^^|four^^^|^cuatro|’).map(s -> ‘'’s‘'’).join(‘, ’))