defmodule Files do
  def find_duplicate_files(dir) do
    IO.puts "\nDirectory : #{dir}"
    File.cd!(dir, fn ->
      Enum.filter(File.ls!, fn fname -> File.regular?(fname) end)
      |> Enum.group_by(fn file -> File.stat!(file).size end)
      |> Enum.filter(fn {_, files} -> length(files)>1 end)
      |> Enum.each(fn {size, files} ->
           Enum.group_by(files, fn file -> :erlang.md5(File.read!(file)) end)
           |> Enum.filter(fn {_, files} -> length(files)>1 end)
           |> Enum.each(fn {_md5, fs} ->
                IO.puts "  --------------------------------------------"
                Enum.each(fs, fn file ->
                  IO.puts "  #{inspect File.stat!(file).mtime}\t#{size}  #{file}"
                end)
              end)
         end)
    end)
  end
end

hd(System.argv) |> Files.find_duplicate_files


package main

import (
    "fmt"
    "crypto/md5"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
    "sort"
    "time"
)

type fileData struct {
    filePath string
    info     os.FileInfo
}

type hash [16]byte

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func checksum(filePath string) hash {
    bytes, err := ioutil.ReadFile(filePath)
    check(err)
    return hash(md5.Sum(bytes))
}

func findDuplicates(dirPath string, minSize int64) [][2]fileData {
    var dups [][2]fileData
    m := make(map[hash]fileData)
    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !info.IsDir() && info.Size() >= minSize {
            h := checksum(path)
            fd, ok := m[h]
            fd2 := fileData{path, info}
            if !ok {
                m[h] = fd2
            } else {
                dups = append(dups, [2]fileData{fd, fd2})
            }
        }
        return nil
    })
    check(werr)
    return dups
}

func main() {
    dups := findDuplicates(".", 1)
    fmt.Println("The following pairs of files have the same size and the same hash:\n")
    fmt.Println("File name                 Size      Date last modified")
    fmt.Println("==========================================================")
    sort.Slice(dups, func(i, j int) bool {
        return dups[i][0].info.Size() > dups[j][0].info.Size() // in order of decreasing size
    })
    for _, dup := range dups {
        for i := 0; i < 2; i++ {
            d := dup[i]
            fmt.Printf("%-20s  %8d    %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))
        }
        fmt.Println()
    }
}


FOR i=1 TO 100
    t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "")
    PRINT IIF(LEN(t$), t$, i)
NEXT i


*        Last Sunday of each month 31/01/2017
LASTSUND CSECT
         USING  LASTSUND,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    prolog
         ST     R13,4(R15)         " <-
         ST     R15,8(R13)         " ->
         LR     R13,R15            " addressability
         L      R4,YEAR            year
         SRDA   R4,32              .
         D      R4,=F'400'         year/400
         LTR    R4,R4              if year//400=0
         BZ     LEAP
         L      R4,YEAR            year
         SRDA   R4,32              .
         D      R4,=F'4'           year/4
         LTR    R4,R4              if year//4=0
         BNZ    NOTLEAP
         L      R4,YEAR            year
         SRDA   R4,32              .
         D      R4,=F'100'         year/400
         LTR    R4,R4              if year//100=0
         BZ     NOTLEAP
LEAP     MVC    DAYS+4(4),=F'29'   days(2)=29
NOTLEAP  L      R8,YEAR            year
         BCTR   R8,0               y=year-1
         LA     R7,42              42
         AR     R7,R8              +y
         LR     R3,R8              y
         SRA    R3,2               y/4
         AR     R7,R3              +y/4
         LR     R4,R8              y
         SRDA   R4,32              .
         D      R4,=F'100'         y/100
         LA     R4,0               .
         M      R4,=F'6'           *6
         AR     R7,R5              +6*(y/100)
         LR     R4,R8              y
         SRDA   R4,32              .
         D      R4,=F'400'         y/100
         AR     R7,R5              k=42+y+y/4+6*(y/100)+y/400
         LA     R6,1               m=1
LOOPM    C      R6,=F'12'          do m=1 to 12
         BH     ELOOPM
         LR     R1,R6              m
         SLA    R1,2               .
         L      R2,DAYS-4(R1)      days(m)
         AR     R7,R2              k=k+days(m)
         LR     R4,R7              k
         SRDA   R4,32              .
         D      R4,=F'7'           k/7
         SR     R2,R4              days(m)-k//7
         LR     R9,R2              d=days(m)-k//7
         L      R1,YEAR            year
         CVD    R1,DW              year: binary to packed
         OI     DW+7,X'0F'           zap sign
         UNPK   PG(4),DW             unpack (ZL4)
         CVD    R6,DW              m : binary to packed
         OI     DW+7,X'0F'           zap sign
         UNPK   PG+5(2),DW           unpack (ZL2)
         CVD    R9,DW              d: binary to packed
         OI     DW+7,X'0F'           zap sign
         UNPK   PG+8(2),DW           unpack (ZL2)
         XPRNT  PG,L'PG            print buffer
         LA     R6,1(R6)           m=m+1
         B      LOOPM
ELOOPM   L      R13,4(0,R13)       epilog
         LM     R14,R12,12(R13)    " restore
         XR     R15,R15            " rc=0
         BR     R14                exit
YEAR     DC     F'2013'            <== input year
DAYS     DC     F'31',F'28',F'31',F'30',F'31',F'30'
         DC     F'31',F'31',F'30',F'31',F'30',F'31'
PG       DC     CL80'YYYY-MM-DD'   buffer
XDEC     DS     CL12               temp
DW       DS     D                  packed (PL8) 15num
         YREGS
         END    LASTSUND


;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods
BYTE FUNC DayOfWeek(INT y BYTE m,d)	;1<=m<=12, y>1752
  BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]
  BYTE res

  IF m<3 THEN
    y==-1
  FI
  res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7
RETURN (res)

BYTE FUNC IsLeapYear(INT y)
  IF y MOD 100=0 THEN
    IF y MOD 400=0 THEN
      RETURN (1)
    ELSE
      RETURN (0)
    FI
  FI

  IF y MOD 4=0 THEN
    RETURN (1)
  FI
RETURN (0)

INT FUNC GetMaxDay(INT y BYTE m)
  BYTE ARRAY MaxDay=[31 28 31 30 31 30 31 31 30 31 30 31]

  IF m=2 AND IsLeapYear(y)=1 THEN
    RETURN (29)
  FI
RETURN (MaxDay(m-1))

PROC PrintB2(BYTE x)
  IF x<10 THEN
    Put('0)
  FI
  PrintB(x)
RETURN

PROC Main()
  INT MinYear=[1753],MaxYear=[9999],y
  BYTE m,d,last,maxD

  DO
    PrintF("Input year in range %I...%I: ",MinYear,MaxYear)
    y=InputI()
  UNTIL y>=MinYear AND y<=MaxYear
  OD

  FOR m=1 TO 12
  DO
    last=0
    maxD=GetMaxDay(y,m)
    FOR d=1 TO maxD
    DO
      IF DayOfWeek(y,m,d)=0 THEN
        last=d
      FI
    OD
    PrintI(y) Put('-)
    PrintB2(m) Put('-)
    PrintB2(last) PutE()
  OD
RETURN


ltp=:3 :0
  probe=. i.1 0
  while. #probe do.
    probe=. (#~ 1 p: y #.]),/(}.i.y),"0 _1/have=. probe
  end.
  >./y#.have
)


import java.math.BigInteger;
import java.util.*;

class LeftTruncatablePrime
{
  private static List<BigInteger> getNextLeftTruncatablePrimes(BigInteger n, int radix, int millerRabinCertainty)
  {
    List<BigInteger> probablePrimes = new ArrayList<BigInteger>();
    String baseString = n.equals(BigInteger.ZERO) ? "" : n.toString(radix);
    for (int i = 1; i < radix; i++)
    {
      BigInteger p = new BigInteger(Integer.toString(i, radix) + baseString, radix);
      if (p.isProbablePrime(millerRabinCertainty))
        probablePrimes.add(p);
    }
    return probablePrimes;
  }

  public static BigInteger getLargestLeftTruncatablePrime(int radix, int millerRabinCertainty)
  {
    List<BigInteger> lastList = null;
    List<BigInteger> list = getNextLeftTruncatablePrimes(BigInteger.ZERO, radix, millerRabinCertainty);
    while (!list.isEmpty())
    {
      lastList = list;
      list = new ArrayList<BigInteger>();
      for (BigInteger n : lastList)
        list.addAll(getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty));
    }
    if (lastList == null)
      return null;
    Collections.sort(lastList);
    return lastList.get(lastList.size() - 1);
  }

  public static void main(String[] args)
  {
    if (args.length != 2) {
      System.err.println("There must be exactly two command line arguments.");
      return;
    }
    int maxRadix;
    try {
      maxRadix = Integer.parseInt(args[0]);
      if (maxRadix < 3) throw new NumberFormatException();
    } catch (NumberFormatException e) {
      System.err.println("Radix must be an integer greater than 2.");
      return;
    }
    int millerRabinCertainty;
    try {
      millerRabinCertainty = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
      System.err.println("Miiller-Rabin Certainty must be an integer.");
      return;
    }
    for (int radix = 3; radix <= maxRadix; radix++)
    {
      BigInteger largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty);
      System.out.print("n=" + radix + ": ");
      if (largest == null)
        System.out.println("No left-truncatable prime");
      else
        System.out.println(largest + " (in base " + radix + "): " + largest.toString(radix));
    }
  }

}


var level : Integer;

procedure Recursive;
begin
   Inc(level);
   try
      Recursive;
   except
   end;
end;

Recursive;

Println('Recursion Level is ' + IntToStr(level));


rec-fun n:
	!. n
	rec-fun ++ n

rec-fun 0


func recurse i . .
  print i
  call recurse i + 1
.
call recurse 0


(defun my-recurse (n)
  (my-recurse (1+ n)))
(my-recurse 1)
=>
enters debugger at (my-recurse 595),
per the default max-lisp-eval-depth 600 in Emacs 24.1


- checks for wrong command line input (not existing directory / negative size)
- works on Windows as well as Unix Systems (tested with Mint 17 / Windows 7)


import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.security.*;
import java.util.*;

public class DuplicateFiles {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.err.println("Directory name and minimum file size are required.");
            System.exit(1);
        }
        try {
            findDuplicateFiles(args[0], Long.parseLong(args[1]));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void findDuplicateFiles(String directory, long minimumSize)
        throws IOException, NoSuchAlgorithmException {
        System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes.");
        Path path = FileSystems.getDefault().getPath(directory);
        FileVisitor visitor = new FileVisitor(path, minimumSize);
        Files.walkFileTree(path, visitor);
        System.out.println("The following sets of files have the same size and checksum:");
        for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {
            Map<Object, List<String>> map = e.getValue();
            if (!containsDuplicates(map))
                continue;
            List<List<String>> fileSets = new ArrayList<>(map.values());
            for (List<String> files : fileSets)
                Collections.sort(files);
            Collections.sort(fileSets, new StringListComparator());
            FileKey key = e.getKey();
            System.out.println();
            System.out.println("Size: " + key.size_ + " bytes");
            for (List<String> files : fileSets) {
                for (int i = 0, n = files.size(); i < n; ++i) {
                    if (i > 0)
                        System.out.print(" = ");
                    System.out.print(files.get(i));
                }
                System.out.println();
            }
        }
    }

    private static class StringListComparator implements Comparator<List<String>> {
        public int compare(List<String> a, List<String> b) {
            int len1 = a.size(), len2 = b.size();
            for (int i = 0; i < len1 && i < len2; ++i) {
                int c = a.get(i).compareTo(b.get(i));
                if (c != 0)
                    return c;
            }
            return Integer.compare(len1, len2);
        }
    }

    private static boolean containsDuplicates(Map<Object, List<String>> map) {
        if (map.size() > 1)
            return true;
        for (List<String> files : map.values()) {
            if (files.size() > 1)
                return true;
        }
        return false;
    }

    private static class FileVisitor extends SimpleFileVisitor<Path> {
        private MessageDigest digest_;
        private Path directory_;
        private long minimumSize_;
        private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();

        private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {
            directory_ = directory;
            minimumSize_ = minimumSize;
            digest_ = MessageDigest.getInstance("MD5");
        }

        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (attrs.size() >= minimumSize_) {
                FileKey key = new FileKey(file, attrs, getMD5Sum(file));
                Map<Object, List<String>> map = fileMap_.get(key);
                if (map == null)
                    fileMap_.put(key, map = new HashMap<>());
                List<String> files = map.get(attrs.fileKey());
                if (files == null)
                    map.put(attrs.fileKey(), files = new ArrayList<>());
                Path relative = directory_.relativize(file);
                files.add(relative.toString());
            }
            return FileVisitResult.CONTINUE;
        }

        private byte[] getMD5Sum(Path file) throws IOException {
            digest_.reset();
            try (InputStream in = new FileInputStream(file.toString())) {
                byte[] buffer = new byte[8192];
                int bytes;
                while ((bytes = in.read(buffer)) != -1) {
                    digest_.update(buffer, 0, bytes);
                }
            }
            return digest_.digest();
        }
    }

    private static class FileKey implements Comparable<FileKey> {
        private byte[] hash_;
        private long size_;

        private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {
            size_ = attrs.size();
            hash_ = hash;
        }

        public int compareTo(FileKey other) {
            int c = Long.compare(other.size_, size_);
            if (c == 0)
                c = hashCompare(hash_, other.hash_);
            return c;
        }
    }

    private static int hashCompare(byte[] a, byte[] b) {
        int len1 = a.length, len2 = b.length;
        for (int i = 0; i < len1 && i < len2; ++i) {
            int c = Byte.compare(a[i], b[i]);
            if (c != 0)
                return c;
        }
        return Integer.compare(len1, len2);
    }
}


BEGIN # find the last Sunday in each month of a year             #
    # returns true if year is a leap year, false otherwise       #
    # assumes year is in the Gregorian Calendar                  #
    PROC is leap year = ( INT year )BOOL:
         year MOD 400 = 0 OR ( year MOD 4 = 0 AND year MOD 100 /= 0 );
    # returns the day of the week of the specified date (d/m/y)  #
    #         Sunday = 1                                         #
    PROC day of week = ( INT d, m, y )INT:
         BEGIN
            INT mm := m;
            INT yy := y;
            IF mm <= 2 THEN
                mm := mm + 12;
                yy := yy - 1
            FI;
            INT j = yy OVER 100;
            INT k = yy MOD  100;
            (d + ( ( mm + 1 ) * 26 ) OVER 10 + k + k OVER 4 + j OVER 4 + 5 * j ) MOD 7
         END # day of week # ;
    # returns an array of the last Sunday of each month in year  #
    PROC last sundays = ( INT year )[]INT:
         BEGIN
            [ 1 : 12 ]INT last days := ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
            IF is leap year( year ) THEN last days[ 2 ] := 29 FI;
            # for each month, determine the day number of the    #
            # last Sunday                                        #
            [ 1 : 12 ]INT last;
            FOR m pos TO 12 DO
                INT dow := day of week( last days[ m pos ], m pos, year );
                IF dow = 0 # Saturday # THEN dow := 7 FI;
                # calculate the offset for the previous Sunday   #
                last[ m pos ] := ( last days[ m pos ] + 1 ) - dow
            OD;
            last
         END # last sundays # ;
    # test the last sundays procedure                            #
    INT   year = 2021;
    []INT last = last sundays( year );
    FOR m pos TO 12 DO
        print( ( whole( year, 0 )
               , IF m pos < 10 THEN "-0" ELSE "-1" FI
               , whole( m pos MOD 10, 0 )
               , "-"
               , whole( last[ m pos ], 0 )
               , newline
               )
             )
    OD
END


using Primes, Printf

function addmsdigit(p::Integer, b::Integer, s::Integer)
    a = Vector{typeof(p)}()
    q = p
    for i in 1:(b-1)
        q += s
        isprime(q) || continue
        push!(a, q)
    end
    return a
end

function lefttruncprime(pbase::Integer)
    a = Vector{BigInt}()
    append!(a, primes(pbase - 1))
    mlt = zero(BigInt)
    s = one(BigInt)
    while !isempty(a)
        mlt = maximum(a)
        s *= pbase
        for i in 1:length(a)
            p = popfirst!(a)
            append!(a, addmsdigit(p, pbase, s))
        end
    end
    return mlt
end

lo, hi = 3, 17
println("The largest left truncatable primes for bases", @sprintf(" %d to %d.", lo, hi))
for i in lo:hi
    mlt = lefttruncprime(i)
    @printf("%10d %-30d (%s)\n", i, mlt, string(mlt, base=i))
end


// version 1.1.2

import java.math.BigInteger

fun nextLeftTruncatablePrimes(n: BigInteger, radix: Int, certainty: Int): List<BigInteger> {
    val probablePrimes = mutableListOf<BigInteger>()
    val baseString = if (n == BigInteger.ZERO) "" else n.toString(radix)
    for (i in 1 until radix) {
        val p = BigInteger(i.toString(radix) + baseString, radix)
        if (p.isProbablePrime(certainty)) probablePrimes.add(p)
    }
    return probablePrimes
}

fun largestLeftTruncatablePrime(radix: Int, certainty: Int): BigInteger? {
    var lastList: List<BigInteger>? = null
    var list = nextLeftTruncatablePrimes(BigInteger.ZERO, radix, certainty)
    while (!list.isEmpty()) {
        lastList = list
        list = mutableListOf()
        for (n in lastList) list.addAll(nextLeftTruncatablePrimes(n, radix, certainty))
    }
    if (lastList == null) return null
    return lastList.sorted().last()
}

fun main(args: Array<String>) {
    print("Enter maximum radix : ")
    val maxRadix = readLine()!!.toInt()
    print("Enter certainty     : ")
    val certainty = readLine()!!.toInt()
    println()
    for (radix in 3..maxRadix) {
        val largest = largestLeftTruncatablePrime(radix, certainty)
        print("Base = ${"%-2d".format(radix)} : ")
        if (largest == null)
            println("No left truncatable prime")
        else
            println("${largest.toString().padEnd(35)} -> ${largest.toString(radix)}")
    }
}


MaxLeftTruncatablePrime := proc(b, $)
local i, j, c, p, sdprimes;
local tprimes := table();
    sdprimes := select(isprime, [seq(1..b-1)]);
    for p in sdprimes do
        if assigned(tprimes[p]) then
            next;
        end if;
        i := ilog[b](p)+1;
        j := 1;
        do
            c := j*b^i + p;
            if j >= b then
            # we have tried all 1 digit extensions of p, add p to tprimes and move back 1 digit
                tprimes[p] := p;
                if i = 1 then
                    # if we are at the first digit,  go to the next 1 digit prime
                    break;
                end if;
                i := i - 1;
                j := 1;
                p := p - iquo(p, b^i)*b^i;
            elif assigned(tprimes[c]) then
                j := j + 1;
            elif isprime(c) then
                p := c;
                i := i + 1;
                j := 1;
            else
                j := j+1;
            end if;
        end do;
    end do;
    return max(indices(tprimes, 'nolist'));
end proc;


let rec recurse n =
  recurse (n+1)

recurse 0


: recurse ( n -- n ) 1 + recurse ;

0 recurse


using Printf, Nettle

function find_duplicates(path::String, minsize::Int = 0)
    filesdict = Dict{String,Array{NamedTuple}}()

    for (root, dirs, files) in walkdir(path), fn in files
        filepath = joinpath(root, fn)
        filestats = stat(filepath)

        filestats.size > minsize || continue

        hash = open(f -> hexdigest("md5", read(f)), filepath)

        if haskey(filesdict, hash)
            push!(filesdict[hash], (path = filepath, stats = filestats))
        else
            filesdict[hash] = [(path = filepath, stats = filestats)]
        end
    end

    # Get duplicates
    dups = [tups for tups in values(filesdict) if length(tups) > 1]

    return dups

end

function main()
    path = "."
    println("Finding duplicates in \"$path\"")
    dups = find_duplicates(".", 1)

    println("The following group of files have the same size and the same hash:\n")
    println("File name                                       Size   last modified")
    println("="^76)

    for files in sort(dups, by = tups -> tups[1].stats.size, rev = true)
        for (path, stats) in sort(files, by = tup -> tup.path, rev = true)
            @printf("%-44s%8d   %s\n", path, stats.size, Libc.strftime(stats.mtime))
        end
        println()
    end
end

main()


import algorithm
import os
import strformat
import strutils
import tables
import std/sha1
import times

type

  # Mapping "size" -> "list of paths".
  PathsFromSizes = Table[BiggestInt, seq[string]]

  # Mapping "hash" -> "list fo paths".
  PathsFromHashes = Table[string, seq[string]]

  # Information data.
  Info = tuple[size: BiggestInt; paths: seq[string]]

#---------------------------------------------------------------------------------------------------

proc processCmdLine(): tuple[dirpath: string; minsize: Natural] =
  ## Process the command line. Extra parameters are ignored.

  if paramCount() == 0:
    quit fmt"Usage: {getAppFileName().splitPath()[1]} folder minsize"

  result.dirpath = paramStr(1)
  if not result.dirpath.dirExists():
    quit fmt"Wrong directory path: {result.dirpath}"

  if paramCount() >= 2:
    try:
      result.minsize = parseInt(paramStr(2))
    except ValueError:
      quit fmt"Wrong minimum size: {paramStr(2)}"

#---------------------------------------------------------------------------------------------------

proc initPathsFromSize(dirpath: string; minsize: Natural): PathsFromSizes =
  ## Retrieve the files in directory "dirpath" with minimal size "minsize"
  ## and build the mapping from size to paths.

  for path in dirpath.walkDirRec():
    if not path.fileExists():
      continue    # Not a regular file.
    let size = path.getFileSize()
    if size >= minSize:
      # Store path in "size to paths" table.
      result.mgetOrPut(size, @[]).add(path)

#---------------------------------------------------------------------------------------------------

proc initPathsFromHashes(pathsFromSizes: PathsFromSizes): PathsFromHashes =
  ## Compute hashes for files whose size is not unique and build the mapping
  ## from hash to paths.

  for size, paths in pathsFromSizes.pairs:
    if paths.len > 1:
      for path in paths:
        # Store path in "digest to paths" table.
        result.mgetOrPut($path.secureHashFile(), @[]).add(path)

#---------------------------------------------------------------------------------------------------

proc cmp(x, y: Info): int =
  ## Compare two information tuples. Used to sort the list of duplicates files.

  result = cmp(x.size, y.size)
  if result == 0:
    # Same size. Compare the first paths (we are sure that they are different).
    result = cmp(x.paths[0], y.paths[0])

#---------------------------------------------------------------------------------------------------

proc displayDuplicates(dirpath: string; pathsFromHashes: PathsFromHashes) =
  ## Display duplicates files in directory "dirpath".

  echo "Files with same size and same SHA1 hash value in directory: ", dirpath
  echo ""

  # Build list of duplicates.
  var duplicates: seq[Info]
  for paths in pathsFromHashes.values:
    if paths.len > 1:
      duplicates.add((paths[0].getFileSize(), sorted(paths)))
  if duplicates.len == 0:
    echo "No files"
    return
  duplicates.sort(cmp, Descending)

  # Display duplicates.
  echo fmt"""{"Size":>10}     {"Last date modified":^19}   {"Inode":>8}    HL    File name"""
  echo repeat('=', 80)
  for (size, paths) in duplicates:
    echo ""
    for path in paths:
      let mtime = path.getLastModificationTime().format("YYYY-MM-dd HH:mm:ss")
      let info = path.getFileInfo()
      let inode = info.id.file
      let hardlink = if info.linkCount == 1: " " else: "*"
      echo fmt"{size:>10} {mtime:>23} {inode:>12}  {hardlink:<5} {path.relativePath(dirpath)}"

#———————————————————————————————————————————————————————————————————————————————————————————————————

let (dirpath, minsize) = processCmdLine()
let pathsFromSizes = initPathsFromSize(dirpath, minsize)
let pathsFromHashes = initPathsFromHashes(pathsFromSizes)
dirpath.displayDuplicates(pathsFromHashes)


use System.IO.File;
use System.Time;
use Collection;

class Duplicate {
  function : Main(args : String[]) ~ Nil {
    if(args->Size() = 2) {
      file_sets := SortDups(GetDups(args[0], args[1]->ToInt()));
      each(i : file_sets) {
        file_set := file_sets->Get(i)->As(Vector);
        if(file_set->Size() > 1) {
          "Duplicates:"->PrintLine();
          "----"->PrintLine();
          each(j : file_set) {
            file_set->Get(j)->As(FileMeta)->ToString()->PrintLine();
          };
        };
        '\n'->Print();
      };
    };
  }

  function : SortDups(unsorted : Vector) ~ Vector {
    sorted := IntMap->New();

    each(i : unsorted) {
      value := unsorted->Get(i)->As(Vector);
      key := value->Get(0)->As(FileMeta)->GetSize();
      sorted->Insert(key, value);
    };

    return sorted->GetValues();
  }

  function : GetDups(dir : String, size : Int) ~ Vector {
    duplicates := StringMap->New();

    files := Directory->List(dir);
    each(i : files) {
      file_name := String->New(dir);
      file_name += '/';
      file_name += files[i];

      file_size := File->Size(file_name);
      if(file_size >= size) {
        file_date := File->ModifiedTime(file_name);
        file_hash := file_size->ToString();
        file_hash += ':';
        file_hash += Encryption.Hash->MD5(FileReader->ReadBinaryFile(file_name))->ToString();
        file_meta := FileMeta->New(file_name, file_size, file_date, file_hash);

        file_set := duplicates->Find(file_hash)->As(Vector);
        if(file_set = Nil) {
          file_set := Vector->New();
          duplicates->Insert(file_hash, file_set);
        };
        file_set->AddBack(file_meta);
      };
    };

    return duplicates->GetValues();
  }
}

class FileMeta {
  @name : String;
  @size : Int;
  @date : Date;
  @hash : String;

  New(name : String, size : Int, date : Date, hash : String) {
    @name := name;
    @size := size;
    @date := date;
    @hash := hash;
  }

  method : public : GetSize() ~ Int {
    return @size;
  }

  method : public : ToString() ~ String {
    date_str := @date->ToShortString();
    return "{[email protected]}, {[email protected]}, {$date_str}";
  }
}


100 each 1 + as n
  ''
  n 3 mod 0 = if 'Fizz' cat
  n 5 mod 0 = if 'Buzz' cat
  dup empty if drop n
  say


BEGIN

% CALCULATE P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
   MOD := P - Q * (P / Q);
END;

COMMENT
  RETURN DAY OF WEEK (SUN=0, MON=1, ETC.) FOR A GIVEN
  GREGORIAN CALENDAR DATE USING ZELLER'S CONGRUENCE;
INTEGER FUNCTION DAYOFWEEK(MO, DA, YR);
INTEGER MO, DA, YR;
BEGIN
  INTEGER Y, C, Z;
  IF MO < 3 THEN
    BEGIN
      MO := MO + 10;
      YR := YR - 1;
    END
  ELSE MO := MO - 2;
  Y := MOD(YR, 100);
  C := YR / 100;
  Z := (26 * MO - 2) / 10;
  Z := Z + DA + Y + (Y / 4) + (C / 4) - 2 * C + 777;
  DAYOFWEEK := MOD(Z, 7);
END;

% RETURN 1 IF Y IS A LEAP YEAR, OTHERWISE 0 %
INTEGER FUNCTION ISLEAPYR(Y);
INTEGER Y;
BEGIN
  IF MOD(Y,4) <> 0 THEN  % QUICK EXIT IN MOST COMMON CASE %
    ISLEAPYR := 0
  ELSE IF MOD(Y,400) = 0 THEN
    ISLEAPYR := 1
  ELSE IF MOD(Y,100) = 0 THEN
    ISLEAPYR := 0
  ELSE                   % NON-CENTURY AND DIVISIBLE BY 4 %
    ISLEAPYR := 1;
END;

% RETURN THE NUMBER OF DAYS IN THE SPECIFIED MONTH %
INTEGER FUNCTION MONTHDAYS(MO, YR);
INTEGER MO, YR;
BEGIN
  IF MO = 2 THEN
    BEGIN
      IF ISLEAPYR(YR) = 1 THEN
        MONTHDAYS := 29
      ELSE
        MONTHDAYS := 28;
    END
  ELSE IF (MO = 4) OR (MO = 6) OR (MO = 9) OR (MO = 11) THEN
    MONTHDAYS := 30
  ELSE
    MONTHDAYS := 31;
END;

COMMENT
  RETURN THE DAY OF THE MONTH CORRESPONDING TO LAST OCCURRENCE
  OF WEEKDAY K (SUN=0, MON=1, ETC.) FOR A GIVEN MONTH AND YEAR;
INTEGER FUNCTION LASTKDAY(K, M, Y);
INTEGER K, M, Y;
BEGIN
  INTEGER D, W;
  % DETERMINE WEEKDAY FOR THE LAST DAY OF THE MONTH %
  D := MONTHDAYS(M, Y);
  W := DAYOFWEEK(M, D, Y);
  % BACK UP AS NEEDED TO DESIRED WEEKDAY %
  IF W >= K THEN
    D := D - (W - K)
  ELSE
    D := D - (7 - K - W);
  LASTKDAY := D;
END;

STRING FUNCTION MONTHNAME(N);
INTEGER N;
BEGIN
  CASE (N - 1) OF
    BEGIN
      MONTHNAME := "JAN";
      MONTHNAME := "FEB";
      MONTHNAME := "MAR";
      MONTHNAME := "APR";
      MONTHNAME := "MAY";
      MONTHNAME := "JUN";
      MONTHNAME := "JUL";
      MONTHNAME := "AUG";
      MONTHNAME := "SEP";
      MONTHNAME := "OCT";
      MONTHNAME := "NOV";
      MONTHNAME := "DEC";
    END;
END;

% EXERCISE THE ROUTINE %
INTEGER M, Y, SUNDAY;
SUNDAY := 0;
WRITE("DISPLAY LAST SUNDAYS FOR WHAT YEAR?");
READ(Y);
FOR M:=1 STEP 1 UNTIL 12 DO
  WRITE(MONTHNAME(M), LASTKDAY(SUNDAY,M,Y));

END


begin % find the last Sunday in each month of a year             %
    % returns true if year is a leap year, false otherwise       %
    % assumes year is in the Gregorian Calendar                  %
    logical procedure isLeapYear ( integer value year ) ;
        year rem 400 = 0 or ( year rem 4 = 0 and year rem 100 not = 0 );
    % returns the day of the week of the specified date (d/m/y)  %
    %         Sunday = 1                                         %
    integer procedure Day_of_week ( integer value d, m, y );
        begin
            integer j, k, mm, yy;
            mm := m;
            yy := y;
            if mm <= 2 then begin
                mm := mm + 12;
                yy := yy - 1;
            end if_m_le_2;
            j := yy div 100;
            k := yy rem 100;
            (d + ( ( mm + 1 ) * 26 ) div 10 + k + k div 4 + j div 4 + 5 * j ) rem 7
        end Day_of_week;
    % sets the elements of last to the day of the last Sunday   %
    % of each month in year                                     %
    procedure lastSundays ( integer value year
                          ; integer array last ( * )
                          ) ;
        begin
            integer array lastDays ( 1 :: 12 );
            integer m;
            % set ld to the day number od the last day of each  %
            % month in year                                     %
            m := 1;
            for ld := 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 do begin
                lastDays( m ) := ld;
                m             := m + 1
            end for_ld ;
            if isLeapYear( year ) then lastDays( 2 ) := 29;
            % for each month, determine the day number of the   %
            % last Sunday                                       %
            for mPos := 1 until 12 do begin
                integer dow;
                dow := Day_of_week( lastDays( mPos ), mPos, year );
                if dow = 0 % Saturday % then dow := 7;
                % calculate the offset for the previous Sunday  %
                last( mPos ) := ( lastDays( mPos ) + 1 ) - dow
            end for_mPos
        end lastSundays ;
    begin
        % test the lastSundays procedure                        %
        integer array last ( 1 :: 12 );
        integer year;
        year := 2020;
        lastSundays( year, last );
        i_w := 1; s_w := 0; % output formatting                 %
        for mPos := 1 until 12 do write( year, if mPos < 10 then "-0" else "-1", mPos rem 10, "-", last( mPos ) )
    end
end.


-- LAST SUNDAYS OF YEAR ------------------------------------------------------

--  lastSundaysOfYear :: Int -> [Date]
on lastSundaysOfYear(y)

    -- lastWeekDaysOfYear :: Int -> Int -> [Date]
    script lastWeekDaysOfYear
        on |λ|(intYear, iWeekday)

            -- lastWeekDay :: Int -> Int -> Date
            script lastWeekDay
                on |λ|(iLastDay, iMonth)
                    set iYear to intYear

                    calendarDate(iYear, iMonth, iLastDay - ¬
                        (((weekday of calendarDate(iYear, iMonth, iLastDay)) as integer) + ¬
                            (7 - (iWeekday))) mod 7)
                end |λ|
            end script

            map(lastWeekDay, lastDaysOfMonths(intYear))
        end |λ|

        -- isLeapYear :: Int -> Bool
        on isLeapYear(y)
            (0 = y mod 4) and (0 ≠ y mod 100) or (0 = y mod 400)
        end isLeapYear

        -- lastDaysOfMonths :: Int -> [Int]
        on lastDaysOfMonths(y)
            {31, cond(isLeapYear(y), 29, 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
        end lastDaysOfMonths
    end script

    lastWeekDaysOfYear's |λ|(y, Sunday as integer)
end lastSundaysOfYear

-- TEST ----------------------------------------------------------------------
on run argv

    intercalate(linefeed, ¬
        map(isoRow, ¬
            transpose(map(lastSundaysOfYear, ¬
                apply(cond(class of argv is list and argv ≠ {}, ¬
                    singleYearOrRange, fiveCurrentYears), argIntegers(argv))))))

end run

-- ARGUMENT HANDLING ---------------------------------------------------------

-- Up to two optional command line arguments: [yearFrom], [yearTo]
-- (Default range in absence of arguments: from two years ago, to two years ahead)

-- ~ $ osascript ~/Desktop/lastSundays.scpt
-- ~ $ osascript ~/Desktop/lastSundays.scpt 2013
-- ~ $ osascript ~/Desktop/lastSundays.scpt 2013 2016

-- singleYearOrRange :: [Int] -> [Int]
on singleYearOrRange(argv)
    apply(cond(length of argv > 0, my range, my fiveCurrentYears), argv)
end singleYearOrRange

-- fiveCurrentYears :: () -> [Int]
on fiveCurrentYears(_)
    set intThisYear to year of (current date)
    enumFromTo(intThisYear - 2, intThisYear + 2)
end fiveCurrentYears

-- argIntegers :: maybe [String] -> [Int]
on argIntegers(argv)
    if class of argv is list and argv ≠ {} then
        {map(my parseInt, argv)}
    else
        {}
    end if
end argIntegers

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- apply (a -> b) -> a -> b
on apply(f, a)
    mReturn(f)'s |λ|(a)
end apply

-- calendarDate :: Int -> Int -> Int -> Date
on calendarDate(intYear, intMonth, intDay)
    tell (current date)
        set {its year, its month, its day, its time} to ¬
            {intYear, intMonth, intDay, 0}
        return it
    end tell
end calendarDate

-- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b)
on cond(bool, f, g)
    if bool then
        f
    else
        g
    end if
end cond

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m > n then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end enumFromTo

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- isoDateString :: Date -> String
on isoDateString(dte)
    (((year of dte) as string) & ¬
        "-" & text items -2 thru -1 of ¬
        ("0" & ((month of dte) as integer) as string)) & ¬
        "-" & text items -2 thru -1 of ¬
        ("0" & day of dte)
end isoDateString

-- isoRow :: [Date] -> String
on isoRow(lstDate)
    intercalate(tab, map(my isoDateString, lstDate))
end isoRow

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- parseInt :: String -> Int
on parseInt(s)
    s as integer
end parseInt

-- transpose :: [[a]] -> [[a]]
on transpose(xss)
    script column
        on |λ|(_, iCol)
            script row
                on |λ|(xs)
                    item iCol of xs
                end |λ|
            end script

            map(row, xss)
        end |λ|
    end script

    map(column, item 1 of xss)
end transpose


LargestLeftTruncatablePrimeInBase[n_] :=
 Max[NestWhile[{Select[
       [email protected][Function[{a, b}, #[[2]] a + b],
         Range[1, n - 1], #[[1]]], PrimeQ], n #[[2]]} &, {{0},
     1}, #[[1]] != {} &, 1, Infinity, -1][[1]]]


import bignum, strformat

const

  Primes = [2, 3, 5, 7, 11, 13, 17]
  Digits = "0123456789abcdefghijklmnopqrstuvwxyz"

#---------------------------------------------------------------------------------------------------

func isProbablyPrime(n: Int): bool =
  ## Return true if "n" is not definitively composite.
  probablyPrime(n, 25) != 0

#---------------------------------------------------------------------------------------------------

func maxLeftTruncablePrime(base: int): Int =
  ## Return the maximum left truncable prime for given base.

  let base = base.int32
  var primes: seq[Int]

  # Initialize primes with one digit in given base.
  for p in Primes:
    if p < base:
      primes.add(newInt(p))
    else:
      break

  # Build prime list with one more digit per generation.
  var next: seq[Int]
  while true:

    # Build the next generation (with one more digit).
    for p in primes:
      var pstr = ' ' & `$`(p, base)   # ' ' as a placeholder for next digit.
      for i in 1..<base:
        pstr[0] = Digits[i]
        let n = newInt(pstr, base)
        if n.isProbablyPrime():
          next.add(n)

    if next.len == 0:
      # No primes with this number of digits.
      # Return the greatest prime in previous generation.
      return max(primes)

    # Prepare to build next generation.
    primes = next
    next.setLen(0)

#———————————————————————————————————————————————————————————————————————————————————————————————————

echo "Base    Greatest left truncable prime"
echo "====================================="
for base in 3..17:
  let m = maxLeftTruncablePrime(base)
  echo &"{base:>3}     {m}", if base > 10: " (" & `$`(m, base.int32) & ')' else: ""


a(n)=my(v=primes(primepi(n-1)),u,t,b=1,best); while(#v, best=vecmax(v); b*=n; u=List(); for(i=1,#v,for(k=1,n-1,if(isprime(t=v[i]+k*b), listput(u,t)))); v=Vec(u)); best


use ntheory qw/:all/;
use Math::GMPz;

sub lltp {
  my($n, $b, $best) = (shift, Math::GMPz->new(1));
  my @v = map { Math::GMPz->new($_) } @{primes($n-1)};
  while (@v) {
    $best = vecmax(@v);
    $b *= $n;
    my @u;
    foreach my $vi (@v) {
      push @u, grep { is_prob_prime($_) } map { $vi + $_*$b } 1 .. $n-1;
    }
    @v = @u;
  }
  die unless is_provable_prime($best);
  $best;
}

printf "%2d %s\n", $_, lltp($_)  for 3 .. 17;


: munge ( n -- n' ) 1+ recurse ;

: test   0 ['] munge catch if ." Recursion limit at depth " . then ;

test   \ Default gforth: Recursion limit at depth 3817


program recursion_depth

  implicit none

  call recurse (1)

contains

  recursive subroutine recurse (i)

    implicit none
    integer, intent (in) :: i

    write (*, '(i0)') i
    call recurse (i + 1)

  end subroutine recurse

end program recursion_depth


f := function(n)
  return f(n+1);
end;

# Now loop until an error occurs
f(0);

# Error message :
#   Entering break read-eval-print loop ...
#   you can 'quit;' to quit to outer loop, or
#   you may 'return;' to continue

n;
# 4998

# quit "brk mode" and return to GAP
quit;


# Put this in a file foo.gnuplot and run as
#     gnuplot foo.gnuplot

# probe by 1 up to 1000, then by 1% increases
if (! exists("try")) { try=0 }
try=(try<1000 ? try+1 : try*1.01)

recurse(n) = (n > 0 ? recurse(n-1) : 'ok')
print "try recurse ", try
print recurse(try)
reread


use File::Find qw(find);
use File::Compare qw(compare);
use Sort::Naturally;
use Getopt::Std qw(getopts);

my %opts;
$opts{s} = 1;
getopts("s:", \%opts);

sub find_dups {
    my($dir) = @_;

    my @results;
    my %files;
    find {
        no_chdir => 1,
        wanted => sub { lstat; -f _ && (-s >= $opt{s} ) && push @{$files{-s _}}, $_ }
    } => $dir;

    foreach my $files (values %files) {
        next unless @$files;

        my %dups;
        foreach my $a (0 .. @$files - 1) {
            for (my $b = $a + 1 ; $b < @$files ; $b++) {
                next if compare(@$files[$a], @$files[$b]);
                push @{$dups{ @$files[$a] }}, splice @$files, $b--, 1;
            }
        }

        while (my ($original, $clones) = each %dups) {
            push @results, sprintf "%8d %s\n", (stat($original))[7], join ', ', sort $original, @$clones;
        }
    }
    reverse nsort @results;

}

print for find_dups(@ARGV);


without js -- file i/o
integer min_size=1
sequence res = {}
atom t1 = time()+1

function store_res(string filepath, sequence dir_entry)
    if not match("backup",filepath) -- (example filter)
    and not find('d', dir_entry[D_ATTRIBUTES]) then
        atom size = dir_entry[D_SIZE]
        if size>=min_size then
            res = append(res,{size,filepath,dir_entry})
            if time()>t1 then
                printf(1,"%d files found\r",length(res))
                t1 = time()+1
            end if
        end if
    end if
    return 0 -- keep going
end function
integer exit_code = walk_dir("demo\\clocks\\love", store_res, true)

res = sort(res,DESCENDING)
printf(1,"%d files found\n",length(res))

integer duplicates = 0
for i=1 to length(res)-1 do
    for j=i+1 to length(res) do
        if res[i][1]!=res[j][1] then exit end if
        string si = join_path({res[i][2],res[i][3][D_NAME]}),
               sj = join_path({res[j][2],res[j][3][D_NAME]})
        integer fni = open(si,"rb"),
                fnj = open(sj,"rb"),
                size = res[i][1]
        bool same = true
        if fni=-1 or fnj=-1 then ?9/0 end if
        for k=1 to size+1 do    -- (check eof as well)
            if getc(fni)!=getc(fnj) then
                same = false
                exit
            end if
        end for
        close(fni)
        close(fnj)
        if same then
            -- prettifying the output left as an exercise...
            ?res[i]
            ?res[j]
            duplicates += 1
        end if
    end for
    if time()>t1 then
        printf(1,"processing %d/%d...\r",{i,length(res)})
        t1 = time()+1
    end if
end for
printf(1,"%d duplicates found\n",duplicates)


let fizzbuzz i =>
  switch (i mod 3, i mod 5) {
  | (0, 0) => "FizzBuzz"
  | (0, _) => "Fizz"
  | (_, 0) => "Buzz"
  | _ => string_of_int i
  };

for i in 1 to 100 {
  print_endline (fizzbuzz i)
};


lastSundayForMonth: function [m,y][
    ensure -> in? m 1..12

    daysOfMonth: @[0 31 (leap? y)? -> 28 -> 27 31 30 31 30 31 31 30 31 30 31]
    loop range get daysOfMonth m 1 [d][
        dt: to :date.format:"yyyy-M-dd" ~"|y|-|m|-|d|"
        if dt\Day = "Sunday" -> return dt
    ]
]

getLastSundays: function [year][
    loop 1..12 'month [
        print to :string.format:"yyyy-MM-dd" lastSundayForMonth month year
    ]
]

getLastSundays 2013


InputBox, Year, , Enter a year., , 300, 135
Date := Year . "0101"

while SubStr(Date, 1, 4) = Year {
    FormatTime, WD, % Date, WDay
    if (WD = 1)
        MM := LTrim(SubStr(Date, 5, 2), "0"), Day%MM% := SubStr(Date, 7, 2)
    Date += 1, Days
}

Gui, Font, S10, Courier New
Gui, Add, Text, , % "Last Sundays of " Year ":`n---------------------"

Loop, 12 {
    FormatTime, Month, % Year (A_Index > 9 ? "" : "0") A_Index, MMMM
    Gui, Add, Text, y+1, % Month (StrLen(Month) > 7 ? "" : "`t") "`t" Day%A_Index%
}

Gui, Show
return


with javascript_semantics
include mpfr.e
sequence tens = mpz_inits(1,1),
         vals = mpz_inits(1),
         digits = {0}
mpz answer = mpz_init(0)
integer base, seen_depth

procedure add_digit(integer i)
    atom t1 = time()+1
    if i>length(vals) then
        vals &= mpz_init_set(vals[i-1])
        tens &= mpz_init_set(tens[i-1])
        mpz_mul_si(tens[i],tens[i],base)
        digits &= 0
    end if
    for d=1 to base-1 do
        digits[i] = d
        mpz_set(vals[i], vals[i-1])
        mpz_addmul_ui(vals[i], tens[i], d)
        if mpz_prime(vals[i]) then
            if i>seen_depth
            or (i==seen_depth and mpz_cmp(vals[i], answer)>0) then
                mpz_set(answer, vals[i])
                seen_depth = i
            end if
            add_digit(i+1)
        end if
        if time()>t1 and platform()!=JS then
            printf(1,"    base %d: (%d) %v   \r", {base, seen_depth, digits[1..i]})
        end if
    end for
end procedure

procedure do_base()
    atom t0 = time()
    seen_depth = 0
    mpz_set_si(answer, 0)
    mpz_set_si(tens[1], 1)
    for i=2 to length(tens) do
        mpz_mul_si(tens[i], tens[i-1], base)
    end for
    for i=1 to base do
        integer pi = get_prime(i)
        if pi>=base then exit end if
        mpz_set_si(vals[1], pi)
        digits[1] = pi
        add_digit(2)
    end for
    string rd = mpz_get_str(answer),
           rb = mpz_get_str(answer,base)
    t0 = time()-t0
    string t = iff(t0>0.1?" ["&elapsed(t0)&"]":"")
    printf(1,"%3d %-41s (%s, %d digits)%s\n", {base,rd,rb,length(rb),t})
end procedure

atom t0 = time()
for b=3 to 31 do
    if (platform()!=JS or not find(b,{12,14,16,21,25,27,31}))
    and (b<=17 or remainder(b,2)=1) then
        base = b
        do_base()
    end if
end for
?elapsed(time()-t0)


package main

import (
	"flag"
	"fmt"
	"runtime/debug"
)

func main() {
	stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
	flag.Parse()
	if *stack > 0 {
		debug.SetMaxStack(*stack)
	}
	r(1)
}

func r(l int) {
	if l%1000 == 0 {
		fmt.Println(l)
	}
	r(l + 1)
}


`Recurse'
{
    show .depth.
    .depth. = {rpn .depth. 1 +}
    Recurse
}
.depth. = 1
Recurse


def recurse;
recurse = {
    try {
        recurse (it + 1)
    } catch (StackOverflowError e) {
        return it
    }
}

recurse(0)


import Debug.Trace (trace)

recurse :: Int -> Int
recurse n = trace (show n) recurse (succ n)

main :: IO ()
main = print $ recurse 1


`(== 64 64)
(de mmap (L F)
   (native "@" "mmap" 'N 0 L 1 2 F 0) )
(de munmap (A L)
   (native "@" "munmap" 'N A L) )
(de xxh64 (M S)
   (let
      (R (native "libxxhash.so" "XXH64" 'N M S 0)
         P `(** 2 64) )
      (if (lt0 R)
         (& (+ R P) (dec P))
         R ) ) )
(de walk (Dir)
   (recur (Dir)
      (for F (dir Dir)
         (let (Path (pack Dir "/" F)  Info (info Path T))
            (when (car Info)
               (if (=T (car Info))
                  (recurse Path)
                  (if (lup D (car Info))
                     (push (cdr @) Path)
                     (idx 'D (list (car Info) (cons Path)) T) ) ) ) ) ) ) )
(off D)
(walk "/bin")
(for Lst (filter cdadr (idx 'D))
   (let L
      (by
         '((F)
            (let (M (mmap (car Lst) (open F T))
               S (car Lst) )
               (prog1 (xxh64 M S) (munmap M S)) ) )
         group
         (cadr Lst) )
      (and (filter cdr L) (println (car Lst) @)) ) )


from __future__ import print_function
import os
import hashlib
import datetime

def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
    knownFiles = {}

    #Analyse files
    for root, dirs, files in os.walk(pth):
        for fina in files:
            fullFina = os.path.join(root, fina)
            isSymLink = os.path.islink(fullFina)
            if isSymLink:
                continue # Skip symlinks
            si = os.path.getsize(fullFina)
            if si < minSize:
                continue
            if si not in knownFiles:
                knownFiles[si] = {}
            h = hashlib.new(hashName)
            h.update(open(fullFina, "rb").read())
            hashed = h.digest()
            if hashed in knownFiles[si]:
                fileRec = knownFiles[si][hashed]
                fileRec.append(fullFina)
            else:
                knownFiles[si][hashed] = [fullFina]

    #Print result
    sizeList = list(knownFiles.keys())
    sizeList.sort(reverse=True)
    for si in sizeList:
        filesAtThisSize = knownFiles[si]
        for hashVal in filesAtThisSize:
            if len(filesAtThisSize[hashVal]) < 2:
                continue
            fullFinaLi = filesAtThisSize[hashVal]
            print ("=======Duplicate=======")
            for fullFina in fullFinaLi:
                st = os.stat(fullFina)
                isHardLink = st.st_nlink > 1
                infoStr = []
                if isHardLink:
                    infoStr.append("(Hard linked)")
                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
                print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr))

if __name__=="__main__":

    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)


# syntax: GAWK -f FIND_THE_LAST_SUNDAY_OF_EACH_MONTH.AWK [year]
BEGIN {
    split("31,28,31,30,31,30,31,31,30,31,30,31",daynum_array,",") # days per month in non leap year
    year = (ARGV[1] == "") ? strftime("%Y") : ARGV[1]
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
      daynum_array[2] = 29
    }
    for (m=1; m<=12; m++) {
      for (d=daynum_array[m]; d>=1; d--) {
        if (strftime("%a",mktime(sprintf("%d %d %d 0 0 0",year,m,d))) == "Sun") {
          printf("%04d-%02d-%02d\n",year,m,d)
          break
        }
      }
    }
    exit(0)
}


@echo off
setlocal enabledelayedexpansion
set /p yr= Enter year:
echo.
call:monthdays %yr% list
set mm=1
for %%i in (!list!) do (
  call:calcdow !yr! !mm! %%i dow
  set/a lsu=%%i-dow
  set mf=0!mm!
  echo !yr!-!mf:~-2!-!lsu!
  set /a mm+=1
)
pause
exit /b

:monthdays yr &list
setlocal
call:isleap %1 ly
for /L %%i in (1,1,12) do (
  set /a "nn = 30 + ^!(((%%i & 9) + 6) %% 7) + ^!(%%i ^^ 2) * (ly - 2)
  set list=!list! !nn!
)
endlocal & set %2=%list%
exit /b

:calcdow yr mt dy &dow  :: 0=sunday
setlocal
set/a a=(14-%2)/12,yr=%1-a,m=%2+12*a-2,"dow=(%3+yr+yr/4-yr/100+yr/400+31*m/12)%%7"
endlocal & set %~4=%dow%
exit /b

:isleap yr &leap  :: remove ^ if not delayed expansion
set /a "%2=^!(%1%%4)+(^!^!(%1%%100)-^!^!(%1%%400))"
exit /b


import random

def is_probable_prime(n,k):
    #this uses the miller-rabin primality test found from rosetta code
    if n==0 or n==1:
        return False
    if n==2:
        return True
    if n % 2 == 0:
        return False
    s = 0
    d = n-1

    while True:
        quotient, remainder = divmod(d, 2)
        if remainder == 1:
            break
        s += 1
        d = quotient

    def try_composite(a):
        if pow(a, d, n) == 1:
            return False
        for i in range(s):
            if pow(a, 2**i * d, n) == n-1:
                return False
        return True # n is definitely composite

    for i in range(k):
        a = random.randrange(2, n)
        if try_composite(a):
            return False

    return True # no base tested showed n as composite

def largest_left_truncatable_prime(base):
    radix = 0
    candidates = [0]
    while True:
        new_candidates=[]
        multiplier = base**radix
        for i in range(1,base):
            new_candidates += [x+i*multiplier for x in candidates if is_probable_prime(x+i*multiplier,30)]
        if len(new_candidates)==0:
            return max(candidates)
        candidates = new_candidates
        radix += 1

for b in range(3,24):
    print("%d:%d\n" % (b,largest_left_truncatable_prime(b)))


use ntheory:from<Perl5> <is_prime>;

for 3 .. 11 -> $base {
    say "Starting base $base...";
    my @stems = grep { .is-prime }, ^$base;
    for 1 .. * -> $digits {
        print ' ', @stems.elems;
        my @new;
        my $place = $base ** $digits;
        for 1 ..^ $base -> $digit {
            my $left = $digit * $place;
            @new.append: (@stems »+» $left).grep: { is_prime("$_") }
        }
        last unless [email protected]new;
        @stems = @new;
    }
    say "\nLargest ltp in base $base = {@stems.max} or :$base\<@stems.max.base($base)}>\n";
}


fun rec n
  println n
  rec (n + 1)
endfun

rec 1


U0 Recurse(U64 i) {
  Print("%d\n", i);
  Recurse(i + 1);
}

Recurse(0);


function test(counter) {
	print(counter)
	test(counter+1)
}

software {
	test(0)
}


procedure main()
envar := "MSTKSIZE"
write(&errout,"Program to test recursion depth - dependant on the environment variable ",envar," = ",\getenv(envar)|&null)
deepdive()
end

procedure deepdive()
static d
initial d := 0
write( d +:= 1)
deepdive()
end


Home is a room.

When play begins: recurse 0.

To recurse (N - number):
	say "[N].";
	recurse N + 1.


#lang racket

(struct F (name id size [links #:mutable]))

(require openssl/sha1)
(define (find-duplicate-files path size)
  (define Fs
    (sort
     (fold-files
      (λ(path type acc)
        (define s (and (eq? 'file type) (file-size path)))
        (define i (and s (<= size s) (file-or-directory-identity path)))
        (define ln (and i (findf (λ(x) (equal? i (F-id x))) acc)))
        (when ln (set-F-links! ln (cons (path->string path) (F-links ln))))
        (if (and i (not ln)) (cons (F path i s '()) acc) acc))
      '() path #f)
     > #:key F-size))
  (define (find-duplicates Fs)
    (define t (make-hash))
    (for ([F Fs])
      (define cksum (call-with-input-file (F-name F) sha1))
      (hash-set! t cksum (cons F (hash-ref t cksum '()))))
    (for/list ([(n Fs) (in-hash t)] #:unless (null? (cdr Fs))) Fs))
  (let loop ([Fs Fs])
    (if (null? Fs) '()
        (let-values ([(Fs Rs)
                      (splitf-at Fs (λ(F) (= (F-size F) (F-size (car Fs)))))])
          (append (find-duplicates Fs)
                  (loop Rs))))))

(define (show-duplicates path size)
  (for ([Fs (find-duplicate-files path size)])
    (define (links F)
      (if (null? (F-links F)) ""
          (format " also linked at ~a" (string-join (F-links F) ", "))))
    (printf "~a (~a)~a\n" (F-name (car Fs)) (F-size (car Fs)) (links (car Fs)))
    (for ([F (cdr Fs)]) (printf "  ~a~a\n" (F-name F) (links F)))))

(show-duplicates (find-system-path 'home-dir) 1024)


use Digest::SHA256::Native;

sub MAIN( $dir = '.', :$minsize = 5, :$recurse = True ) {
    my %files;
    my @dirs = $dir.IO.absolute.IO;
    while @dirs {
        my @files = @dirs.pop;
        while @files {
            for @files.pop.dir -> $path {
                %files{ $path.s }.push: $path if $path.f and $path.s >= $minsize;
                @dirs.push: $path if $path.d and $path.r and $recurse
            }
        }
    }

    for %files.sort( +*.key ).grep( *.value.elems > 1)».kv -> ($size, @list) {
        my %dups;
        @list.map: { %dups{ sha256( $_.slurp :bin ) }.push: $_.Str };
        for %dups.grep( *.value.elems > 1)».value -> @dups {
            say sprintf("%9s : ", scale $size ),  @dups.join(', ');
        }
    }
}

sub scale ($bytes) {
    given $bytes {
        when $_ < 2**10 {  $bytes                    ~ ' B'  }
        when $_ < 2**20 { ($bytes / 2**10).round(.1) ~ ' KB' }
        when $_ < 2**30 { ($bytes / 2**20).round(.1) ~ ' MB' }
        default         { ($bytes / 2**30).round(.1) ~ ' GB' }
    }
}


rebol [
	Title: "FizzBuzz"
	URL: http://rosettacode.org/wiki/FizzBuzz
]

; Concatenative. Note use of 'case/all' construct to evaluate all
; conditions. I use 'copy' to allocate a new string each time through
; the loop -- otherwise 'x' would get very long...

repeat i 100 [
	x: copy ""
	case/all [
		0 = mod i 3 [append x "Fizz"]
		0 = mod i 5 [append x "Buzz"]
		"" = x      [x: mold i]
	]
	print x
]


INSTALL @lib$+"DATELIB"

INPUT "What year to calculate (YYYY)? " Year%

PRINT '"Last Sundays in ";Year%;" are on:"
FOR Month%=1 TO 12
  PRINT Year% "-" RIGHT$("0"+STR$Month%,2) "-";FN_dim(Month%,Year%)-FN_dow(FN_mjd(FN_dim(Month%,Year%),Month%,Year%))
NEXT
END


# Compute the largest left truncatable prime
#
#  Nigel_Galloway
#  September 15th., 2012.
#
require 'prime'
BASE = 3
MAX = 500
stems = Prime.each(BASE-1).to_a
(1..MAX-1).each {|i|
  print "#{stems.length} "
  t = []
  b = BASE ** i
  stems.each {|z|
    (1..BASE-1).each {|n|
      c = n*b+z
      t.push(c) if c.prime?
  }}
  break if t.empty?
  stems = t
}
puts "The largest left truncatable prime #{"less than #{BASE ** MAX} " if MAX < 500}in base #{BASE} is #{stems.max}"


import scala.collection.parallel.immutable.ParSeq

object LeftTruncatablePrime extends App {
  private def leftTruncatablePrime(maxRadix: Int, millerRabinCertainty: Int) {
    def getLargestLeftTruncatablePrime(radix: Int, millerRabinCertainty: Int): BigInt = {
      def getNextLeftTruncatablePrimes(n: BigInt, radix: Int, millerRabinCertainty: Int) = {
        def baseString = if (n == 0) "" else n.toString(radix)

        for {i <- (1 until radix).par
             p = BigInt(Integer.toString(i, radix) + baseString, radix)
             if p.isProbablePrime(millerRabinCertainty)
        } yield p
      }

      def iter(list: ParSeq[BigInt], lastList: ParSeq[BigInt]): ParSeq[BigInt] = {
        if (list.isEmpty) lastList
        else
          iter((for (n <- list.par) yield getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty)).flatten, list)
      }

      iter(getNextLeftTruncatablePrimes(0, radix, millerRabinCertainty), ParSeq.empty).max
    }

    for (radix <- (3 to maxRadix).par) {
      val largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty)
      println(f"n=$radix%3d: " +
        (if (largest == null) "No left-truncatable prime"
        else f"$largest%35d (in base $radix%3d) ${largest.toString(radix)}"))

    }
  }

  val argu: Array[String] = if (args.length >=2 ) args.slice(0, 2) else Array("17", "100")
  val maxRadix = argu(0).toInt.ensuring(_ > 2, "Radix must be an integer greater than 2.")

  try {
    val millerRabinCertainty = argu(1).toInt

    println(s"Run with maxRadix = $maxRadix and millerRabinCertainty = $millerRabinCertainty")

    leftTruncatablePrime(maxRadix, millerRabinCertainty)
    println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
  }
  catch {
    case _: NumberFormatException => Console.err.println("Miller-Rabin Certainty must be an integer.")
  }

}


(recur=: verb def 'recur smoutput N=:N+1')N=:0


public class RecursionTest {

    private static void recurse(int i) {
        try {
	    recurse(i+1);
	} catch (StackOverflowError e) {
	    System.out.print("Recursion depth on this system is " + i + ".");
	}
    }

    public static void main(String[] args) {
        recurse(0);
    }
}


function recurse(depth)
{
 try
 {
  return recurse(depth + 1);
 }
 catch(ex)
 {
  return depth;
 }
}

var maxRecursion = recurse(1);
document.write("Recursion depth on this system is " + maxRecursion);


def zero_arity:
  if (. % 1000000 == 0) then . else empty end, ((.+1)| zero_arity);

1|zero_arity


/*REXX program to reads a (DOS) directory  and  finds and displays files that identical.*/
sep=center(' files are identical in size and content: ',79,"═")    /*define the header. */
tFID= 'c:\TEMP\FINDDUP.TMP'                      /*use this as a temporary  FileID.     */
arg maxSize aDir                                 /*obtain optional arguments from the CL*/
if maxSize='' | maxSize="," then maxSize=1000000 /*filesize limit (in bytes) [1 million]*/
aDir=strip(aDir)                                 /*remove any leading or trailing blanks*/
if right(aDir,1)\=='\'  then aDir=aDir"\"        /*possibly add a trailing backslash [\]*/
"DIR"  aDir  '/a-d-s-h /oS /s | FIND "/" >' tFID /*the (DOS) DIR output ───► temp file. */
pFN=                                             /*the previous  filename and filesize. */
pSZ=;  do j=0  while lines(tFID)\==0             /*process each of the files in the list*/
       aLine=linein(tFID)                        /*obtain (DOS) DIR's output about a FID*/
       parse var aLine . . sz fn                 /*obtain the filesize and its fileID.  */
       sz=space(translate(sz,,','),0)            /*elide any commas from the size number*/
       if sz>maxSize  then leave                 /*Is the file > maximum?  Ignore file. */
                                                 /* [↓]  files identical?  (1st million)*/
       if sz==pSZ  then  if charin(aDir||pFN,1,sz)==charin(aDir||FN,1,sz)  then do
                                                                                say sep
                                                                                say pLine
                                                                                say aLine
                                                                                say
                                                                                end
       pSZ=sz;      pFN=FN;      pLine=aLine     /*remember the previous stuff for later*/
       end   /*j*/

if lines(tFID)\==0  then 'ERASE' tFID            /*do housecleaning  (delete temp file).*/
                                                 /*stick a fork in it,  we're all done. */


# Project : Find duplicate files

d = "/Windows/System32"
chdir(d)
dir = dir(d)
dirlist = []
for n = 1 to len(dir)
     if dir[n][2] = 0
        str = read(dir[n][1])
        lenstr = len(str)
        add(dirlist,[lenstr,dir[n][1]])
     ok
next
see "Directory : " + d + nl
see "--------------------------------------------" + nl
dirlist = sortfirst(dirlist)
line = 0
for n = 1 to len(dirlist)-1
     if dirlist[n][1] = dirlist[n+1][1]
        see "" + dirlist[n][1] + " " + dirlist[n][2] + nl
        see "" + dirlist[n+1][1] + " " + dirlist[n+1][2] + nl
        if n < len(dirlist)-2 and dirlist[n+1][1] != dirlist[n+2][1]
           line = 1
        ok
     else
        line = 0
     ok
     if line = 1
        see "--------------------------------------------" + nl
     ok
next

func sortfirst(alist)
        for n = 1 to len(alist) - 1
             for m = n + 1 to len(alist)
                  if alist[m][1] < alist[n][1]
                     swap(alist,m,n)
                  ok
                  if alist[m][1] = alist[n][1] and strcmp(alist[m][2],alist[n][2]) < 0
                     swap(alist,m,n)
                  ok
             next
        next
        return alist


require 'digest/md5'

def find_duplicate_files(dir)
  puts "\nDirectory : #{dir}"
  Dir.chdir(dir) do
    file_size = Dir.foreach('.').select{|f| FileTest.file?(f)}.group_by{|f| File.size(f)}
    file_size.each do |size, files|
      next if files.size==1
      files.group_by{|f| Digest::MD5.file(f).to_s}.each do |md5,fs|
        next if fs.size==1
        puts "  --------------------------------------------"
        fs.each{|file| puts "  #{File.mtime(file)}  #{size}  #{file}"}
      end
    end
  end
end

find_duplicate_files("/Windows/System32")


Red ["FizzBuzz"]

repeat i 100 [
    print case [
        i % 15 = 0 ["FizzBuzz"]
        i % 5 = 0 ["Buzz"]
        i % 3 = 0 ["Fizz"]
        true [i]
    ]
]


using System;

namespace LastSundayOfEachMonth
{
    class Program
    {
        static void Main()
        {
            Console.Write("Year to calculate: ");

            string strYear = Console.ReadLine();
            int year = Convert.ToInt32(strYear);

            DateTime date;
            for (int i = 1; i <= 12; i++)
            {
                date = new DateTime(year, i, DateTime.DaysInMonth(year, i), System.Globalization.CultureInfo.CurrentCulture.Calendar);
                /* Modification by Albert Zakhia on 2021-16-02
                   The below code is very slow due to the loop, we will go twice as fast
                while (date.DayOfWeek != DayOfWeek.Sunday)
                {
                    date = date.AddDays(-1);
                }
                */
                // The updated code
                int daysOffset = date.DayOfWeek - dayOfWeek; // take the offset to subtract directly instead of looping
                if (daysOffset < 0) daysOffset += 7; // if the code is negative, we need to normalize them
                date = date.AddDays(-daysOffset ); // now just add the days offset
                Console.WriteLine(date.ToString("yyyy-MM-dd"));
            }
        }
    }
}


func lltp(n) {
    var b = 1
    var best = nil
    var v = (n-1 -> primes)

    while (v) {
        best = v.max
        b *= n
        v.map! { |vi|
            {|i| i*b + vi }.map(1..^n).grep{.is_prime}...
        }
    }

    return best
}

for i in (3..17) {
    printf("%2d %s\n", i, lltp(i))
}


import BigInt

func largestLeftTruncatablePrime(_ base: Int) -> BigInt {
  var radix = 0
  var candidates = [BigInt(0)]

  while true {
    let multiplier = BigInt(base).power(radix)
    var newCandidates = [BigInt]()

    for i in 1..<BigInt(base) {
      newCandidates += candidates.map({ ($0+i*multiplier, ($0+i*multiplier).isPrime(rounds: 30)) })
                                 .filter({ $0.1 })
                                 .map({ $0.0 })
    }

    if newCandidates.count == 0 {
      return candidates.max()!
    }

    candidates = newCandidates
    radix += 1
  }
}

for i in 3..<18 {
  print("\(i): \(largestLeftTruncatablePrime(i))")
}


package require Tcl 8.5

proc tcl::mathfunc::modexp {a b n} {
    for {set c 1} {$b} {set a [expr {$a*$a%$n}]} {
        if {$b & 1} {
            set c [expr {$c*$a%$n}]
        }
        set b [expr {$b >> 1}]
    }
    return $c
}
# Based on Miller-Rabin primality testing, but with small prime check first
proc is_prime {n {count 10}} {
    # fast check against small primes
    foreach p {
	2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
    } {
	if {$n == $p} {return true}
	if {$n % $p == 0} {return false}
    }

    # write n-1 as 2^s·d with d odd by factoring powers of 2 from n-1
    set d [expr {$n - 1}]
    for {set s 0} {$d & 1 == 0} {incr s} {
        set d [expr {$d >> 1}]
    }

    for {} {$count > 0} {incr count -1} {
        set a [expr {2 + int(rand()*($n - 4))}]
        set x [expr {modexp($a, $d, $n)}]
        if {$x == 1 || $x == $n - 1} continue
        for {set r 1} {$r < $s} {incr r} {
            set x [expr {modexp($x, 2, $n)}]
            if {$x == 1} {return false}
            if {$x == $n - 1} break
        }
	if {$x != $n-1} {return false}
    }
    return true
}

proc max_left_truncatable_prime {base} {
    set stems {}
    for {set i 2} {$i < $base} {incr i} {
	if {[is_prime $i]} {
	    lappend stems $i
	}
    }
    set primes $stems
    set size 0
    for {set b $base} {[llength $stems]} {set b [expr {$b * $base}]} {
	# Progress monitoring is nice once we get to 10 and beyond...
	if {$base > 9} {
	    puts "\t[llength $stems] candidates at length [incr size]"
	}
	set primes $stems
	set certainty [expr {[llength $primes] > 100 ? 1 : 5}]
	set stems {}
	foreach s $primes {
	    for {set i 1} {$i < $base} {incr i} {
		set n [expr {$b*$i + $s}]
		if {[is_prime $n $certainty]} {
		    lappend stems $n
		}
	    }
	}
    }
    # Could be several at same length; choose largest
    return [tcl::mathfunc::max {*}$primes]
}

for {set i 3} {$i <= 20} {incr i} {
    puts "$i: [max_left_truncatable_prime $i]"
}


function divedivedive(d::Int)
    try
        divedivedive(d+1)
    catch
        return d
    end
end


// version 1.1.2

fun recurse(i: Int) {
    try {
        recurse(i + 1)
    }
    catch(e: StackOverflowError) {
        println("Limit of recursion is $i")
    }
}

fun main(args: Array<String>) = recurse(0)


'subroutine recursion limit- end up on 475000

call test 1

sub test n
    if n mod 1000 = 0 then locate 1,1: print n
    call test n+1
end sub


/* Enable limiting recursive calls to lil_parse - this can be used to avoid call stack
 * overflows and is also useful when running through an automated fuzzer like AFL */
/*#define LIL_ENABLE_RECLIMIT 10000*/


make "depth 0

to recurse
  make "depth :depth + 1
  recurse
end

catch "ERROR [recurse]
  ; hit control-C after waiting a while
print error          ; 16 Stopping... recurse [make "depth :depth + 1]
(print [Depth reached:] :depth)   ; some arbitrarily large number


use std::{
    collections::BTreeMap,
    fs::{read_dir, File},
    hash::Hasher,
    io::Read,
    path::{Path, PathBuf},
};

type Duplicates = BTreeMap<(u64, u64), Vec<PathBuf>>;

struct DuplicateFinder {
    found: Duplicates,
    min_size: u64,
}

impl DuplicateFinder {
    fn search(path: impl AsRef<Path>, min_size: u64) -> std::io::Result<Duplicates> {
        let mut result = Self {
            found: BTreeMap::new(),
            min_size,
        };

        result.walk(path)?;
        Ok(result.found)
    }

    fn walk(&mut self, path: impl AsRef<Path>) -> std::io::Result<()> {
        let listing = read_dir(path.as_ref())?;
        for entry in listing {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                self.walk(path)?;
            } else {
                self.compute_digest(&path)?;
            }
        }

        Ok(())
    }

    fn compute_digest(&mut self, file: &Path) -> std::io::Result<()> {
        let size = file.metadata()?.len();
        if size < self.min_size {
            return Ok(());
        }

        // This hasher is weak, we could otherwise use an external crate
        let mut hasher = std::collections::hash_map::DefaultHasher::default();
        let mut bytes = [0u8; 8182];
        let mut f = File::open(file)?;
        loop {
            let n = f.read(&mut bytes[..])?;
            hasher.write(&bytes[..n]);
            if n == 0 {
                break;
            }
        }

        let hash = hasher.finish();

        self.found
            .entry((size, hash))
            .or_insert_with(Vec::new)
            .push(file.to_owned());

        Ok(())
    }
}

fn main() -> std::io::Result<()> {
    let mut args = std::env::args();

    args.next(); // Skip the executable name
    let dir = args.next().unwrap_or_else(|| ".".to_owned());

    let min_size = args
        .next()
        .and_then(|arg| arg.parse::<u64>().ok())
        .unwrap_or(0u64);

    DuplicateFinder::search(dir, min_size)?
        .iter()
        .rev()
        .filter(|(_, files)| files.len() > 1)
        .for_each(|((size, _), files)| {
            println!("Size: {}", size);

            files
                .iter()
                .for_each(|file| println!("{}", file.to_string_lossy()));

            println!();
        });

    Ok(())
}


# usage: sidef fdf.sf [size] [dir1] [...]

require('File::Find')

func find_duplicate_files(Block code, size_min=0, *dirs) {
    var files = Hash()
    %S<File::Find>.find(
        Hash(
            no_chdir => true,
            wanted   => func(arg) {
                var file = File(arg)
                file.is_file || return()
                file.is_link && return()
                var size = file.size
                size >= size_min || return()
                files{size} := [] << file
            },
        ) => dirs...
    )

    files.values.each { |set|
        set.len > 1 || next
        var dups = Hash()
        for i in (^set.end) {
            for (var j = set.end; j > i; --j) {
                if (set[i].compare(set[j]) == 0) {
                    dups{set[i]} := [] << set.pop_at(j++)
                }
            }
        }
        dups.each{ |k,v| code(k.to_file, v...) }
    }

    return()
}

var duplicates = Hash()
func collect(*files) {
    duplicates{files[0].size} := [] << files
}

find_duplicate_files(collect, Num(ARGV.shift), ARGV...)

for k,v in (duplicates.sort_by { |k| -k.to_i }) {
    say "=> Size: #{k}\n#{'~'*80}"
    for files in v {
        say "#{files.sort.join(%Q[\n])}\n#{'-'*80}"
    }
}


package require fileutil
package require md5

proc finddupfiles {dir {minsize 1}} {
    foreach fn [fileutil::find $dir] {
    file lstat $fn stat
    if {$stat(size) < $minsize} continue
    dict lappend byino $stat(dev),$stat(ino) $fn
    if {$stat(type) ne "file"} continue
    set f [open $fn "rb"]
    set content [read $f]
    close $f
    set md5 [md5::md5 -hex $content]
    dict lappend byhash $md5 $fn
    }
    set groups {}
    foreach group [dict values $byino] {
    if {[llength $group] <= 1} continue
    set gs [lsort $group]
    dict set groups [lindex $gs 0] $gs
    }
    foreach group [dict values $byhash] {
    if {[llength $group] <= 1} continue
    foreach f $group {
        if {[dict exists $groups $f]} {
        dict set groups $f [lsort -unique \
            [concat [dict get $groups $f] $group]]
        unset group
        break
        }
    }
    if {[info exist group]} {
        set gs [lsort $group]
        dict set groups [lindex $gs 0] $gs
    }
    }
    set masters {}
    dict for {n g} $groups {
    lappend masters [list $n [llength $g],$n]
    }
    set result {}
    foreach p [lsort -decreasing -index 1 -dictionary $masters] {
    set n [lindex $p 0]
    lappend result $n [dict get $groups $n]
    }
    return $result
}

foreach {leader dupes} [finddupfiles {*}$argv] {
    puts "$leader has duplicates"
    set n 0
    foreach d $dupes {
    if {$d ne $leader} {
        puts "   dupe #[incr n]: $d"
    }
    }
}


: fizz?    ( s-f ) 3 mod 0 = ;
: buzz?    ( s-f ) 5 mod 0 = ;
: num?     ( s-f ) dup fizz? swap buzz? or 0 = ;
: ?fizz    ( s-  ) fizz? [ "Fizz" puts ] ifTrue ;
: ?buzz    ( s-  ) buzz? [ "Buzz" puts ] ifTrue ;
: ?num     ( s-  ) num? &putn &drop if ;
: fizzbuzz ( s-  ) dup ?fizz dup ?buzz dup ?num space ;
: all      (  -  ) 100 [ 1+ fizzbuzz ] iter ;


/*REXX program displays numbers  1 ──► 100  (some transformed) for the FizzBuzz problem.*/
                                                 /*╔═══════════════════════════════════╗*/
  do j=1  to 100;      z=  j                     /*║                                   ║*/
  if j//3    ==0  then z= 'Fizz'                 /*║  The divisors  (//)  of the  IFs  ║*/
  if j//5    ==0  then z= 'Buzz'                 /*║  must be in ascending order.      ║*/
  if j//(3*5)==0  then z= 'FizzBuzz'             /*║                                   ║*/
  say right(z, 8)                                /*╚═══════════════════════════════════╝*/
  end   /*j*/                                    /*stick a fork in it,  we're all done. */


(ns last-sundays.core
  (:require [clj-time.core :as time]
            [clj-time.periodic :refer [periodic-seq]]
            [clj-time.format :as fmt])
  (:import (org.joda.time DateTime DateTimeConstants))
  (:gen-class))

(defn sunday? [t]
  (= (.getDayOfWeek t) (DateTimeConstants/SUNDAY)))

(defn sundays [year]
  (take-while #(= (time/year %) year)
              (filter sunday? (periodic-seq (time/date-time year 1 1) (time/days 1)))))

(defn last-sundays-of-months [year]
  (->> (sundays year)
       (group-by time/month)
       (vals)
       (map (comp first #(sort-by time/day > %)))
       (map #(fmt/unparse (fmt/formatters :year-month-day) %))
       (interpose "\n")
       (apply str)))

(defn -main [& args]
  (println (last-sundays-of-months (Integer. (first args)))))


import "/big" for BigInt
import "/fmt" for Conv, Fmt
import "/sort" for Sort
import "/ioutil" for Input

var nextLeftTruncatablePrimes = Fn.new { |n, radix, certainty|
    var probablePrimes = []
    var baseString = (n == BigInt.zero) ? "" : n.toBaseString(radix)
    for (i in 1...radix) {
        var p = BigInt.fromBaseString(Conv.itoa(i, radix) + baseString, radix)
        if (p.isProbablePrime(certainty)) probablePrimes.add(p)
    }
    return probablePrimes
}

var largestLeftTruncatablePrime = Fn.new { |radix, certainty|
    var lastList = null
    var list = nextLeftTruncatablePrimes.call(BigInt.zero, radix, certainty)
    while (!list.isEmpty) {
        lastList = list
        list = []
        for (n in lastList) list.addAll(nextLeftTruncatablePrimes.call(n, radix, certainty))
    }
    if (!lastList) return null
    Sort.quick(lastList)
    return lastList[-1]
}

var maxRadix  = Input.integer("Enter maximum radix : ", 3, 36)
var certainty = Input.integer("Enter certainty     : ", 1, 100)
System.print()
for (radix in 3..maxRadix) {
    var largest = largestLeftTruncatablePrime.call(radix, certainty)
    Fmt.write("Base = $-2d : ", radix)
    if (!largest) {
        System.print("No left truncatable prime")
    } else {
        Fmt.print("$-35i -> $s", largest, largest.toBaseString(radix))
    }
}


var [const] BN=Import("zklBigNum");  // libGMP
fcn largest_lefty_prime(base){
   primes,p:=List(),BN(1); while(p.nextPrime()<base){ primes.append(p.copy()) }
   b,biggest := BN(1),0;
   while(primes){
      b*=base;  // base,base^2,base^3... gets big
      ps:=List();
      foreach p,n in (primes,[1..base-1]){
         if((z:=(p + b*n)).probablyPrime()){
	    ps.append(z);
	    if(z>biggest) biggest=z;
	 }
      }
      primes=ps;  // the number of lists is small
   }
   biggest
}

foreach n in ([3..17]){ println("%2d %s".fmt(n,largest_lefty_prime(n))) }


integer iLimit_of_Recursion = 0;
Find_Limit_of_Recursion(integer x) {
	llOwnerSay("x="+(string)x);
	iLimit_of_Recursion = x;
	Find_Limit_of_Recursion(x+1);
}
default {
	state_entry() {
		Find_Limit_of_Recursion(0);
		llOwnerSay("iLimit_of_Recursion="+(string)iLimit_of_Recursion);
	}
}


local c = 0
function Tail(proper)
  c = c + 1
  if proper then
    if c < 9999999 then return Tail(proper) else return c end
  else
    return 1/c+Tail(proper) -- make the recursive call must keep previous stack
  end
end

local ok,check = pcall(Tail,true)
print(c, ok, check)
c=0
ok,check = pcall(Tail,false)
print(c, ok, check)


Module checkit {
      Global z
      Function a {
            z++
            =a()
      }
      try {
            m=a()
      }
      Print z

      z<=0
      Function a {
            z++
            call a()
      }
      try {
            call a()
      }
      Print z

      z<=0
      Module m {
            z++
            Call m
      }
      try {
            call m
      }
      Print z

      z<=0
      \\ without Call a module can't call itself
      \\ but can call something global, and that global can call back
      Module Global m1 {
            z++
            m2
      }
      Module Global m2 {
            z++
            m1
      }
      try {
            call m1
      }
      Print z
}
Checkit


import "io" for Directory, File, Stat
import "/crypto" for Sha1
import "/sort" for Sort

var findDuplicates = Fn.new { |dir, minSize|
    if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.")
    var files = Directory.list(dir).where { |f| Stat.path("%(dir)/%(f)").size >= minSize }
    var hashMap = {}
    for (file in files) {
        var path = "%(dir)/%(file)"
        if (Stat.path(path).isDirectory) continue
        var contents = File.read(path)
        var hash = Sha1.digest(contents)
        var exists = hashMap.containsKey(hash)
        if (exists) {
            hashMap[hash].add(file)
        } else {
            hashMap[hash] = [file]
        }
    }
    var duplicates  = []
    for (key in hashMap.keys) {
        if (hashMap[key].count > 1) {
            var files = hashMap[key]
            var path = "%(dir)/%(files[0])"
            var size = Stat.path(path).size
            duplicates.add([size, files])
        }
    }
    var cmp = Fn.new { |i, j| (j[0] - i[0]).sign } // by decreasing size
    Sort.insertion(duplicates, cmp)
    System.print("The sets of duplicate files are:\n")
    for (dup in duplicates) {
        System.print("Size %(dup[0]) bytes:")
        System.print(dup[1].join("\n"))
        System.print()
    }
}

findDuplicates.call("./", 1000)


include(zkl.h.zkl);
const FLAGS=FILE.GLOB.IGNORE_CASE + FILE.GLOB.NO_DIRS;
var [const] MsgHash=Import("zklMsgHash");
var recurse=False, fileSpec, minSz=0, maxSz=(0).MAX;

argh:=Utils.Argh(
   T("+R","R","Recurse into subdirectories, starting at <arg>",
    fcn(arg){ recurse=arg }),
   T("+minSz","","Only consider files larger than <arg>",
    fcn(arg){ minSz=arg.toInt() }),
   T("+maxSz","","Only consider files less than <arg>",
    fcn(arg){ maxSz=arg.toInt() }),
);

argh.parse(vm.arglist);
try { fileSpec=argh.loners[0]; }
catch{
   argh.usage("Find duplicate files");
   System.exit(1);
}

fnames:=Data(0,String);
if (recurse) File.globular(recurse,fileSpec,True,FLAGS,fnames);
else         File.glob(fileSpec,FLAGS).pump(fnames);

files:=Dictionary();  // (len:(name,name...), ...)
foreach fname in (fnames){
   sz:=File.len(fname);
   if(minSz<=sz<=maxSz) files.appendV(File.len(fname),fname);
}

    //////////////////////// group files by size
files=files.pump(List,Void.Xplode,fcn(k,v){ v.len()>1 and v or Void.Skip });
println("Found %d groups of same sized files, %d files total.".fmt(files.len(),
   files.apply("len").sum(0)));

if(not files) System.exit();    // no files found

buffer:=Data(0d100_000);  // we'll resuse this buffer for hashing
hashes:=files.pump(List,'wrap(fnames){ // get the MD5 hash for each file
   fnames.pump(List,'wrap(fname){
      file,hash := File(fname,"rb"), MsgHash.toSink("MD5");
      file.pump(buffer,hash); file.close();
      return(hash.close(),fname); // -->( (hash,name), (hash,name) ... )
   })
},T(Void.Write,Void.Write)); // flatten list of lists of lists to above

   // Hash the file hashes, then scoop out the files with the same hash
buffer:=Dictionary();
files:=hashes.pump(Void,Void.Xplode,buffer.appendV)
       .pump(List,Void.Xplode,fcn(k,v){ v.len()>1 and v or Void.Skip });

println("Found %d duplicate files:".fmt(files.apply("len").sum(0)));
foreach group in (files){ println("   ",group.concat(", ")) }


for n = 1 to 100
    if n % 15 = 0 see "" + n + " = " + "FizzBuzz"+ nl
    but n % 5 = 0 see "" + n + " = " + "Buzz" + nl
    but n % 3 = 0 see "" + n + " = " + "Fizz" + nl
    else see "" + n + " = " + n + nl ok
next


       program-id. last-sun.
       data division.
       working-storage section.
       1 wk-date.
        2 yr pic 9999.
        2 mo pic 99 value 1.
        2 da pic 99 value 1.
       1 rd-date redefines wk-date pic 9(8).
       1 binary.
        2 int-date pic 9(8).
        2 dow pic 9(4).
        2 sunday pic 9(4) value 7.
       procedure division.
           display "Enter a calendar year (1601 thru 9999): "
               with no advancing
           accept yr
           if yr >= 1601 and <= 9999
               continue
           else
               display "Invalid year"
               stop run
           end-if
           perform 12 times
               move 1 to da
               add 1 to mo
               if mo > 12              *> to avoid y10k in 9999
                   move 12 to mo
                   move 31 to da
               end-if
               compute int-date = function
                   integer-of-date (rd-date)
               if mo =12 and da = 31   *> to avoid y10k in 9999
                   continue
               else
                   subtract 1 from int-date
               end-if
               compute rd-date = function
                   date-of-integer (int-date)
               compute dow = function mod
                   ((int-date - 1) 7) + 1
               compute dow = function mod ((dow - sunday) 7)
               subtract dow from da
               display yr "-" mo "-" da
               add 1 to mo
           end-perform
           stop run
           .
       end program last-sun.


>> get(0,'RecursionLimit')

ans =

   500

>> set(0,'RecursionLimit',2500)
>> get(0,'RecursionLimit')

ans =

        2500


f(p) := f(n: p + 1)$
f(0);
Maxima encountered a Lisp error:
 Error in PROGN [or a callee]: Bind stack overflow.
Automatically continuing.
To enable the Lisp debugger set *debugger-hook* to nil.

n;
406


MODULE recur;

IMPORT InOut;

PROCEDURE recursion (a : CARDINAL);

BEGIN
  InOut.Write ('.');    (*  just count the dots....     *)
  recursion (a + 1)
END recursion;

BEGIN
  recursion (0)
END recur.


RECURSE
 IF $DATA(DEPTH)=1 SET DEPTH=1+DEPTH
 IF $DATA(DEPTH)=0 SET DEPTH=1
 WRITE !,DEPTH_" levels down"
 DO RECURSE
 QUIT


set "local1" to 1
: "loop"
wait for 10
if "('local1' % 15)" = 0 then "fizzbuzz"
if "('local1' % 3)" = 0 then "fizz"
if "('local1' % 5)" = 0 then "buzz"
* "&local1&"
: "inc"
inc "local1" by 1
if "local1" <= 100 then "loop"
goto "done"

: "fizzbuzz"
* "FizzBuzz"
goto "inc"

: "fizz"
* "Fizz"
goto "inc"

: "buzz"
* "Buzz"
goto "inc"

: "done"
end


Midnight takes your heart and your soul
While your heart is as high as your soul
Put your heart without your soul into your heart

Give back your heart

Desire is a lovestruck ladykiller
My world is nothing
Fire is ice
Hate is water
Until my world is Desire,
Build my world up
If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing
Shout "FizzBuzz!"
Take it to the top

If Midnight taking my world, Fire is nothing
Shout "Fizz!"
Take it to the top

If Midnight taking my world, Hate is nothing
Say "Buzz!"
Take it to the top

Whisper my world


(defun last-sundays (year)
  (loop for month from 1 to 12
        for last-month-p = (= month 12)
        for next-month = (if last-month-p 1 (1+ month))
        for year-of-next-month = (if last-month-p (1+ year) year)
        for 1st-day-next-month = (encode-universal-time 0 0 0 1 next-month year-of-next-month 0)
        for 1st-day-dow = (nth-value 6 (decode-universal-time 1st-day-next-month 0))
        ;; 0: monday, 1: tuesday, ... 6: sunday
        for diff-to-last-sunday = (1+ 1st-day-dow)
        for last-sunday = (- 1st-day-next-month (* diff-to-last-sunday 24 60 60))
        do (multiple-value-bind (second minute hour date month year)
               (decode-universal-time last-sunday 0)
             (declare (ignore second minute hour))
             (format t "~D-~2,'0D-~2,'0D~%" year month date))))

(last-sundays 2013)


void lastSundays(in uint year) {
    import std.stdio, std.datetime;

    foreach (immutable month; 1 .. 13) {
        auto date = Date(year, month, 1);
        date.day(date.daysInMonth);
        date.roll!"days"(-(date.dayOfWeek + 7) % 7);
        date.writeln;
    }
}

void main() {
    lastSundays(2013);
}


def recurse(counter)
        println counter
        counter += 1
        recurse(counter)
end

recurse(1)


/**
 Recursion limit, in Neko
*/

/* This version is effectively unlimited, (50 billion test before ctrl-c) */
sum = 0.0
counter = 0
tco = function(n) {
    sum += n
    counter += 1
    if n > 10000000 return n else tco(n + 1)
}

try $print("Tail call recursion: ", tco(0), " sum: ", sum, "\n")
catch with $print("tco counter: ", counter, " ", with, "\n")

/* Code after tail, these accumulate stack, will run out of space */
sum = 0.0
counter = 0
recurse = function(n) {
    sum += n
    counter += 1
    if n > 1000000 return n else recurse(n + 1)
    return sum
}

try $print("Recurse: ", recurse(0), " sum: ", sum, "\n")
catch with $print("recurse limit exception: ", counter, " ", with, "\n")


/* NetRexx */
options replace format comments java crossref symbols binary

import java.lang.management.

memoryInfo()
digDeeper(0)

/**
 * Just keep digging
 * @param level depth gauge
 */
method digDeeper(level = int) private static binary
  do
    digDeeper(level + 1)
  catch ex = Error
    System.out.println('Recursion got' level 'levels deep on this system.')
    System.out.println('Recursion stopped by' ex.getClass.getName())
  end
  return

/**
 * Display some memory usage from the JVM
 * @see ManagementFactory
 * @see MemoryMXBean
 * @see MemoryUsage
 */
method memoryInfo() private static
  mxBean = ManagementFactory.getMemoryMXBean()   -- get the MemoryMXBean
  hmMemoryUsage = mxBean.getHeapMemoryUsage()    -- get the heap MemoryUsage object
  nmMemoryUsage = mxBean.getNonHeapMemoryUsage() -- get the non-heap MemoryUsage object
  say 'JVM Memory Information:'
  say '      Heap:' hmMemoryUsage.toString()
  say '  Non-Heap:' nmMemoryUsage.toString()
  say '-'.left(120, '-')
  say
  return


1.upto(100) do |n|
  print "Fizz" if a = (n % 3).zero?
  print "Buzz" if b = (n % 5).zero?
  print n unless (a || b)
  puts
end


program Find_the_last_Sunday_of_each_month;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.DateUtils;

// ADayOfWeek -> sunday is the first day and is 1
function LastDayOfWeekOfEachMonth(AYear, ADayOfWeek: Word): TArray<TDateTime>;
var
  month: word;
  daysOffset: Integer;
  date: TDatetime;
begin
  if (ADayOfWeek > 7) or (ADayOfWeek < 1) then
    raise Exception.CreateFmt('Error on FindAllDaysOfWeek: "%d" must be in [1..7] (sun..sat)',
      [ADayOfWeek]);

  SetLength(Result, 12);

  for month := 1 to 12 do
  begin
    date := EncodeDate(AYear, month, DaysInAMonth(AYear, month));

    daysOffset := DayOfWeek(date) - ADayOfWeek;
    if daysOffset < 0 then
      inc(daysOffset, 7);

    Result[month - 1] := date - daysOffset;
  end;
end;

var
  strYear: string;
  Year: Integer;
  date: TDateTime;

begin
  write('Year to calculate: ');
  Readln(strYear);
  if not TryStrToInt(strYear, Year) or (Year < 1900) then
    raise Exception.CreateFmt('Error: "%s" is not a valid year', [strYear]);

  for date in LastDayOfWeekOfEachMonth(Year, 1) do
    writeln(FormatDateTime('yyyy-mmm-dd', date));

  readln;
end.


defmodule RC do
  def lastSunday(year) do
    Enum.map(1..12, fn month ->
      lastday = :calendar.last_day_of_the_month(year, month)
      daynum = :calendar.day_of_the_week(year, month, lastday)
      sunday = lastday - rem(daynum, 7)
      {year, month, sunday}
    end)
  end
end

y = String.to_integer(hd(System.argv))
Enum.each(RC.lastSunday(y), fn {year, month, day} ->
  :io.format "~4b-~2..0w-~2..0w~n", [year, month, day]
end)


proc recurse(i: int): int =
  echo i
  recurse(i+1)
echo recurse(0)


# let last = ref 0 ;;
val last : int ref = {contents = 0}
# let rec f i =
    last := i;
    i + (f (i+1))
  ;;
val f : int -> int = <fun>
# f 0 ;;
stack overflow during evaluation (looping recursion?).
# !last ;;
- : int = 262067


Using ooRexx for the program shown under Rexx:

 rexx pgm 1>x1 2>x2

 puts the numbers in x1 and the error messages in x2

...
2785
2786
8 *-*      call self
....
     8 *-*   call self
     3 *-* call self
Error 11 running C:\work.ooRexx\wc\main.4.1.1.release\Win32Rel\StreamClasses.orx line 366:  Control stack full
Error 11.1:  Insufficient control stack space; cannot continue execution


declare
  proc {Recurse Number}
     {Show Number}
     {Recurse Number+1}
  end
in
  {Recurse 1}


require 'fizzbuzz'

describe 'FizzBuzz' do
  context 'knows that a number is divisible by' do
    it '3' do
      expect(is_divisible_by_three?(3)).to be_true
    end
    it '5' do
      expect(is_divisible_by_five?(5)).to be_true
    end
    it '15' do
      expect(is_divisible_by_fifteen?(15)).to be_true
    end
  end
  context 'knows that a number is not divisible by' do
    it '3' do
      expect(is_divisible_by_three?(1)).not_to be_true
    end
    it '5' do
      expect(is_divisible_by_five?(1)).not_to be_true
    end
    it '15' do
      expect(is_divisible_by_fifteen?(1)).not_to be_true
    end
  end
  context 'while playing the game it returns' do
    it 'the number' do
      expect(fizzbuzz(1)).to eq 1
    end
    it 'Fizz' do
      expect(fizzbuzz(3)).to eq 'Fizz'
    end
    it 'Buzz' do
      expect(fizzbuzz(5)).to eq 'Buzz'
    end
    it 'FizzBuzz' do
      expect(fizzbuzz(15)).to eq 'FizzBuzz'
    end
  end
end


(require 'calendar)

(defun last-sunday (year)
  "Print the last Sunday in each month of year"
  (mapcar (lambda (month)
    (let*
      ((days (number-sequence 1 (calendar-last-day-of-month month year)))
       (mdy (mapcar (lambda (x) (list month x year)) days))
       (weekdays (mapcar #'calendar-day-of-week mdy))
       (lastsunday (1+ (cl-position 0 weekdays :from-end t))))
      (insert (format "%i-%02i-%02i \n" year month lastsunday))))
    (number-sequence 1 12)))

(last-sunday 2013)


-module(last_sundays).

-export([in_year/1]).

% calculate all the last sundays in a particular year
in_year(Year) ->
    [lastday(Year, Month, 7) || Month <- lists:seq(1, 12)].

% calculate the date of the last occurrence of a particular weekday
lastday(Year, Month, WeekDay) ->
    Ldm = calendar:last_day_of_the_month(Year, Month),
    Diff = calendar:day_of_the_week(Year, Month, Ldm) rem WeekDay,
    {Year, Month, Ldm - Diff}.


my $x = 0;
recurse($x);

sub recurse ($x) {
   print ++$x,"\n";
   recurse($x);
}


atom t1 = time()+1

integer depth = 0

procedure recurse()
    if time()>t1 then
        ?depth
        t1 = time()+1
    end if
    depth += 1
    -- only 1 of these will ever get called, of course...
    recurse()
    recurse()
    recurse()
end procedure

recurse()


<?php
function a() {
    static $i = 0;
    print ++$i . "\n";
    a();
}
a();


lastSundayOfEachMonth
=LAMBDA(y,
    LAMBDA(monthEnd,
        1 + monthEnd - WEEKDAY(monthEnd)
    )(
        EDATE(
            DATEVALUE(y & "-01-31"),
            SEQUENCE(12, 1, 0, 1)
        )
    )
)


$ ulimit -s
8192
$ pil +
: (let N 0 (recur (N) (recurse (msg (inc N)))))
...
730395
730396
730397
Segmentation fault


recurs: proc options (main) reorder;
dcl sysprint file;
dcl mod      builtin;

dcl ri       fixed bin(31) init (0);

recursive: proc recursive;
  ri += 1;
  if mod(ri, 1024) = 1 then
    put data(ri);

  call recursive();
end recursive;

call recursive();
end recurs;


function TestDepth ( $N )
    {
    $N
    TestDepth ( $N + 1 )
    }

try
    {
    TestDepth 1 | ForEach { $Depth = $_ }
    }
catch
    {
    "Exception message: " + $_.Exception.Message
    }
"Last level before error: " + $Depth


Procedure Recur(n)
  PrintN(str(n))
  Recur(n+1)
EndProcedure

Recur(1)


data _null_;
  do i=1 to 100;
    if mod(i,15)=0 then put "FizzBuzz";
    else if mod(i,5)=0 then put "Buzz";
    else if mod(i,3)=0 then put "Fizz";
    else put i;
  end;
run;


USING: calendar calendar.format command-line io kernel math math.parser
sequences ;
IN: rosetta-code.last-sunday

: parse-year     (    -- ts  ) (command-line) second string>number <year> ;
: print-last-sun ( ts --     ) last-sunday-of-month (timestamp>ymd) nl ;
: inc-month      ( ts -- ts' ) 1 months time+ ;
: process-month  ( ts -- ts' ) dup print-last-sun inc-month ;
: main           (    --     ) parse-year 12 [ process-month ] times drop ;

MAIN: main


#APPTYPE CONSOLE

DIM date AS INTEGER, dayname AS STRING
FOR DIM i = 1 TO 12
    FOR DIM j = 31 DOWNTO 1
        date = 20130000 + (i * 100) + j
        IF CHECKDATE(i, j, 2013) THEN
            dayname = DATECONV(date, "dddd")
            IF dayname = "Sunday" THEN
                PRINT 2013, " ", i, " ", j
                EXIT FOR
            END IF
        END IF
    NEXT
NEXT

PAUSE


#Get the limit
options("expressions")

#Set it
options(expressions = 10000)

#Test it
recurse <- function(x)
{
  print(x)
  recurse(x+1)

}
recurse(0)


#lang racket
(define (recursion-limit)
  (with-handlers ((exn? (lambda (x) 0)))
    (add1 (recursion-limit))))


my $x = 0;
recurse;

sub recurse () {
   ++$x;
   say $x if $x %% 1_000_000;
   recurse;
}


/*REXX program finds the recursion limit:   a subroutine that repeatably calls itself.  */
parse version x;     say x;     say             /*display which REXX is being used.     */
#=0                                             /*initialize the numbers of invokes to 0*/
call self                                       /*invoke the  SELF  subroutine.         */
                                                /* [↓]  this will never be executed.    */
exit                                            /*stick a fork in it,  we're all done.  */
/*──────────────────────────────────────────────────────────────────────────────────────*/
self: procedure expose #                        /*declaring that  SELF  is a subroutine.*/
      #=#+1                                     /*bump number of times SELF is invoked. */
      say #                                     /*display the number of invocations.    */
      call self                                 /*invoke ourselves recursively.         */


class MAIN is
  main is
    loop i ::= 1.upto!(100);
      s:STR := "";
      if i % 3 = 0 then s := "Fizz"; end;
      if i % 5 = 0 then s := s + "Buzz"; end;
      if s.length > 0 then
        #OUT + s + "\n";
      else
        #OUT + i + "\n";
      end;
    end;
  end;
end;


      D = DAYNUM(Y,M,D)    !Daynumber from date.
      DAYNUM(Y,M,D) = D    !Date parts from a day number.


program sundays;

Uses sysutils;

type
  MonthLength = Array[1..13] of Integer;

procedure sund(y : Integer);
var
  dt : TDateTime;
  m,mm : Integer;
  len : MonthLength;
begin
   len[1] := 31; len[2] := 28; len[3] := 31; len[4] := 30;
   len[5] := 31; len[6] := 30; len[7] := 31; len[8] := 31;
   len[9] := 30; len[10] := 31; len[11] := 30; len[12] := 31; len[13] := 29;
   for m := 1 to 12 do
   begin
      mm := m;
      if (m = 2) and IsLeapYear( y ) then
         mm := 13;
      dt := EncodeDate( y, mm, len[mm] );
      dt := EncodeDate( y, mm, len[mm] - DayOfWeek(dt) + 1 );
      WriteLn(FormatDateTime('YYYY-MM-DD', dt ));
   end;
end;

var
  i : integer;
  yy: integer;
begin
   for i := 1 to paramCount() do begin
      Val( paramStr(1), yy );
      sund( yy );
   end;
end.


recurse(0)

func recurse x
     see ""+ x + nl
     recurse(x+1)


def recurse x
  puts x
  recurse(x+1)
end

recurse(0)


a = recurTest(1)

function recurTest(n)
if n mod 100000 then cls:print n
if n > 327000 then [ext]
   n = recurTest(n+1)
[ext]
end function


fn recurse(n: i32) {
    println!("depth: {}", n);
    recurse(n + 1)
}

fn main() {
    recurse(0);
}


class MAIN is
  attr r:INT;
  recurse is
    r := r + 1;
    #OUT + r + "\n";
    recurse;
  end;
  main is
    r := 0;
    recurse;
  end;
end;


def recurseTest(i:Int):Unit={
   try{
      recurseTest(i+1)
   } catch { case e:java.lang.StackOverflowError =>
      println("Recursion depth on this system is " + i + ".")
   }
}
recurseTest(0)


object FizzBuzz extends App {
  1 to 100 foreach { n =>
    println((n % 3, n % 5) match {
      case (0, 0) => "FizzBuzz"
      case (0, _) => "Fizz"
      case (_, 0) => "Buzz"
      case _ => n
    })
  }
}