from itertools import count, chain
from collections import deque

def primes(_cache=[2, 3]):
    yield from _cache
    for n in count(_cache[-1]+2, 2):
        if isprime(n):
            _cache.append(n)
            yield n

def isprime(n):
    for p in primes():
        if n%p == 0:
            return False
        if p*p > n:
            return True

def factors(n):
    for p in primes():
    # prime factoring is such a non-issue for small numbers that, for
    # this example, we might even just say
    # for p in count(2):
        if p*p > n:
            if n > 1:
                yield(n, 1, 1)
            break

        if n%p == 0:
            cnt = 0
            while True:
                n, cnt = n//p, cnt+1
                if n%p != 0: break
            yield p, cnt, n
# ^^ not the most sophisticated prime number routines, because no need

# Returns (list1, list2) representing the division between
# two polinomials. A list p of integers means the product
#   (x^p[0] - 1) * (x^p[1] - 1) * ...
def cyclotomic(n):
    def poly_div(num, den):
        return (num[0] + den[1], num[1] + den[0])

    def elevate(poly, n): # replace poly p(x) with p(x**n)
        powerup = lambda p, n: [a*n for a in p]
        return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n))

    if n == 0:
        return ([], [])
    if n == 1:
        return ([1], [])

    p, m, r = next(factors(n))
    poly = cyclotomic(r)
    return elevate(poly_div(elevate(poly, p), poly), p**(m-1))

def to_text(poly):
    def getx(c, e):
        if e == 0:
            return '1'
        elif e == 1:
            return 'x'
        return 'x' + (''.join('⁰¹²³⁴⁵⁶⁷⁸⁹'[i] for i in map(int, str(e))))

    parts = []
    for (c,e) in (poly):
        if c < 0:
            coef = ' - ' if c == -1 else f' - {-c} '
        else:
            coef = (parts and ' + ' or '') if c == 1 else f' + {c}'
        parts.append(coef + getx(c,e))
    return ''.join(parts)

def terms(poly):
    # convert above representation of division to (coef, power) pairs

    def merge(a, b):
        # a, b should be deques. They may change during the course.
        while a or b:
            l = a[0] if a else (0, -1) # sentinel value
            r = b[0] if b else (0, -1)
            if l[1] > r[1]:
                a.popleft()
            elif l[1] < r[1]:
                b.popleft()
                l = r
            else:
                a.popleft()
                b.popleft()
                l = (l[0] + r[0], l[1])
            yield l

    def mul(poly, p): # p means polynomial x^p - 1
        poly = list(poly)
        return merge(deque((c, e+p) for c,e in poly),
                     deque((-c, e) for c,e in poly))

    def div(poly, p): # p means polynomial x^p - 1
        q = deque()
        for c,e in merge(deque(poly), q):
            if c:
                q.append((c, e - p))
                yield (c, e - p)
            if e == p: break

    p = [(1, 0)]  # 1*x^0, i.e. 1

    for x in poly[0]: # numerator
        p = mul(p, x)
    for x in sorted(poly[1], reverse=True): # denominator
        p = div(p, x)
    return p

for n in chain(range(11), [2]):
    print(f'{n}: {to_text(terms(cyclotomic(n)))}')

want = 1
for n in count():
    c = [c for c,_ in terms(cyclotomic(n))]
    while want in c or -want in c:
        print(f'C[{want}]: {n}')
        want += 1


#lang racket
(require srfi/14)

(define 0-char (char->integer #\0))
(define A-char (char->integer #\A))

(define (cusip-value c)
  (cond
    [(char-set-contains? char-set:digit c)
     (- (char->integer c) 0-char)]
    [(char-set-contains? char-set:upper-case c)
     (+ 10 (- (char->integer c) A-char))]
    [(char=? c #\*) 36]
    [(char=? c #\@) 37]
    [(char=? c #\#) 38]))

(define (cusip-check-digit cusip)
  (modulo
   (- 10
      (modulo
       (for/sum
        ((i (sequence-map add1 (in-range 8))) (c (in-string cusip)))
         (let* ((v (cusip-value c)) (v′ (if (even? i) (* v 2) v)))
           (+ (quotient v′ 10) (modulo v′ 10)))) 10)) 10))

(define (CUSIP? s)
  (char=? (string-ref s (sub1 (string-length s)))
          (integer->char (+ 0-char (cusip-check-digit s)))))

(module+ test
  (require rackunit)
  (check-true (CUSIP? "037833100"))
  (check-true (CUSIP? "17275R102"))
  (check-true (CUSIP? "38259P508"))
  (check-true (CUSIP? "594918104"))
  (check-false (CUSIP? "68389X106"))
  (check-true (CUSIP? "68389X105")))


Module Module1
    Dim primes As List(Of Long) = {3L, 5L}.ToList()

    Sub Main(args As String())
        Const cutOff As Integer = 200, bigUn As Integer = 100000,
              tn As String = " cuban prime"
        Console.WriteLine("The first {0:n0}{1}s:", cutOff, tn)
        Dim c As Integer = 0, showEach As Boolean = True, skip As Boolean = True,
            v As Long = 0, st As DateTime = DateTime.Now
        For i As Long = 1 To Long.MaxValue
            v = 3 * i : v = v * i + v + 1
            Dim found As Boolean = False, mx As Integer = Math.Ceiling(Math.Sqrt(v))
            For Each item In primes
                If item > mx Then Exit For
                If v Mod item = 0 Then found = True : Exit For
            Next : If Not found Then
                c += 1 : If showEach Then
                    For z = primes.Last + 2 To v - 2 Step 2
                        Dim fnd As Boolean = False
                        For Each item In primes
                            If item > mx Then Exit For
                            If z Mod item = 0 Then fnd = True : Exit For
                        Next : If Not fnd Then primes.Add(z)
                    Next : primes.Add(v) : Console.Write("{0,11:n0}", v)
                    If c Mod 10 = 0 Then Console.WriteLine()
                    If c = cutOff Then showEach = False
                Else
                    If skip Then skip = False : i += 772279 : c = bigUn - 1
                End If
                If c = bigUn Then Exit For
            End If
        Next
        Console.WriteLine("{1}The {2:n0}th{3} is {0,17:n0}", v, vbLf, c, tn)
        Console.WriteLine("Computation time was {0} seconds", (DateTime.Now - st).TotalSeconds)
        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
    End Sub
End Module


import "/fmt" for Fmt

var start = System.clock
var primes = [3, 5]
var cutOff = 200
var bigOne = 100000
var cubans = []
var bigCuban = ""
var c = 0
var showEach = true
var u = 0
var v = 1

for (i in 1...(1<<20)) {
    var found = false
    u = u + 6
    v = v + u
    var mx = v.sqrt.floor
    for (item in primes) {
        if (item > mx) break
        if (v%item == 0) {
            found = true
            break
        }
    }
    if (!found) {
        c = c + 1
        if (showEach) {
            var z = primes[-1]
            while (z <= v -2) {
                z = z + 2
                var fnd = false
                for (item in primes) {
                    if (item > mx) break
                    if (z%item == 0) {
                        fnd = true
                        break
                    }
                }
                if (!fnd) {
                    primes.add(z)
                }
            }
            primes.add(v)
            cubans.add(Fmt.commatize(v))
            if (c == cutOff) showEach = false
        }
        if (c == bigOne) {
            bigCuban = Fmt.commatize(v)
            break
        }
    }
}

System.print("The first 200 cuban primes are:-")
for (i in 0...20) {
    var j = i * 10
    for (k in j...j+10) System.write(Fmt.s(10, cubans[k])) // 10 per line say
    System.print()
}

System.print("\nThe 100,000th cuban prime is %(bigCuban)")
System.print("\nTook %(System.clock - start) secs")


def makeRunningStdDev() {
    var sum := 0.0
    var sumSquares := 0.0
    var count := 0.0

    def insert(v) {
        sum += v
        sumSquares += v ** 2
        count += 1
    }

    /** Returns the standard deviation of the inputs so far, or null if there
        have been no inputs. */
    def stddev() {
        if (count > 0) {
            def meanSquares := sumSquares/count
            def mean := sum/count
            def variance := meanSquares - mean**2
            return variance.sqrt()
        }
    }

    return [insert, stddev]
}


use Math::Polynomial::Cyclotomic:from<Perl5> <cyclo_poly_iterate cyclo_poly>;

say 'First 30 cyclotomic polynomials:';
my $iterator = cyclo_poly_iterate(1);
say "Φ($_) = " ~ super $iterator().Str for 1..30;

say "\nSmallest cyclotomic polynomial with |n| as a coefficient:";
say "Φ(1) has a coefficient magnitude: 1";

my $index = 0;
for 2..9 -> $coefficient {
    loop {
        $index += 5;
        my \Φ = cyclo_poly($index);
        next unless Φ ~~ / $coefficient\* /;
        say "Φ($index) has a coefficient magnitude: $coefficient";
        $index -= 5;
        last;
    }
}

sub super ($str) {
    $str.subst( / '^' (\d+) /, { $0.trans([<0123456789>.comb] => [<⁰¹²³⁴⁵⁶⁷⁸⁹>.comb]) }, :g)
}


/*REXX program validates that the  last digit (the check digit)  of a  CUSIP  is valid. */
@.=
parse arg @.1 .
if @.1=='' | @.1==","  then do;   @.1= 037833100       /* Apple Incorporated            */
                                  @.2= 17275R102       /* Cisco Systems                 */
                                  @.3= 38259P508       /* Google Incorporated           */
                                  @.4= 594918104       /* Microsoft Corporation         */
                                  @.5= 68389X106       /* Oracle Corporation (incorrect)*/
                                  @.6= 68389X105       /* Oracle Corporation            */
                            end

     do j=1  while @.j\='';   chkDig=CUSIPchk(@.j)     /*calculate check digit from func*/
     OK=word("isn't is", 1 + (chkDig==right(@.j,1) ) ) /*validate  check digit with func*/
     say 'CUSIP '    @.j    right(OK, 6)     "valid."  /*display the CUSIP and validity.*/
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
CUSIPchk: procedure;  arg x 9;  $=0;                     abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                                       do k=1  for 8
                                       y=substr(x, k, 1)
                                          select
                                          when datatype(y,'W')  then #=y
                                          when datatype(y,'U')  then #=pos(y, abc) + 9
                                          when          y=='*'  then #=36
                                          when          y=='@'  then #=37
                                          when          y=='#'  then #=38
                                          otherwise  return 0       /*invalid character.*/
                                          end   /*select*/
                                       if k//2==0  then #=#+#       /*K even?  Double it*/
                                       $=$ + #%10 + #//10
                                       end      /*k*/
           return (10- $//10) // 10


# Project : CUSIP

inputstr = list(6)
inputstr[1] = "037833100"
inputstr[2] = "17275R102"
inputstr[3] = "38259P508"
inputstr[4] = "594918104"
inputstr[5] = "68389X106"
inputstr[6] = "68389X105"
for n = 1 to len(inputstr)
     cusip(inputstr[n])
next

func cusip(inputstr)
        if len(inputstr) != 9
            see " length is incorrect, invalid cusip"
            return
        ok
        v = 0
        sum = 0
        for i = 1 to 8
             flag = 0
             x = ascii(inputstr[i])
             if x >= ascii("0") and x <= ascii("9")
                v = x - ascii("0")
                flag = 1
             ok
             if x >= ascii("A") and x <= ascii("Z")
                v = x - 55
                flag = 1
             ok
             if x = ascii("*")
                v= 36
                flag = 1
             ok
             if x = ascii("@")
                v = 37
                flag = 1
             ok
             if x = ascii("#")
                v = 38
                flag = 1
             ok
             if flag = 0
                  see " found a invalid character, invalid cusip" + nl
             ok
             if (i % 2) = 0
                 v = v * 2
             ok
             sum = sum + floor(v / 10) + v % 10
        next
        sum = (10 - (sum % 10)) % 10
        if sum = (ascii(inputstr[9]) - ascii("0"))
           see inputstr + " is valid" + nl
        else
           see inputstr + " is invalid" + nl
        ok


var [const] BI=Import("zklBigNum");  // libGMP
cubans:=(1).walker(*).tweak('wrap(n){ // lazy iterator
   p:=3*n*(n + 1) + 1;
   BI(p).probablyPrime() and p or Void.Skip
});
println("First 200 cuban primes:");
do(20){ (10).pump(String, cubans.next, "%10,d".fmt).println() }

cubans.drop(100_000 - cubans.n).value :
   println("\nThe 100,000th cuban prime is: %,d".fmt(_));


defmodule Standard_deviation do
  def add_sample( pid, n ), do: send( pid, {:add, n} )

  def create, do: spawn_link( fn -> loop( [] ) end )

  def destroy( pid ), do: send( pid, :stop )

  def get( pid ) do
    send( pid, {:get, self()} )
    receive do
      { :get, value, _pid } -> value
    end
  end

  def task do
    pid = create()
    for x <- [2,4,4,4,5,5,7,9], do: add_print( pid, x, add_sample(pid, x) )
    destroy( pid )
  end

  defp add_print( pid, n, _add ) do
    IO.puts "Standard deviation #{ get(pid) } when adding #{ n }"
  end

  defp loop( ns ) do
    receive do
      {:add, n} -> loop( [n | ns] )
      {:get, pid} ->
        send( pid, {:get, loop_calculate( ns ), self()} )
        loop( ns )
      :stop -> :ok
    end
  end

  defp loop_calculate( ns ) do
    average = loop_calculate_average( ns )
    :math.sqrt( loop_calculate_average( for x <- ns, do: :math.pow(x - average, 2) ) )
  end

  defp loop_calculate_average( ns ), do: Enum.sum( ns ) / length( ns )
end

Standard_deviation.task


var Poly = require('Math::Polynomial')
Poly.string_config(Hash(fold_sign => true, prefix => "", suffix => ""))

func poly_interpolation(v) {
    v.len.of {|n| v.len.of {|k| n**k } }.msolve(v)
}

say "First 30 cyclotomic polynomials:"
for k in (1..30) {
    var a = (k+1).of { cyclotomic(k, _) }
    var Φ = poly_interpolation(a)
    say ("Φ(#{k}) = ", Poly.new(Φ...))
}

say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:"
for n in (1..10) {  # very slow
    var k = (1..Inf -> first {|k|
        poly_interpolation((k+1).of { cyclotomic(k, _) }).first { .abs == n }
    })
    say "Φ(#{k}) has coefficient with magnitude #{n}"
}


#!/usr/bin/env ruby

def check_cusip(cusip)
  abort('CUSIP must be 9 characters') if cusip.size != 9

  sum = 0
  cusip.split('').each_with_index do |char, i|
    next if i == cusip.size - 1
    case
    when char.scan(/\D/).empty?
      v = char.to_i
    when char.scan(/\D/).any?
      pos = char.upcase.ord - 'A'.ord + 1
      v = pos + 9
    when char == '*'
      v = 36
    when char == '@'
      v = 37
    when char == '#'
      v = 38
    end

    v *= 2 unless (i % 2).zero?
    sum += (v/10).to_i + (v % 10)
  end

  check = (10 - (sum % 10)) % 10
  return 'VALID' if check.to_s == cusip.split('').last
  'INVALID'
end

CUSIPs = %w[
  037833100 17275R102 38259P508 594918104 68389X106 68389X105
]

CUSIPs.each do |cusip|
  puts "#{cusip}: #{check_cusip(cusip)}"
end


fn cusip_check(cusip: &str) -> bool {
    if cusip.len() != 9 {
        return false;
    }

    let mut v = 0;
    let capital_cusip = cusip.to_uppercase();
    let char_indices = capital_cusip.as_str().char_indices().take(7);

    let total = char_indices.fold(0, |total, (i, c)| {
        v = match c {
            '*' => 36,
            '@' => 37,
            '#' => 38,
            _ if c.is_digit(10) => c.to_digit(10).unwrap() as u8,
            _ if c.is_alphabetic() => (c as u8) - b'A' + 1 + 9,
            _ => v,
        };

        if i % 2 != 0 {
            v *= 2
        }
        total + (v / 10) + v % 10
    });

    let check = (10 - (total % 10)) % 10;
    (check.to_string().chars().nth(0).unwrap()) == cusip.chars().nth(cusip.len() - 1).unwrap()
}

fn main() {
    let codes = [
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105",
    ];
    for code in &codes {
        println!("{} -> {}", code, cusip_check(code))
    }
}


(defun running-std (items)
  (let ((running-sum 0)
        (running-len 0)
        (running-squared-sum 0)
        (result 0))
    (dolist (item items)
      (setq running-sum (+ running-sum item))
      (setq running-len (1+ running-len))
      (setq running-squared-sum (+ running-squared-sum (* item item)))
      (setq result (sqrt (- (/ running-squared-sum (float running-len))
                            (/ (* running-sum running-sum)
                               (float (* running-len running-len))))))
      (message "%f" result))
    result))

(running-std '(2 4 4 4 5 5 7 9))


-module( standard_deviation ).

-export( [add_sample/2, create/0, destroy/1, get/1, task/0] ).

-compile({no_auto_import,[get/1]}).

add_sample( Pid, N ) -> Pid ! {add, N}.

create() -> erlang:spawn_link( fun() -> loop( [] ) end ).

destroy( Pid ) -> Pid ! stop.

get( Pid ) ->
	Pid ! {get, erlang:self()},
	receive
	{get, Value, Pid} -> Value
	end.

task() ->
	Pid = create(),
	[add_print(Pid, X, add_sample(Pid, X)) || X <- [2,4,4,4,5,5,7,9]],
	destroy( Pid ).

add_print( Pid, N, _Add ) -> io:fwrite( "Standard deviation ~p when adding ~p~n", [get(Pid), N] ).

loop( Ns ) ->
	receive
	{add, N} -> loop( [N | Ns] );
	{get, Pid} ->
		Pid ! {get, loop_calculate( Ns ), erlang:self()},
		loop( Ns );
	stop -> ok
	end.

loop_calculate( Ns ) ->
	Average = loop_calculate_average( Ns ),
	math:sqrt( loop_calculate_average([math:pow(X - Average, 2) || X <- Ns]) ).

loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).


Imports System.Text

Module Module1
    Private ReadOnly MAX_ALL_FACTORS As Integer = 100_000
#Const ALGORITHM = 2

    Class Term
        Implements IComparable(Of Term)

        Public ReadOnly Property Coefficient As Long
        Public ReadOnly Property Exponent As Long

        Public Sub New(c As Long, Optional e As Long = 0)
            Coefficient = c
            Exponent = e
        End Sub

        Public Shared Operator -(t As Term) As Term
            Return New Term(-t.Coefficient, t.Exponent)
        End Operator

        Public Shared Operator +(lhs As Term, rhs As Term) As Term
            If lhs.Exponent <> rhs.Exponent Then
                Throw New ArgumentException("Exponents not equal")
            End If
            Return New Term(lhs.Coefficient + rhs.Coefficient, lhs.Exponent)
        End Operator

        Public Shared Operator *(lhs As Term, rhs As Term) As Term
            Return New Term(lhs.Coefficient * rhs.Coefficient, lhs.Exponent + rhs.Exponent)
        End Operator

        Public Function CompareTo(other As Term) As Integer Implements IComparable(Of Term).CompareTo
            Return -Exponent.CompareTo(other.Exponent)
        End Function

        Public Overrides Function ToString() As String
            If Coefficient = 0 Then
                Return "0"
            End If
            If Exponent = 0 Then
                Return Coefficient.ToString
            End If
            If Coefficient = 1 Then
                If Exponent = 1 Then
                    Return "x"
                End If
                Return String.Format("x^{0}", Exponent)
            End If
            If Coefficient = -1 Then
                If Exponent = 1 Then
                    Return "-x"
                End If
                Return String.Format("-x^{0}", Exponent)
            End If
            If Exponent = 1 Then
                Return String.Format("{0}x", Coefficient)
            End If
            Return String.Format("{0}x^{1}", Coefficient, Exponent)
        End Function
    End Class

    Class Polynomial
        Implements IEnumerable(Of Term)

        Private ReadOnly polyTerms As New List(Of Term)

        Public Sub New()
            polyTerms.Add(New Term(0))
        End Sub

        Public Sub New(ParamArray values() As Term)
            If values.Length = 0 Then
                polyTerms.Add(New Term(0))
            Else
                polyTerms.AddRange(values)
            End If
            Normalize()
        End Sub

        Public Sub New(values As IEnumerable(Of Term))
            polyTerms.AddRange(values)
            If polyTerms.Count = 0 Then
                polyTerms.Add(New Term(0))
            End If
            Normalize()
        End Sub

        Public Function LeadingCoeficient() As Long
            Return polyTerms(0).Coefficient
        End Function

        Public Function Degree() As Long
            Return polyTerms(0).Exponent
        End Function

        Public Function HasCoefficentAbs(coeff As Long) As Boolean
            For Each t In polyTerms
                If Math.Abs(t.Coefficient) = coeff Then
                    Return True
                End If
            Next
            Return False
        End Function

        Public Function GetEnumerator() As IEnumerator(Of Term) Implements IEnumerable(Of Term).GetEnumerator
            Return polyTerms.GetEnumerator
        End Function

        Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
            Return polyTerms.GetEnumerator
        End Function

        Private Sub Normalize()
            polyTerms.Sort(Function(a As Term, b As Term) a.CompareTo(b))
        End Sub

        Public Shared Operator +(lhs As Polynomial, rhs As Term) As Polynomial
            Dim terms As New List(Of Term)
            Dim added = False
            For Each ct In lhs
                If ct.Exponent = rhs.Exponent Then
                    added = True
                    If ct.Coefficient + rhs.Coefficient <> 0 Then
                        terms.Add(ct + rhs)
                    End If
                Else
                    terms.Add(ct)
                End If
            Next
            If Not added Then
                terms.Add(rhs)
            End If
            Return New Polynomial(terms)
        End Operator

        Public Shared Operator *(lhs As Polynomial, rhs As Term) As Polynomial
            Dim terms As New List(Of Term)
            For Each ct In lhs
                terms.Add(ct * rhs)
            Next
            Return New Polynomial(terms)
        End Operator

        Public Shared Operator +(lhs As Polynomial, rhs As Polynomial) As Polynomial
            Dim terms As New List(Of Term)
            Dim thisCount = lhs.polyTerms.Count
            Dim polyCount = rhs.polyTerms.Count
            While thisCount > 0 OrElse polyCount > 0
                If thisCount = 0 Then
                    Dim polyTerm = rhs.polyTerms(polyCount - 1)
                    terms.Add(polyTerm)
                    polyCount -= 1
                ElseIf polyCount = 0 Then
                    Dim thisTerm = lhs.polyTerms(thisCount - 1)
                    terms.Add(thisTerm)
                    thisCount -= 1
                Else
                    Dim polyTerm = rhs.polyTerms(polyCount - 1)
                    Dim thisTerm = lhs.polyTerms(thisCount - 1)
                    If thisTerm.Exponent = polyTerm.Exponent Then
                        Dim t = thisTerm + polyTerm
                        If t.Coefficient <> 0 Then
                            terms.Add(t)
                        End If
                        thisCount -= 1
                        polyCount -= 1
                    ElseIf thisTerm.Exponent < polyTerm.Exponent Then
                        terms.Add(thisTerm)
                        thisCount -= 1
                    Else
                        terms.Add(polyTerm)
                        polyCount -= 1
                    End If
                End If
            End While
            Return New Polynomial(terms)
        End Operator

        Public Shared Operator *(lhs As Polynomial, rhs As Polynomial) As Polynomial
            Throw New Exception("Not implemented")
        End Operator

        Public Shared Operator /(lhs As Polynomial, rhs As Polynomial) As Polynomial
            Dim q As New Polynomial
            Dim r = lhs
            Dim lcv = rhs.LeadingCoeficient
            Dim dv = rhs.Degree
            While r.Degree >= rhs.Degree
                Dim lcr = r.LeadingCoeficient
                Dim s = lcr \ lcv
                Dim t As New Term(s, r.Degree() - dv)
                q += t
                r += rhs * -t
            End While
            Return q
        End Operator

        Public Overrides Function ToString() As String
            Dim builder As New StringBuilder
            Dim it = polyTerms.GetEnumerator()
            If it.MoveNext Then
                builder.Append(it.Current)
            End If
            While it.MoveNext
                If it.Current.Coefficient < 0 Then
                    builder.Append(" - ")
                    builder.Append(-it.Current)
                Else
                    builder.Append(" + ")
                    builder.Append(it.Current)
                End If
            End While
            Return builder.ToString
        End Function
    End Class

    Function GetDivisors(number As Integer) As List(Of Integer)
        Dim divisors As New List(Of Integer)
        Dim root = CType(Math.Sqrt(number), Long)
        For i = 1 To root
            If number Mod i = 0 Then
                divisors.Add(i)
                Dim div = number \ i
                If div <> i AndAlso div <> number Then
                    divisors.Add(div)
                End If
            End If
        Next
        Return divisors
    End Function

    Private ReadOnly allFactors As New Dictionary(Of Integer, Dictionary(Of Integer, Integer)) From {{2, New Dictionary(Of Integer, Integer) From {{2, 1}}}}
    Function GetFactors(number As Integer) As Dictionary(Of Integer, Integer)
        If allFactors.ContainsKey(number) Then
            Return allFactors(number)
        End If

        Dim factors As New Dictionary(Of Integer, Integer)
        If number Mod 2 = 0 Then
            Dim factorsDivTwo = GetFactors(number \ 2)
            For Each pair In factorsDivTwo
                If Not factors.ContainsKey(pair.Key) Then
                    factors.Add(pair.Key, pair.Value)
                End If
            Next
            If factors.ContainsKey(2) Then
                factors(2) += 1
            Else
                factors.Add(2, 1)
            End If
            If number < MAX_ALL_FACTORS Then
                allFactors.Add(number, factors)
            End If
            Return factors
        End If
        Dim root = CType(Math.Sqrt(number), Long)
        Dim i = 3L
        While i <= root
            If number Mod i = 0 Then
                Dim factorsDivI = GetFactors(number \ i)
                For Each pair In factorsDivI
                    If Not factors.ContainsKey(pair.Key) Then
                        factors.Add(pair.Key, pair.Value)
                    End If
                Next
                If factors.ContainsKey(i) Then
                    factors(i) += 1
                Else
                    factors.Add(i, 1)
                End If
                If number < MAX_ALL_FACTORS Then
                    allFactors.Add(number, factors)
                End If
                Return factors
            End If
            i += 2
        End While
        factors.Add(number, 1)
        If number < MAX_ALL_FACTORS Then
            allFactors.Add(number, factors)
        End If
        Return factors
    End Function

    Private ReadOnly computedPolynomials As New Dictionary(Of Integer, Polynomial)
    Function CyclotomicPolynomial(n As Integer) As Polynomial
        If computedPolynomials.ContainsKey(n) Then
            Return computedPolynomials(n)
        End If

        If n = 1 Then
            REM polynomial: x - 1
            Dim p As New Polynomial(New Term(1, 1), New Term(-1))
            computedPolynomials.Add(n, p)
            Return p
        End If

        Dim factors = GetFactors(n)
        Dim terms As New List(Of Term)
        Dim cyclo As Polynomial

        If factors.ContainsKey(n) Then
            REM n prime
            For index = 1 To n
                terms.Add(New Term(1, index - 1))
            Next

            cyclo = New Polynomial(terms)
            computedPolynomials.Add(n, cyclo)
            Return cyclo
        ElseIf factors.Count = 2 AndAlso factors.ContainsKey(2) AndAlso factors(2) = 1 AndAlso factors.ContainsKey(n / 2) AndAlso factors(n / 2) = 1 Then
            REM n = 2p
            Dim prime = n \ 2
            Dim coeff = -1

            For index = 1 To prime
                coeff *= -1
                terms.Add(New Term(coeff, index - 1))
            Next

            cyclo = New Polynomial(terms)
            computedPolynomials.Add(n, cyclo)
            Return cyclo
        ElseIf factors.Count = 1 AndAlso factors.ContainsKey(2) Then
            REM n = 2^h
            Dim h = factors(2)
            terms = New List(Of Term) From {
                New Term(1, Math.Pow(2, h - 1)),
                New Term(1)
            }

            cyclo = New Polynomial(terms)
            computedPolynomials.Add(n, cyclo)
            Return cyclo
        ElseIf factors.Count = 1 AndAlso factors.ContainsKey(n) Then
            REM n = p^k
            Dim p = 0
            Dim k = 0
            For Each it In factors
                p = it.Key
                k = it.Value
            Next
            For index = 1 To p
                terms.Add(New Term(1, (index - 1) * Math.Pow(p, k - 1)))
            Next

            cyclo = New Polynomial(terms)
            computedPolynomials.Add(n, cyclo)
            Return cyclo
        ElseIf factors.Count = 2 AndAlso factors.ContainsKey(2) Then
            REM n = 2^h * p^k
            Dim p = 0
            For Each it In factors
                If it.Key <> 2 Then
                    p = it.Key
                End If
            Next

            Dim coeff = -1
            Dim twoExp = CType(Math.Pow(2, factors(2) - 1), Long)
            Dim k = factors(p)
            For index = 1 To p
                coeff *= -1
                terms.Add(New Term(coeff, (index - 1) * twoExp * Math.Pow(p, k - 1)))
            Next

            cyclo = New Polynomial(terms)
            computedPolynomials.Add(n, cyclo)
            Return cyclo
        ElseIf factors.ContainsKey(2) AndAlso (n / 2) Mod 2 = 1 AndAlso n / 2 > 1 Then
            REM CP(2m)[x] = CP(-m)[x], n odd integer > 1
            Dim cycloDiv2 = CyclotomicPolynomial(n \ 2)
            For Each t In cycloDiv2
                If t.Exponent Mod 2 = 0 Then
                    terms.Add(t)
                Else
                    terms.Add(-t)
                End If
            Next

            cyclo = New Polynomial(terms)
            computedPolynomials.Add(n, cyclo)
            Return cyclo
        End If

#If ALGORITHM = 0 Then
        REM slow - uses basic definition
        Dim divisors = GetDivisors(n)
        REM Polynomial: (x^n - 1)
        cyclo = New Polynomial(New Term(1, n), New Term(-1))
        For Each i In divisors
            Dim p = CyclotomicPolynomial(i)
            cyclo /= p
        Next

        computedPolynomials.Add(n, cyclo)
        Return cyclo
#ElseIf ALGORITHM = 1 Then
        REM Faster.  Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
        Dim divisors = GetDivisors(n)
        Dim maxDivisor = Integer.MinValue
        For Each div In divisors
            maxDivisor = Math.Max(maxDivisor, div)
        Next
        Dim divisorExceptMax As New List(Of Integer)
        For Each div In divisors
            If maxDivisor Mod div <> 0 Then
                divisorExceptMax.Add(div)
            End If
        Next

        REM Polynomial:  ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
        cyclo = New Polynomial(New Term(1, n), New Term(-1)) / New Polynomial(New Term(1, maxDivisor), New Term(-1))
        For Each i In divisorExceptMax
            Dim p = CyclotomicPolynomial(i)
            cyclo /= p
        Next

        computedPolynomials.Add(n, cyclo)
        Return cyclo
#ElseIf ALGORITHM = 2 Then
        REM Fastest
        REM Let p ; q be primes such that p does not divide n, and q divides n
        REM Then Cp(np)[x] = CP(n)[x^p] / CP(n)[x]
        Dim m = 1
        cyclo = CyclotomicPolynomial(m)
        Dim primes As New List(Of Integer)
        For Each it In factors
            primes.Add(it.Key)
        Next
        primes.Sort()
        For Each prime In primes
            REM CP(m)[x]
            Dim cycloM = cyclo
            REM Compute CP(m)[x^p]
            terms = New List(Of Term)
            For Each t In cyclo
                terms.Add(New Term(t.Coefficient, t.Exponent * prime))
            Next
            cyclo = New Polynomial(terms) / cycloM
            m *= prime
        Next
        REM Now, m is the largest square free divisor of n
        Dim s = n \ m
        REM Compute CP(n)[x] = CP(m)[x^s]
        terms = New List(Of Term)
        For Each t In cyclo
            terms.Add(New Term(t.Coefficient, t.Exponent * s))
        Next

        cyclo = New Polynomial(terms)
        computedPolynomials.Add(n, cyclo)
        Return cyclo
#Else
        Throw New Exception("Invalid algorithm")
#End If
    End Function

    Sub Main()
        Console.WriteLine("Task 1:  cyclotomic polynomials for n <= 30:")
        For i = 1 To 30
            Dim p = CyclotomicPolynomial(i)
            Console.WriteLine("CP[{0}] = {1}", i, p)
        Next
        Console.WriteLine()

        Console.WriteLine("Task 2:  Smallest cyclotomic polynomial with n or -n as a coefficient:")
        Dim n = 0
        For i = 1 To 10
            While True
                n += 1
                Dim cyclo = CyclotomicPolynomial(n)
                If cyclo.HasCoefficentAbs(i) Then
                    Console.WriteLine("CP[{0}] has coefficient with magnitude = {1}", n, i)
                    n -= 1
                    Exit While
                End If
            End While
        Next
    End Sub

End Module


object Cusip extends App {

  val candidates = Seq("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")

  for (candidate <- candidates)
    printf(f"$candidate%s -> ${if (isCusip(candidate)) "correct" else "incorrect"}%s%n")

  private def isCusip(s: String): Boolean = {
    if (s.length != 9) false
    else {
      var sum = 0
      for (i <- 0 until 7) {
        val c = s(i)
        var v = 0
        if (c >= '0' && c <= '9') v = c - 48
        else if (c >= 'A' && c <= 'Z') v = c - 55 // lower case letters apparently invalid
        else if (c == '*') v = 36
        else if (c == '@') v = 37
        else if (c == '#') v = 38
        else return false
        if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing
        sum += v / 10 + v % 10
      }
      s(8) - 48 == (10 - (sum % 10)) % 10
    }
  }

}


#!/usr/local/bin/snobol4 -r
*  cusip.sno
*   -- Committee on Uniform Security Identification Procedures
*  -r : read data placed after the end label.
*  Verify check digit and size of cusip code.

     define("cusipt()i")                  :(cusipt_end)
cusipt
     chars = &digits &ucase "*@#"
     cusipt = table()
     i = 0
cusipt_1
     chars pos(i) len(1) . c              :f(return)
     cusipt[c] = i
     i = i + 1                            :(cusipt_1)
cusipt_end

     define("check_cusip(line)c,i")       :(check_cusip_end)
check_cusip
     eq(size(line), 9)                    :f(freturn)
     check_cusip = 0
     i = 0
check_cusip_1
     line pos(i) len(1) . c
     value = t[c]
     value = eq(remdr(i, 2), 1) t[c] * 2
     check_cusip = check_cusip + (value / 10) + remdr(value, 10)
     i = lt(i, 7) i + 1                   :s(check_cusip_1)
     check_cusip = remdr(10 - remdr(check_cusip, 10), 10)
     eq(substr(line, 9, 1), check_cusip)  :s(return)f(freturn)
check_cusip_end

*** main ***
     t = cusipt()

read line = input                         :f(end)
     check_cusip(line)                    :f(bad_cusip)
     output = line " valid."              :(read)
bad_cusip
     output =  line " not valid."         :(read)
end
037833100
17275R102
38259P508
594918104
68389X106
68389X105
68389X10
68389X1059
68389x105


USING: accessors io kernel math math.functions math.parser
sequences ;
IN: standard-deviator

TUPLE: standard-deviator sum sum^2 n ;

: <standard-deviator> ( -- standard-deviator )
    0.0 0.0 0 standard-deviator boa ;

: current-std ( standard-deviator -- std )
    [ [ sum^2>> ] [ n>> ] bi / ]
    [ [ sum>> ] [ n>> ] bi / sq ] bi - sqrt ;

: add-value ( value standard-deviator -- )
    [ nip [ 1 + ] change-n drop ]
    [ [ + ] change-sum drop ]
    [ [ [ sq ] dip + ] change-sum^2 drop ] 2tri ;

: main ( -- )
    { 2 4 4 4 5 5 7 9 }
    <standard-deviator> [ [ add-value ] curry each ] keep
    current-std number>string print ;


: f+! ( x addr -- ) dup [email protected] f+ f! ;

: st-count ( stats -- n )                  [email protected] ;
: st-sum   ( stats -- sum )       float+   [email protected] ;
: st-sumsq ( stats -- sum*sum ) 2 floats + [email protected] ;

: st-mean ( stats -- mean )
  dup st-sum st-count f/ ;

: st-variance ( stats -- var )
  dup st-sumsq
  dup st-mean fdup f* dup st-count f*  f-
  st-count f/ ;

: st-stddev ( stats -- stddev )
  st-variance fsqrt ;

: st-add ( fnum stats -- )
  dup
    1e dup f+!  float+
  fdup dup f+!  float+
  fdup f*  f+!
  std-stddev ;


import "/trait" for Stepped
import "/sort" for Sort
import "/math" for Int, Nums
import "/fmt" for Fmt

var algo = 2
var maxAllFactors = 1e5

class Term {
    construct new(coef, exp) {
        _coef = coef
        _exp = exp
    }

    coef { _coef }
    exp  { _exp }

    *(t) { Term.new(_coef * t.coef, _exp + t.exp) }

    +(t) {
        if (_exp != t.exp) Fiber.abort("Exponents unequal in term '+' method.")
        return Term.new(_coef + t.coef, _exp)
    }

    - { Term.new(-_coef, _exp) }

    toString {
        if (_coef == 0) return "0"
        if (_exp == 0)  return _coef.toString
        if (_coef == 1) return (_exp == 1) ? "x" : "x^%(_exp)"
        if (_exp == 1)  return "%(_coef)x"
        return "%(_coef)x^%(_exp)"
    }
}

class Poly {
    // pass coef, exp in pairs as parameters
    construct new(values) {
        var le = values.count
        if (le == 0) {
            _terms = [Term.new(0, 0)]
        } else {
            if (le%2 != 0) Fiber.abort("Odd number of parameters(%(le)) passed to Poly constructor.")
            _terms = []
            for (i in Stepped.new(0...le, 2)) _terms.add(Term.new(values[i], values[i+1]))
            tidy()
        }
    }

    terms { _terms }

    hasCoefAbs(coef) { _terms.any { |t| t.coef.abs == coef } }

    +(p2) {
        var p3 = Poly.new([])
        var le = _terms.count
        var le2 = p2.terms.count
        while (le > 0 || le2 > 0) {
            if (le == 0) {
                p3.terms.add(p2.terms[le2-1])
                le2 = le2 - 1
            } else if (le2 == 0) {
                p3.terms.add(_terms[le-1])
                le = le - 1
            } else {
                var t = _terms[le-1]
                var t2 = p2.terms[le2-1]
                if (t.exp == t2.exp) {
                    var t3 = t + t2
                    if (t3.coef != 0) p3.terms.add(t3)
                    le = le - 1
                    le2 = le2 - 1
                } else if (t.exp < t2.exp) {
                    p3.terms.add(t)
                    le = le - 1
                } else {
                    p3.terms.add(t2)
                    le2 = le2 - 1
                }
            }
        }
        p3.tidy()
        return p3
    }

    addTerm(t) {
        var q = Poly.new([])
        var added = false
        for (i in 0..._terms.count) {
            var ct = _terms[i]
            if (ct.exp == t.exp) {
                added = true
                if (ct.coef + t.coef != 0) q.terms.add(ct + t)
            } else {
                q.terms.add(ct)
            }
        }
        if (!added) q.terms.add(t)
        q.tidy()
        return q
    }

    mulTerm(t) {
        var q = Poly.new([])
        for (i in 0..._terms.count) {
            var ct = _terms[i]
            q.terms.add(ct * t)
        }
        q.tidy()
        return q
    }

    /(v) {
        var p = this
        var q = Poly.new([])
        var lcv = v.leadingCoef
        var dv = v.degree
        while (p.degree >= v.degree) {
            var lcp = p.leadingCoef
            var s = (lcp/lcv).truncate
            var t = Term.new(s, p.degree - dv)
            q = q.addTerm(t)
            p = p + v.mulTerm(-t)
        }
        q.tidy()
        return q
    }

    leadingCoef { _terms[0].coef }

    degree { _terms[0].exp }

    toString {
        var sb = ""
        var first = true
        for (t in _terms) {
            if (first) {
                sb = sb + t.toString
                first = false
            } else {
                sb = sb + " "
                if (t.coef > 0) {
                    sb = sb + "+ "
                    sb = sb + t.toString
                } else {
                    sb = sb + "- "
                    sb = sb + (-t).toString
                }
            }
        }
        return sb
    }

    // in place descending sort by term.exp
    sortTerms() {
        var cmp  = Fn.new { |t1, t2| (t2.exp - t1.exp).sign }
        Sort.quick(_terms, 0, _terms.count-1, cmp)
    }

    // sort terms and remove any unnecesary zero terms
    tidy() {
        sortTerms()
        if (degree > 0) {
            for (i in _terms.count-1..0) {
                if (_terms[i].coef == 0) _terms.removeAt(i)
            }
            if (_terms.count == 0) _terms.add(Term.new(0, 0))
        }
    }
}

var computed = {}
var allFactors = {2: {2: 1}}

var getFactors // recursive function
getFactors = Fn.new { |n|
    var f = allFactors[n]
    if (f) return f
    var factors = {}
    if (n%2 == 0) {
        var factorsDivTwo = getFactors.call(n/2)
        for (me in factorsDivTwo) factors[me.key] = me.value
        factors[2] = factors[2] ? factors[2] + 1 : 1
        if (n < maxAllFactors) allFactors[n] = factors
        return factors
    }
    var prime = true
    var sqrt = n.sqrt.floor
    var i = 3
    while (i <= sqrt){
        if (n%i == 0) {
            prime = false
            for (me in getFactors.call(n/i)) factors[me.key] = me.value
            factors[i] = factors[i] ? factors[i] + 1 : 1
            if (n < maxAllFactors) allFactors[n] = factors
            return factors
        }
        i = i + 2
    }
    if (prime) {
        factors[n] = 1
        if (n < maxAllFactors) allFactors[n] = factors
    }
    return factors
}

var cycloPoly // recursive function
cycloPoly = Fn.new { |n|
    var p = computed[n]
    if (p) return p
    if (n == 1) {
        // polynomialL x - 1
        p = Poly.new([1, 1, -1, 0])
        computed[1] = p
        return p
    }
    var factors = getFactors.call(n)
    var cyclo = Poly.new([])
    if (factors[n]) {
        // n is prime
        for (i in 0...n) cyclo.terms.add(Term.new(1, i))
    } else if (factors.count == 2 && factors[2] == 1 && factors[n/2] == 1) {
        // n == 2p
        var prime = n / 2
        var coef = -1
        for (i in 0...prime) {
            coef = coef * (-1)
            cyclo.terms.add(Term.new(coef, i))
        }
    } else if (factors.count == 1) {
        var h = factors[2]
        if (h) { // n == 2^h
            cyclo.terms.addAll([Term.new(1, 1 << (h-1)), Term.new(1, 0)])
        } else if (!factors[n]) {
            // n == p ^ k
           var p = 0
           for (prime in factors.keys) p = prime
           var k = factors[p]
           for (i in 0...p) {
                var pk = p.pow(k-1).floor
                cyclo.terms.add(Term.new(1, i * pk))
           }
        }
    } else if (factors.count == 2 && factors[2]) {
        // n = 2^h * p^k
        var p = 0
        for (prime in factors.keys) if (prime != 2) p = prime
        var coef = -1
        var twoExp = 1 << (factors[2] - 1)
        var k = factors[p]
        for (i in 0...p) {
            coef = coef * (-1)
            var pk = p.pow(k-1).floor
            cyclo.terms.add(Term.new(coef, i * twoExp * pk))
        }
    } else if (factors[2] && (n/2) % 2 == 1 && (n/2) > 1) {
        //  CP(2m)[x] == CP(-m)[x], n odd integer > 1
        var cycloDiv2 = cycloPoly.call(n/2)
        for (t in cycloDiv2.terms) {
            var t2 = t
            if (t.exp % 2 != 0) t2 = -t
            cyclo.terms.add(t2)
        }
    } else if (algo == 0) {
        // slow - uses basic definition
        var divs = Int.properDivisors(n)
        // polynomial: x^n - 1
        var cyclo = Poly.new([1, n, -1, 0])
        for (i in divs) {
            var p = cycloPoly.call(i)
            cyclo = cyclo / p
        }
    } else if (algo == 1) {
        //  faster - remove max divisor (and all divisors of max divisor)
        //  only one divide for all divisors of max divisor
        var divs = Int.properDivisors(n)
        var maxDiv = Nums.max(divs)
        var divsExceptMax = divs.where { |d| maxDiv % d != 0 }.toList
        // polynomial:  ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
        cyclo = Poly.new([1, n, -1, 0])
        cyclo = cyclo / Poly.new([1, maxDiv, -1, 0])
        for (i in divsExceptMax) {
            var p = cycloPoly.call(i)
            cyclo = cyclo / p
        }
    } else if (algo == 2) {
        //  fastest
        //  let p, q be primes such that p does not divide n, and q divides n
        //  then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
        var m = 1
        cyclo = cycloPoly.call(m)
        var primes = []
        for (prime in factors.keys) primes.add(prime)
        Sort.quick(primes)
        for (prime in primes) {
            // CP(m)[x]
            var cycloM = cyclo
            // compute CP(m)[x^p]
            var terms = []
            for (t in cycloM.terms) terms.add(Term.new(t.coef, t.exp * prime))
            cyclo = Poly.new([])
            cyclo.terms.addAll(terms)
            cyclo.tidy()
            cyclo = cyclo / cycloM
            m = m * prime
        }
        //  now, m is the largest square free divisor of n
        var s = n / m
        //  Compute CP(n)[x] = CP(m)[x^s]
        var terms = []
        for (t in cyclo.terms) terms.add(Term.new(t.coef, t.exp * s))
        cyclo = Poly.new([])
        cyclo.terms.addAll(terms)
    } else {
        Fiber.abort("Invalid algorithm.")
    }
    cyclo.tidy()
    computed[n] = cyclo
    return cyclo
}

System.print("Task 1:  cyclotomic polynomials for n <= 30:")
for (i in 1..30) {
    var p = cycloPoly.call(i)
    Fmt.print("CP[$2d] = $s", i, p)
}

System.print("\nTask 2:  Smallest cyclotomic polynomial with n or -n as a coefficient:")
var n = 0
for (i in 1..7) {
     while(true) {
        n = n + 1
        var cyclo = cycloPoly.call(n)
        if (cyclo.hasCoefAbs(i)) {
            Fmt.print("CP[$d] has coefficient with magnitude = $d", n, i)
            n = n - 1
            break
        }
    }
}


struct CUSIP {
  var value: String

  private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

  init?(value: String) {
    if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) {
      self.value = value
    } else if value.count == 8, let checkDigit = CUSIP.checkDigit(cusipString: value) {
      self.value = value + checkDigit
    } else {
      return nil
    }
  }

  static func checkDigit(cusipString: String) -> String? {
    guard cusipString.count == 8, cusipString.allSatisfy({ $0.isASCII }) else {
      return nil
    }

    let sum = cusipString.uppercased().enumerated().reduce(0, {sum, pair in
      let (i, char) = pair
      var v: Int

      switch char {
      case "*":
        v = 36
      case "@":
        v = 37
      case "#":
        v = 38
      case _ where char.isNumber:
        v = char.wholeNumberValue!
      case _:
        v = Int(char.asciiValue! - 65) + 10
      }

      if i & 1 == 1 {
        v *= 2
      }

      return sum + (v / 10) + (v % 10)
    })

    return String((10 - (sum % 10)) % 10)
  }
}

let testCases = [
  "037833100",
  "17275R102",
  "38259P508",
  "594918104",
  "68389X106",
  "68389X105"
]

for potentialCUSIP in testCases {
  print("\(potentialCUSIP) -> ", terminator: "")

  switch CUSIP(value: potentialCUSIP) {
  case nil:
    print("Invalid")
  case _:
    print("Valid")
  }
}


proc ordinal-of-alpha {c} {                     ;#  returns ordinal position of c in the alphabet (A=1, B=2...)
    lsearch {_ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z} [string toupper $c]
}

proc Cusip-Check-Digit {cusip} {                ;# algorithm Cusip-Check-Digit(cusip) is
    if {[string length $cusip] != 8} {          ;#    Input: an 8-character CUSIP
        return false
    }

    set sum 0                                   ;#    sum := 0
    for {set i 1} {$i <= 8} {incr i} {          ;#    for 1 ≤ i ≤ 8 do
        set c [string index $cusip $i-1]        ;#       c := the ith character of cusip
        if {[string is digit $c]} {             ;#       if c is a digit then
            set v $c                            ;#          v := numeric value of the digit c
        } elseif {[string is alpha $c]} {       ;#       else if c is a letter then
            set p [ordinal-of-alpha $c]         ;#          p := ordinal position of c in the alphabet (A=1, B=2...)
            set v [expr {$p + 9}]               ;#          v := p + 9
        } elseif {$c eq "*"} {                  ;#       else if c = "*" then
            set v 36                            ;#          v := 36
        } elseif {$c eq "@"} {                  ;#       else if c = "@" then
            set v 37                            ;#          v := 37
        } elseif {$c eq "#"} {                  ;#       else if c = "#" then
            set v 38                            ;#          v := 38
        }                                       ;#       end if
        if {$i % 2 == 0} {                      ;#       if i is even then
            set v [expr {$v * 2}]               ;#          v := v × 2
        }                                       ;#       end if

        incr sum [expr {$v / 10 + $v % 10}]     ;#       sum := sum + int ( v div 10 ) + v mod 10
    }                                           ;#    repeat

    expr {(10 - ($sum % 10)) % 10}              ;#    return (10 - (sum mod 10)) mod 10
}
proc check-cusip {cusip} {
    set last  [string index $cusip end]
    set cusip [string range $cusip 0 end-1]
    expr {$last eq [Cusip-Check-Digit $cusip]}
}


program standard_deviation
  implicit none
  integer(kind=4), parameter :: dp = kind(0.0d0)

  real(kind=dp), dimension(:), allocatable :: vals
  integer(kind=4) :: i

  real(kind=dp), dimension(8) :: sample_data = (/ 2, 4, 4, 4, 5, 5, 7, 9 /)

  do i = lbound(sample_data, 1), ubound(sample_data, 1)
    call sample_add(vals, sample_data(i))
    write(*, fmt='(''#'',I1,1X,''value = '',F3.1,1X,''stddev ='',1X,F10.8)') &
      i, sample_data(i), stddev(vals)
  end do

  if (allocated(vals)) deallocate(vals)
contains
  ! Adds value :val: to array :population: dynamically resizing array
  subroutine sample_add(population, val)
    real(kind=dp), dimension(:), allocatable, intent (inout) :: population
    real(kind=dp), intent (in) :: val

    real(kind=dp), dimension(:), allocatable :: tmp
    integer(kind=4) :: n

    if (.not. allocated(population)) then
      allocate(population(1))
      population(1) = val
    else
      n = size(population)
      call move_alloc(population, tmp)

      allocate(population(n + 1))
      population(1:n) = tmp
      population(n + 1) = val
    endif
  end subroutine sample_add

  ! Calculates standard deviation for given set of values
  real(kind=dp) function stddev(vals)
    real(kind=dp), dimension(:), intent(in) :: vals
    real(kind=dp) :: mean
    integer(kind=4) :: n

    n = size(vals)
    mean = sum(vals)/n
    stddev = sqrt(sum((vals - mean)**2)/n)
  end function stddev
end program standard_deviation


Private Function Cusip_Check_Digit(s As Variant) As Integer
    Dim Sum As Integer, c As String, v As Integer
    For i = 1 To 8
        c = Mid(s, i, 1)
        If IsNumeric(c) Then
            v = Val(c)
        Else
            Select Case c
                Case "a" To "z"
                    v = Asc(c) - Asc("a") + 10
                Case "A" To "Z"
                    v = Asc(c) - Asc("A") + 10
                Case "*"
                    v = 36
                Case "@"
                    v = 37
                Case "#"
                    v = 38
                Case Else
                    Debug.Print "not expected"
            End Select
        End If
        If i Mod 2 = 0 Then v = v * 2
        Sum = Sum + Int(v \ 10) + v Mod 10
    Next i
    Cusip_Check_Digit = (10 - (Sum Mod 10)) Mod 10
End Function


Module Module1

    Function IsCUSIP(s As String) As Boolean
        If s.Length <> 9 Then
            Return False
        End If

        Dim sum = 0
        For i = 0 To 7
            Dim c = s(i)

            Dim v As Integer
            If "0" <= c AndAlso c <= "9" Then
                v = Asc(c) - 48
            ElseIf "A" <= c AndAlso c <= "Z" Then
                v = Asc(c) - 55 ' Lower case letters are apparently invalid
            ElseIf c = "*" Then
                v = 36
            ElseIf c = "#" Then
                v = 38
            Else
                Return False
            End If

            If i Mod 2 = 1 Then
                v *= 2 ' check if odd as using 0-based indexing
            End If
            sum += v \ 10 + v Mod 10
        Next
        Return Asc(s(8)) - 48 = (10 - (sum Mod 10)) Mod 10
    End Function

    Sub Main()
        Dim candidates As New List(Of String) From {
            "037833100",
            "17275R102",
            "38259P508",
            "594918104",
            "68389X106",
            "68389X105"
        }

        For Each candidate In candidates
            Console.WriteLine("{0} -> {1}", candidate, If(IsCUSIP(candidate), "correct", "incorrect"))
        Next
    End Sub

End Module


' FB 1.05.0 Win64

Function calcStandardDeviation(number As Double) As Double
  Static a() As Double
  Redim Preserve a(0 To UBound(a) + 1)
  Dim ub As UInteger = UBound(a)
  a(ub) = number
  Dim sum As Double = 0.0
  For i As UInteger = 0 To ub
    sum += a(i)
  Next
  Dim mean As Double = sum / (ub + 1)
  Dim diff As Double
  sum  = 0.0
  For i As UInteger = 0 To ub
    diff = a(i) - mean
    sum += diff * diff
  Next
  Return Sqr(sum/ (ub + 1))
End Function

Dim a(0 To 7) As Double = {2, 4, 4, 4, 5, 5, 7, 9}

For i As UInteger = 0 To 7
  Print "Added"; a(i); " SD now : "; calcStandardDeviation(a(i))
Next

Print
Print "Press any key to quit"
Sleep


package main

import (
    "fmt"
    "math"
)

func newRsdv() func(float64) float64 {
    var n, a, q  float64
    return func(x float64) float64 {
        n++
        a1 := a+(x-a)/n
        q, a = q+(x-a)*(x-a1), a1
        return math.Sqrt(q/n)
    }
}

func main() {
    r := newRsdv()
    for _, x := range []float64{2,4,4,4,5,5,7,9} {
        fmt.Println(r(x))
    }
}


var isCusip = Fn.new { |s|
    if (s.count != 9) return false
    var sum = 0
    for (i in 0..7) {
        var c = s[i].bytes[0]
        var v
        if (c >= 48 && c <= 57) { // '0' to '9'
            v = c - 48
        } else if (c >= 65 && c <= 90) { // 'A' to 'Z'
            v = c - 55
        } else if (s[i] == "*") {
            v = 36
        } else if (s[i] == "@") {
            v = 37
        } else if (s[i] == "#") {
            v = 38
        } else {
            return false
        }
        if (i%2 == 1) v = v * 2 // check if odd as using 0-based indexing
        sum = sum + (v/10).floor + v%10
    }
    return s[8].bytes[0] - 48 == (10 - (sum%10)) % 10
}

var candidates = [
    "037833100",
    "17275R102",
    "38259P508",
    "594918104",
    "68389X106",
    "68389X105"
]
for (candidate in candidates) {
    var b = (isCusip.call(candidate)) ? "correct" : "incorrect"
    System.print("%(candidate) -> %(b)")
}


List samples = []

def stdDev = { def sample ->
    samples << sample
    def sum = samples.sum()
    def sumSq = samples.sum { it * it }
    def count = samples.size()
    (sumSq/count - (sum/count)**2)**0.5
}

[2,4,4,4,5,5,7,9].each {
    println "${stdDev(it)}"
}


{-# LANGUAGE BangPatterns #-}

import Data.List (foldl') -- '
import Data.STRef
import Control.Monad.ST

data Pair a b = Pair !a !b

sumLen :: [Double] -> Pair Double Double
sumLen = fiof2 . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) --'
  where fiof2 (Pair s l) = Pair s (fromIntegral l)

divl :: Pair Double Double -> Double
divl (Pair _ 0.0) = 0.0
divl (Pair s   l) = s / l

sd :: [Double] -> Double
sd xs = sqrt $ foldl' (\a x -> a+(x-m)^2) 0 xs / l --'
  where p@(Pair s l) = sumLen xs
        m = divl p

mkSD :: ST s (Double -> ST s Double)
mkSD = go <$> newSTRef []
  where go acc x =
          modifySTRef acc (x:) >> (sd <$> readSTRef acc)

main = mapM_ print $ runST $
  mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]


string 0;               \use zero-terminated strings

func    Valid(Cusip);   \Return 'true' if valid CUSIP code
char    Cusip;
int     Sum, I, C, V;
[Sum:= 0;
for I:= 0 to 8-1 do
        [C:= Cusip(I);
        ChOut(0, C);
        case of
          C>=^0 & C<=^9: V:= C-^0;
          C>=^A & C<=^Z: V:= C-^A+10;
          C=^*: V:=36;
          C=^@: V:=37;
          C=^#: V:=38
        other V:= -1;
        if I&1 then V:= V*2;
        Sum:= Sum + V/10 + rem(0);
        ];
C:= Cusip(I);
ChOut(0, C);
V:= rem( (10-rem(Sum/10)) / 10 );
return V = C-^0;
];

int Cusip, N;
[Cusip:= ["037833100",
          "17275R102",
          "38259P508",
          "594918104",
          "68389X106",
          "68389X105"];
for N:= 0 to 6-1 do
        [Text(0, if Valid(Cusip(N))
                then " is valid"
                else " is invalid");
        CrLf(0);
        ];
]


sub cusip(inputStr$)
    local i, v, sum, x$

    Print inputStr$;
    If Len(inputStr$) <> 9 Print " length is incorrect, invalid cusip" : return

    For i = 1 To 8
        x$ = mid$(inputStr$, i, 1)
        switch x$
            Case "*": v = 36 : break
            Case "@": v = 37 : break
            Case "#": v = 38 : break
            default:
                if x$ >= "A" and x$ <= "Z" then
                    v = asc(x$) - Asc("A") + 10
                elsif x$ >= "0" and x$ <= "9" then
                    v = asc(x$) - asc("0")
                else
                    Print " found a invalid character, invalid cusip"
                    return
                end if
        End switch

        If and(i, 1) = 0 v = v * 2
        sum = sum + int(v / 10) + mod(v, 10)
    Next

    sum = mod(10 - mod(sum, 10), 10)
    If sum = asc(mid$(inputStr$, 9, 1)) - Asc("0") Then
        Print " is valid"
    Else
        Print " is invalid"
    End If

End Sub

// ------=< MAIN >=------

Data "037833100", "17275R102", "38259P508"
Data "594918104", "68389X106", "68389X105", ""

Print
do
    Read inputStr$
    if inputStr$ = "" break
    cusip(inputStr$)
loop


const std = @import("std");
const print = std.debug.print;

pub fn CusipCheckDigit(cusip: *const [9:0]u8) bool {
    var i: usize = 0;
    var sum: i32 = 0;
    while (i < 8) {
        const c = cusip[i];
        var v: i32 = undefined;
        if (c <= '9' and c >= '0') {
            v = c - 48;
        }
        else if (c <= 'Z' and c >= 'A') {
            v = c - 55;
        }
        else if (c == '*') {
            v = 36;
        }
        else if (c == '@') {
            v = 37;
        }
        else if (c == '#') {
            v = 38;
        }
        else {
            return false;
        }
        if (i % 2 == 1) {
            v *= 2;
        }
        sum = sum + @divFloor(v, 10) + @mod(v, 10);
        i += 1;
    }
    return (cusip[8] - 48 == @mod((10 - @mod(sum, 10)), 10));
}

pub fn main() void {
    const cusips = [_]*const [9:0]u8 {
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105"
    };
    for (cusips) |cusip| {
        print("{s} -> {}\n", .{cusip, CusipCheckDigit(cusip)});
    }
}


fcn cusipCheckDigit(cusip){
   var [const] vs=[0..9].chain(["A".."Z"],T("*","@","#")).pump(String);
   try{
      sum:=Walker.cycle(1,2).zipWith(fcn(n,c){ v:=vs.index(c)*n; v/10 + v%10 },
           cusip[0,8]).reduce('+);
      ((10 - sum%10)%10 == cusip[8].toInt()) and cusip.len()==9
   }catch{ False }
}


using Lambda;

class Main {
	static function main():Void {
		var nums = [2, 4, 4, 4, 5, 5, 7, 9];
		for (i in 1...nums.length+1)
			Sys.println(sdev(nums.slice(0, i)));
	}

	static function average<T:Float>(nums:Array<T>):Float {
		return nums.fold(function(n, t) return n + t, 0) / nums.length;
	}

	static function sdev<T:Float>(nums:Array<T>):Float {
		var store = [];
		var avg = average(nums);
		for (n in nums) {
			store.push((n - avg) * (n - avg));
		}

		return Math.sqrt(average(store));
	}
}


REAL :: n=8, set(n), sum=0, sum2=0

set = (2,4,4,4,5,5,7,9)

DO k = 1, n
   WRITE() 'Adding ' // set(k) // 'stdev = ' // stdev(set(k))
ENDDO

END ! end of "main"

FUNCTION stdev(x)
   USE : sum, sum2, k
   sum = sum + x
   sum2 = sum2 + x*x
   stdev = ( sum2/k - (sum/k)^2) ^ 0.5
 END


procedure main()

stddev() # reset state / empty
every  s := stddev(![2,4,4,4,5,5,7,9]) do
   write("stddev (so far) := ",s)

end

procedure stddev(x)  # running standard deviation
static X,sumX,sum2X

   if /x then {   # reset state
      X := []
      sumX := sum2X := 0.
      }
   else {         # accumulate
      put(X,x)
      sumX +:= x
      sum2X +:= x^2
      return sqrt( (sum2X / *X) - (sumX / *X)^2 )
      }
end


100 PROGRAM "StDev.bas"
110 LET N=8
120 NUMERIC ARR(1 TO N)
130 FOR I=1 TO N
140   READ ARR(I)
150 NEXT
160 DEF STDEV(N)
170   LET S1,S2=0
180   FOR I=1 TO N
190     LET S1=S1+ARR(I)^2:LET S2=S2+ARR(I)
200   NEXT
210   LET STDEV=SQR((N*S1-S2^2)/N^2)
220 END DEF
230 FOR J=1 TO N
240   PRINT J;"item =";ARR(J),"standard dev =";STDEV(J)
250 NEXT
260 DATA 2,4,4,4,5,5,7,9


   mean=: +/ % #
   dev=: - mean
   stddevP=: [: %:@mean *:@dev          NB. A) 3 equivalent defs for stddevP
   stddevP=: [: mean&.:*: dev           NB. B) uses Under (&.:) to apply inverse of *: after mean
   stddevP=: %:@([email protected]:*: - *:@mean)    NB. C) sqrt of ((mean of squares) - (square of mean))

   stddevP\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2


public class StdDev {
    int n = 0;
    double sum = 0;
    double sum2 = 0;

    public double sd(double x) {
	n++;
	sum += x;
	sum2 += x*x;

	return Math.sqrt(sum2/n - sum*sum/n/n);
    }

    public static void main(String[] args) {
        double[] testData = {2,4,4,4,5,5,7,9};
        StdDev sd = new StdDev();

        for (double x : testData) {
            System.out.println(sd.sd(x));
        }
    }
}


function running_stddev() {
    var n = 0;
    var sum = 0.0;
    var sum_sq = 0.0;
    return function(num) {
        n++;
        sum += num;
        sum_sq += num*num;
        return Math.sqrt( (sum_sq / n) - Math.pow(sum / n, 2) );
    }
}

var sd = running_stddev();
var nums = [2,4,4,4,5,5,7,9];
var stddev = [];
for (var i in nums)
    stddev.push( sd(nums[i]) );

// using WSH
WScript.Echo(stddev.join(', ');


function makerunningstd(::Type{T} = Float64) where T
    ∑x = ∑x² = zero(T)
    n = 0
    function runningstd(x)
        ∑x  += x
        ∑x² += x ^ 2
        n   += 1
        s   = ∑x² / n - (∑x / n) ^ 2
        return s
    end
    return runningstd
end

test = Float64[2, 4, 4, 4, 5, 5, 7, 9]
rstd = makerunningstd()

println("Perform a running standard deviation of ", test)
for i in test
    println(" - add $i → ", rstd(i))
end


// version 1.0.5-2

class CumStdDev {
    private var n = 0
    private var sum = 0.0
    private var sum2 = 0.0

    fun sd(x: Double): Double {
        n++
        sum += x
        sum2 += x * x
        return Math.sqrt(sum2 / n - sum * sum / n / n)
    }
}

fun main(args: Array<String>) {
    val testData = doubleArrayOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0)
    val csd = CumStdDev()
    for (d in testData) println("Add $d => ${csd.sd(d)}")
}


PROC Save(CHAR ARRAY text)
  BYTE dev=[1]

  Close(dev)
  Open(dev,"C:",8,128)
  PrintE("Saving started...")
  PrintF("Saving text: ""%S""%E",text)
  PrintD(dev,text)
  Close(dev)
  PrintE("Saving finished.")
RETURN

PROC Load()
  CHAR ARRAY result(255)
  BYTE dev=[1]

  Close(dev)
  Open(dev,"C:",4,128)
  PrintE("Loading started...")
  WHILE Eof(dev)=0
  DO
    InputSD(dev,result)
    PrintF("Loading text: ""%S""%E",result)
  OD
  Close(dev)
  PrintE("Loading finished.")
RETURN

PROC Main()
  BYTE CH=$02FC ;Internal hardware value for last key pressed

  PrintE("Press any key to save a file on tape.")
  Save("Atari Action!")

  PutE()
  PrintE("Rewind the tape and press any key to load previously saved file from tape.")
  Load()
RETURN


write "TAPE.FILE" {
    This code
    should be able to write
    a file
    to magnetic tape
}


    dim SD.storage$( 100)   '   can call up to 100 versions, using ID to identify.. arrays are global.
                            '   holds (space-separated) number of data items so far, current sum.of.values and current sum.of.squares

    for i =1 to 8
        read x
        print "New data "; x; " so S.D. now = "; using( "###.######", standard.deviation( 1, x))
    next i

    end

function standard.deviation( ID, in)
  if SD.storage$( ID) ="" then SD.storage$( ID) ="0 0 0"
  num.so.far =val( word$( SD.storage$( ID), 1))
  sum.vals   =val( word$( SD.storage$( ID), 2))
  sum.sqs    =val( word$( SD.storage$( ID), 3))
  num.so.far =num.so.far +1
  sum.vals   =sum.vals   +in
  sum.sqs    =sum.sqs    +in^2

  ' standard deviation = square root of (the average of the squares less the square of the average)
  standard.deviation   =(               ( sum.sqs /num.so.far)      -    ( sum.vals /num.so.far)^2)^0.5

  SD.storage$( ID) =str$( num.so.far) +" " +str$( sum.vals) +" " +str$( sum.sqs)
end function

    Data 2, 4, 4, 4, 5, 5, 7, 9


// Stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232

class Stats:
    M = 0.0
    S = 0.0
    n = 0
    def incl(x):
        n += 1
        if n == 1:
            M = x
        else:
            let mm = (x - M)
            M += mm / n
            S += mm * (x - M)
    def mean(): return M
    //def variance(): return (if n > 1.0: S / (n - 1.0) else: 0.0) // Bessel's correction
    def variance(): return (if n > 0.0: S / n else: 0.0)
    def stddev(): return sqrt(variance())
    def count(): return n

def test_stdv() -> float:
    let v = [2,4,4,4,5,5,7,9]
    let s = Stats {}
    for(v) x: s.incl(x+0.0)
    print concat_string(["Mean: ", string(s.mean()), ", Std.Deviation: ", string(s.stddev())], "")

test_stdv()


#include<stdio.h>

int main()
{
	FILE* fp = fopen("TAPE.FILE","w");

	fprintf(fp,"This code should be able to write a file to magnetic tape.\n");
	fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n");
	fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n");
	fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n");
	fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n");
	fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n");
	fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n");
	fprintf(fp,"EOF");

	fclose(fp);

	return 0;
}


#include <iostream>
#include <fstream>

#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif

int main() {
    std::filebuf fb;
    fb.open(FILENAME,std::ios::out);
    std::ostream os(&fb);
    os << "Hello World\n";
    fb.close();
    return 0;
}


       >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. MAKE-TAPE-FILE.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT TAPE-FILE
        ASSIGN "./TAPE.FILE"
        ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD TAPE-FILE.
01 TAPE-FILE-RECORD PIC X(51).

PROCEDURE DIVISION.
    OPEN OUTPUT SHARING WITH ALL OTHER TAPE-FILE
    WRITE TAPE-FILE-RECORD
        FROM "COBOL treats tape files and text files identically."
    END-WRITE
    STOP RUN.


filename = {% if flag?(:win32) %}
    "TAPE.FILE"
  {% else %}
    "/dev/tape"
  {% end %}
File.write filename, "howdy, planet!"


function stdev()
  local sum, sumsq, k = 0,0,0
  return function(n)
    sum, sumsq, k = sum + n, sumsq + n^2, k+1
    return math.sqrt((sumsq / k) - (sum/k)^2)
  end
end

ldev = stdev()
for i, v in ipairs{2,4,4,4,5,5,7,9} do
  print(ldev(v))
end


runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}];StandardDeviation[AppendTo[$Data, n]])


import std.stdio;

void main() {
    version(Windows) {
        File f = File("TAPE.FILE", "w");
    } else {
        File f = File("/dev/tape", "w");
    }
    f.writeln("Hello World!");
}


program Create_a_file_on_magnetic_tape;

{$APPTYPE CONSOLE}

const
{$IFDEF WIN32}
  FileName = 'tape.file';
{$ELSE}
  FileName = '/dev/tape';
{$ENDIF}

var
  f: TextFile;

begin
  Assign(f, FileName);
  Rewrite(f);
  Writeln(f, 'Hello World');
  close(f);
end.


open System
open System.IO

let env = Environment.OSVersion.Platform
let msg = "Hello Rosetta!"

match env with
    | PlatformID.Win32NT | PlatformID.Win32S | PlatformID.Win32Windows | PlatformID.WinCE -> File.WriteAllText("TAPE.FILE", msg)
    | _ -> File.WriteAllText("/dev/tape", msg)


USING: io.encodings.ascii io.files kernel system ;

"Hello from Rosetta Code!"
os windows? "tape.file" "/dev/tape" ?
ascii set-file-contents


Dim As Integer numarch = Freefile
Open "tape.file" For Output As #numarch
Print #numarch, "Soy un archivo de cinta ahora, o espero serlo pronto."
Close #numarch


package main

import (
        "archive/tar"
        "compress/gzip"
        "flag"
        "io"
        "log"
        "os"
        "time"
)

func main() {
        filename := flag.String("file", "TAPE.FILE", "filename within TAR")
        data := flag.String("data", "", "data for file")
        outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
        gzipFlag := flag.Bool("gzip", false, "use gzip compression")
        flag.Parse()

        var w io.Writer = os.Stdout
        if *outfile != "" {
                f, err := os.Create(*outfile)
                if err != nil {
                        log.Fatalf("opening/creating %q: %v", *outfile, err)
                }
                defer f.Close()
                w = f
        }

        if *gzipFlag {
                zw := gzip.NewWriter(w)
                defer zw.Close()
                w = zw
        }

        tw := tar.NewWriter(w)
        defer tw.Close()
        w = tw
        tw.WriteHeader(&tar.Header{
                Name:     *filename,
                Mode:     0660,
                Size:     int64(len(*data)),
                ModTime:  time.Now(),
                Typeflag: tar.TypeReg,
                Uname:    "guest",
                Gname:    "guest",
        })

        _, err := w.Write([]byte(*data))
        if err != nil {
                log.Fatal("writing data:", err)
        }
}


StdDeviator = {}
StdDeviator.count = 0
StdDeviator.sum = 0
StdDeviator.sumOfSquares = 0

StdDeviator.add = function(x)
    self.count = self.count + 1
    self.sum = self.sum + x
    self.sumOfSquares = self.sumOfSquares + x*x
end function

StdDeviator.stddev = function()
    m = self.sum / self.count
    return sqrt(self.sumOfSquares / self.count - m*m)
end function

sd = new StdDeviator
for x in [2, 4, 4, 4, 5, 5, 7, 9]
    sd.add x
end for
print sd.stddev


0	П4	П5	П6	С/П	П0	ИП5	+	П5	ИП0
x^2	ИП6	+	П6	КИП4	ИП6	ИП4	/	ИП5	ИП4
/	x^2	-	КвКор	БП	04


class StdDev
	declare n
	declare sum
	declare sum2

	def StdDev()
		n = 0
		sum = 0
		sum2 = 0
	end

	def sd(x)
		this.n += 1
		this.sum += x
		this.sum2 += x*x

		return sqrt(sum2/n - sum*sum/n/n)
	end
end

testData = {2,4,4,4,5,5,7,9}
sd = new(StdDev)

for x in testData
	println sd.sd(x)
end


import math, strutils

var sdSum, sdSum2, sdN = 0.0

proc sd(x: float): float =
  sdN += 1
  sdSum += x
  sdSum2 += x * x
  sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))

for value in [float 2,4,4,4,5,5,7,9]:
  echo value, " ", formatFloat(sd(value), precision = -1)


import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

class CreateFile {
    static void main(String[] args) throws IOException {
        String os = System.getProperty("os.name")
        if (os.contains("Windows")) {
            Path path = Paths.get("tape.file")
            Files.write(path, Collections.singletonList("Hello World!"))
        } else {
            Path path = Paths.get("/dev/tape")
            Files.write(path, Collections.singletonList("Hello World!"))
        }
    }
}


module Main (main) where

main :: IO ()
main = writeFile "/dev/tape" "Hello from Rosetta Code!"


procedure main()
    write(open("/dev/tape","w"),"Hi")
end


100 OPEN #1:"Tape1:README.TXT" ACCESS OUTPUT
110 PRINT #1:"I am a tape file now, or hope to be soon."
120 CLOSE #1


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class CreateFile {
    public static void main(String[] args) throws IOException {
        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            Path path = Paths.get("tape.file");
            Files.write(path, Collections.singletonList("Hello World!"));
        } else {
            Path path = Paths.get("/dev/tape");
            Files.write(path, Collections.singletonList("Hello World!"));
        }
    }
}


use Structure;

bundle Default {
  class StdDev {
    nums : FloatVector;

    New() {
      nums := FloatVector->New();
    }

    function : Main(args : String[]) ~ Nil {
      sd := StdDev->New();
      test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
      each(i : test_data) {
        sd->AddNum(test_data[i]);
        sd->GetSD()->PrintLine();
      };
    }

    method : public : AddNum(num : Float) ~ Nil {
      nums->AddBack(num);
    }

    method : public : native : GetSD() ~ Float {
      sq_diffs := 0.0;
      avg := nums->Average();
      each(i : nums) {
        num := nums->Get(i);
        sq_diffs += (num - avg) * (num - avg);
      };

      return (sq_diffs / nums->Size())->SquareRoot();
    }
  }
}


#import <Foundation/Foundation.h>

@interface SDAccum : NSObject
{
  double sum, sum2;
  unsigned int num;
}
-(double)value: (double)v;
-(unsigned int)count;
-(double)mean;
-(double)variance;
-(double)stddev;
@end

@implementation SDAccum
-(double)value: (double)v
{
  sum += v;
  sum2 += v*v;
  num++;
  return [self stddev];
}
-(unsigned int)count
{
  return num;
}
-(double)mean
{
  return (num>0) ? sum/(double)num : 0.0;
}
-(double)variance
{
  double m = [self mean];
  return (num>0) ? (sum2/(double)num - m*m) : 0.0;
}
-(double)stddev
{
  return sqrt([self variance]);
}
@end

int main()
{
  @autoreleasepool {

    double v[] = { 2,4,4,4,5,5,7,9 };

    SDAccum *sdacc = [[SDAccum alloc] init];

    for(int i=0; i < sizeof(v)/sizeof(*v) ; i++)
      printf("adding %f\tstddev = %f\n", v[i], [sdacc value: v[i]]);

  }
  return 0;
}


// EXEC PGM=IEBGENER
//* Create a file named "TAPE.FILE" on magnetic tape; "UNIT=TAPE"
//*    may vary depending on site-specific esoteric name assignment
//SYSPRINT DD SYSOUT=*
//SYSIN    DD DUMMY
//SYSUT2   DD UNIT=TAPE,DSN=TAPE.FILE,DISP=(,CATLG)
//SYSUT1   DD *
DATA TO BE WRITTEN TO TAPE
/*


open("/dev/tape", "w") do f
    write(f, "Hello tape!")
end


// version 1.1.0 (Linux)

import java.io.FileWriter

fun main(args: Array<String>) {
    val lp0 = FileWriter("/dev/tape")
    lp0.write("Hello, world!")
    lp0.close()
}


require "lfs"

local out
if lfs.attributes('/dev/tape') then
    out = '/dev/tape'
else
    out = 'tape.file'
end
file = io.open(out, 'w')
file:write('Hello world')
io.close(file)


var t = open("/dev/tape", fmWrite)
t.writeln "Hi Tape!"
t.close


include builtins/write_file.e
constant filepath = iff(platform()=WINDOWS?"tape.file":"/dev/tape"),
write_file(file_path,"Hello world!")


(out "/dev/tape"
   (prin "Hello World!") )


>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
>>>


#lang racket
(with-output-to-file "/dev/tape" #:exists 'append
  (λ() (displayln "I am a cheap imitation of the Perl code for a boring problem")))


my $tape = open "/dev/tape", :w or die "Can't open tape: $!";
$tape.say: "I am a tape file now, or hope to be soon.";
$tape.close;


let sqr x = x *. x

let stddev l =
  let n, sx, sx2 =
    List.fold_left
      (fun (n, sx, sx2) x -> succ n, sx +. x, sx2 +. sqr x)
      (0, 0., 0.) l
  in
  sqrt ((sx2 -. sqr sx /. float n) /. float n)

let _ =
  let l = [ 2.;4.;4.;4.;5.;5.;7.;9. ] in
  Printf.printf "List: ";
  List.iter (Printf.printf "%g  ") l;
  Printf.printf "\nStandard deviation: %g\n" (stddev l)


Channel new [ ] over send drop const: StdValues

: stddev(x)
| l |
   StdValues receive x + dup ->l StdValues send drop
   #qs l map sum l size asFloat / l avg sq - sqrt ;


sdacc = .SDAccum~new
x = .array~of(2,4,4,4,5,5,7,9)
sd = 0
do i = 1 to x~size
   sd = sdacc~value(x[i])
   Say '#'i 'value =' x[i] 'stdev =' sd
end

::class SDAccum
::method sum attribute
::method sum2 attribute
::method count attribute
::method init
  self~sum = 0.0
  self~sum2 = 0.0
  self~count = 0
::method value
  expose sum sum2 count
  parse arg x
  sum = sum + x
  sum2 = sum2 + x*x
  count = count + 1
  return self~stddev
::method mean
  expose sum count
  return sum/count
::method variance
  expose sum2  count
  m = self~mean
  return sum2/count - m*m
::method stddev
  return self~sqrt(self~variance)
::method sqrt
  arg n
  if n = 0 then return 0
  ans = n / 2
  prev = n
  do until prev = ans
    prev = ans
    ans = ( prev + ( n / prev ) ) / 2
  end
  return ans


/*REXX pgm  demonstrates  writing records  to an attached magnetic tape.*/
dsName = 'TAPE.FILE'                   /*dsName of "file" being written.*/

          do j=1  for 100              /*write 100 records to mag tape. */
          call lineout  dsName,  'this is record'   j   ||   "."
          end   /*j*/
                                       /*stick a fork in it, we're done.*/


# Project : Create a file on magnetic tape

fn = "Tape.file"
fp = fopen(fn,"w")
str = "I am a tape file now, or hope to be soon."
fwrite(fp, str)
fclose(fp)


File.open("tape.file", "w") do |fh|
    fh.syswrite("This code should be able to write a file to magnetic tape.\n")
end


use std::io::Write;
use std::fs::File;

fn main() -> std::io::Result<()> {
    File::open("/dev/tape")?.write_all(b"Hello from Rosetta Code!")
}


object LinePrinter extends App {
  import java.io.{ FileWriter, IOException }
  {
    val lp0 = new FileWriter("/dev/tape")
    lp0.write("Hello, world!")
    lp0.close()
  }
}


$ include "seed7_05.s7i";

const proc: main is func
  local
    var file: tapeFile is STD_NULL;
  begin
    tapeFile := open("/dev/tape", "w");
    if tapeFile = STD_NULL then
      tapeFile := open("tape.file", "w");
    end if;
    if tapeFile <> STD_NULL then
      writeln(tapeFile, "Hello, world!");
      close(tapeFile);
    else
      writeln(" ***** Cannot open tape file.");
    end if;
  end func;


cd /tmp

# Create the file
set f [open hello.jnk w]
puts $f "Hello World!"
close $f

# Archive to tape
set fin [open "|tar cf - hello.jnk" rb]
set fout [open /dev/tape wb]
fcopy $fin $fout
close $fin
close $fout


$$ MODE TUSCRIPT
STATUS = CREATE ("tape.file",tape-o,-std-)
PRINT STATUS


newpoint(x)={
  myT=x;
  myS=0;
  myN=1;
  [myT,myS]/myN
};
addpoint(x)={
  myT+=x;
  myN++;
  myS+=(myN*x-myT)^2/myN/(myN-1);
  [myT,myS]/myN
};
addpoints(v)={
  print(newpoint(v[1]));
  for(i=2,#v,print(addpoint(v[i])));
  print("Mean: ",myT/myN);
  print("Standard deviation: ",sqrt(myS/myN))
};
addpoints([2,4,4,4,5,5,7,9])


program stddev;
uses math;
const
  n=8;
var
  arr: array[1..n] of real =(2,4,4,4,5,5,7,9);
function stddev(n: integer): real;
var
   i: integer;
   s1,s2,variance,x: real;
begin
    for i:=1 to n do
    begin
      x:=arr[i];
      s1:=s1+power(x,2);
      s2:=s2+x
    end;
    variance:=((n*s1)-(power(s2,2)))/(power(n,2));
    stddev:=sqrt(variance)
end;
var
   i: integer;
begin
    for i:=1 to n do
    begin
      writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15)
    end
end.


#!/bin/sh
cd    # Make our home directory current
echo "Hello World!" > hello.jnk  # Create a junk file
# tape rewind                    # Uncomment this to rewind the tape
tar c hello.jnk                  # Traditional archivers use magnetic tape by default
# tar c hello.jnk > /dev/tape    # With newer archivers redirection is needed


import "os" for Platform
import "io" for File

var fileName = (Platform.isWindows) ? "TAPE.FILE" : "/dev/tape"
File.create(fileName) { |file|
    file.writeBytes("Hello World!\n")
}


{
    package SDAccum;
    sub new {
	my $class = shift;
	my $self = {};
	$self->{sum} = 0.0;
	$self->{sum2} = 0.0;
	$self->{num} = 0;
	bless $self, $class;
	return $self;
    }
    sub count {
	my $self = shift;
	return $self->{num};
    }
    sub mean {
	my $self = shift;
	return ($self->{num}>0) ? $self->{sum}/$self->{num} : 0.0;
    }
    sub variance {
	my $self = shift;
	my $m = $self->mean;
	return ($self->{num}>0) ? $self->{sum2}/$self->{num} - $m * $m : 0.0;
    }
    sub stddev {
	my $self = shift;
	return sqrt($self->variance);
    }
    sub value {
	my $self = shift;
	my $v = shift;
	$self->{sum} += $v;
	$self->{sum2} += $v * $v;
	$self->{num}++;
	return $self->stddev;
    }
}


with javascript_semantics

atom sdn = 0, sdsum = 0, sdsumsq = 0

procedure sdadd(atom n)
    sdn += 1
    sdsum += n
    sdsumsq += n*n
end procedure

function sdavg()
    return sdsum/sdn
end function

function sddev()
    return sqrt(sdsumsq/sdn - power(sdsum/sdn,2))
end function

--test code:
constant testset = {2, 4, 4, 4, 5, 5, 7, 9}
integer ti
for i=1 to length(testset) do
    ti = testset[i]
    sdadd(ti)
    printf(1,"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n",{i,ti,sdavg(),sddev()})
end for


<?php
class sdcalc {
    private  $cnt, $sumup, $square;

    function __construct() {
       $this->reset();
    }
    # callable on an instance
    function reset() {
       $this->cnt=0; $this->sumup=0; $this->square=0;
    }
    function add($f) {
        $this->cnt++;
        $this->sumup  += $f;
        $this->square += pow($f, 2);
        return $this->calc();
    }
    function calc() {
        if ($this->cnt==0 || $this->sumup==0) {
            return 0;
        } else {
            return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2));
        }
    }
 }

# start test, adding test data one by one
$c = new sdcalc();
foreach ([2,4,4,4,5,5,7,9] as $v) {
    printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL);
}


(scl 2)

(de stdDev ()
   (curry ((Data)) (N)
      (push 'Data N)
      (let (Len (length Data)  M (*/ (apply + Data) Len))
         (sqrt
            (*/
               (sum
                  '((N) (*/ (- N M) (- N M) 1.0))
                  Data )
               1.0
               Len )
            T ) ) ) )

(let Fun (stdDev)
   (for N (2.0 4.0 4.0 4.0 5.0 5.0 7.0 9.0)
      (prinl (format N *Scl) " -> " (format (Fun N) *Scl)) ) )


*process source attributes xref;
 stddev: proc options(main);
   declare a(10) float init(1,2,3,4,5,6,7,8,9,10);
   declare stdev float;
   declare i fixed binary;

   stdev=std_dev(a);
   put skip list('Standard deviation', stdev);

   std_dev: procedure(a) returns(float);
     declare a(*) float, n fixed binary;
     n=hbound(a,1);
     begin;
       declare b(n) float, average float;
       declare i fixed binary;
       do i=1 to n;
         b(i)=a(i);
       end;
       average=sum(a)/n;
       put skip data(average);
       return( sqrt(sum(b**2)/n - average**2) );
     end;
   end std_dev;

 end;


function Get-StandardDeviation {
    begin {
        $avg = 0
        $nums = @()
    }
    process {
        $nums += $_
        $avg = ($nums | Measure-Object -Average).Average
        $sum = 0;
        $nums | ForEach-Object { $sum += ($avg - $_) * ($avg - $_) }
        [Math]::Sqrt($sum / $nums.Length)
    }
}


;Define our Standard deviation function
Declare.d Standard_deviation(x)

; Main program
If OpenConsole()
  Define i, x
  Restore MyList
  For i=1 To 8
    Read.i x
    PrintN(StrD(Standard_deviation(x)))
  Next i
  Print(#CRLF$+"Press ENTER to exit"): Input()
EndIf

;Calculation procedure, with memory
Procedure.d Standard_deviation(In)
  Static in_summa, antal
  Static in_kvadrater.q
  in_summa+in
  in_kvadrater+in*in
  antal+1
  ProcedureReturn Pow((in_kvadrater/antal)-Pow(in_summa/antal,2),0.50)
EndProcedure

;data section
DataSection
MyList:
  Data.i  2,4,4,4,5,5,7,9
EndDataSection


#lang racket
(require math)
(define running-stddev
  (let ([ns '()])
    (λ(n) (set! ns (cons n ns)) (stddev ns))))
;; run it on each number, return the last result
(last (map running-stddev '(2 4 4 4 5 5 7 9)))


sub sd (@a) {
    my $mean = @a R/ [+] @a;
    sqrt @a R/ [+] map (* - $mean)**2, @a;
}

sub sdaccum {
    my @a;
    return { push @a, $^x; sd @a; };
}

my &f = sdaccum;
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;


/*REXX program calculates and displays the standard deviation of a given set of numbers.*/
parse arg #                                      /*obtain optional arguments from the CL*/
if #=''  then  #= 2 4 4 4 5 5 7 9                /*None specified?  Then use the default*/
n= words(#);   $= 0;      $$= 0;    L= length(n) /*N:  # items; $,$$:  sums to be zeroed*/
                                                 /* [↓]  process each number in the list*/
           do j=1  for n
           _= word(#, j);        $= $   +  _
                                $$= $$  +  _**2
           say  '   item'  right(j, L)":"    right(_, 4)    '  average='    left($/j, 12),
                '   standard deviation='     sqrt($$/j  -  ($/j)**2)
           end   /*j*/                           /* [↑]  prettify output with whitespace*/
say 'standard deviation: ' sqrt($$/n - ($/n)**2) /*calculate & display the std deviation*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0  then return 0; d=digits(); h=d+6; m.=9; numeric form
      numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .;   g=g * .5'e'_ % 2
                   do j=0  while h>9;      m.j=h;               h=h%2+1;        end  /*j*/
                   do k=j+5  to 0  by -1;  numeric digits m.k;  g=(g+x/g)*.5;   end  /*k*/
      numeric digits d;                    return g/1


# Project : Cumulative standard deviation

decimals(6)
sdsave = list(100)
sd = "2,4,4,4,5,5,7,9"
sumval = 0
sumsqs = 0

for num = 1 to 8
     sd = substr(sd, ",", "")
     stddata = number(sd[num])
     sumval = sumval + stddata
     sumsqs = sumsqs + pow(stddata,2)
     standdev = pow(((sumsqs / num) - pow((sumval /num),2)),0.5)
     sdsave[num] = string(num) + " " + string(sumval) +" " + string(sumsqs)
     see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl
next


class StdDevAccumulator
  def initialize
    @n, @sum, @sumofsquares = 0, 0.0, 0.0
  end

  def <<(num)
    # return self to make this possible:  sd << 1 << 2 << 3 # => 0.816496580927726
    @n += 1
    @sum += num
    @sumofsquares += num**2
    self
  end

  def stddev
    Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 )
  end

  def to_s
    stddev.to_s
  end
end

sd = StdDevAccumulator.new
i = 0
[2,4,4,4,5,5,7,9].each {|n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }


dim sdSave$(100) 'can call up to 100 versions
                  'holds (space-separated) number of data , sum of values and sum of squares
sd$ = "2,4,4,4,5,5,7,9"

for num = 1 to 8
 stdData = val(word$(sd$,num,","))
  sumVal = sumVal + stdData
  sumSqs = sumSqs + stdData^2

  ' standard deviation = square root of (the average of the squares less the square of the average)
  standDev   =((sumSqs / num) - (sumVal /num) ^ 2) ^ 0.5

  sdSave$(num) = str$(num);" ";str$(sumVal);" ";str$(sumSqs)
  print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev)

next num


pub struct CumulativeStandardDeviation {
    n: f64,
    sum: f64,
    sum_sq: f64
}

impl CumulativeStandardDeviation {
    pub fn new() -> Self {
        CumulativeStandardDeviation {
            n: 0.,
            sum: 0.,
            sum_sq: 0.
        }
    }

    fn push(&mut self, x: f64) -> f64 {
        self.n += 1.;
        self.sum += x;
        self.sum_sq += x * x;

        (self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt()
    }
}

fn main() {
    let nums = [2, 4, 4, 4, 5, 5, 7, 9];

    let mut cum_stdev = CumulativeStandardDeviation::new();
    for num in nums.iter() {
        println!("{}", cum_stdev.push(*num as f64));
    }
}


*--Load the test data;
data test1;
   input x @@;
   obs=_n_;
datalines;
2 4 4 4 5 5 7 9
;
run;

*--Create a dataset with the cummulative data for each set of data for which the SD should be calculated;
data test2 (drop=i obs);
   set test1;
   y=x;
   do i=1 to n;
      set test1 (rename=(obs=setid)) nobs=n point=i;
      if obs<=setid then output;
   end;
proc sort;
   by setid;
run;

*--Calulate the standards deviation (and mean) using PROC MEANS;
proc means data=test2 vardef=n noprint; *--use vardef=n option to calculate the population SD;
   by setid;
   var y;
   output out=stat1 n=n mean=mean std=sd;
run;

*--Output the calculated standard deviations;
proc print data=stat1 noobs;
   var n sd /*mean*/;
run;


import scala.math.sqrt

object StddevCalc extends App {

  def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
    def avg(ts: Iterable[T])(implicit num: Fractional[T]): T =
      num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T

    val mean: T = avg(ts) // Leave val type of T
    // Root of mean diffs
    val stdDev = sqrt(ts.map { x =>
      val diff = num.toDouble(num.minus(x, mean))
      diff * diff
    }.sum / ts.size)

    (mean, stdDev)
  }

  println(calcAvgAndStddev(List(2.0E0, 4.0, 4, 4, 5, 5, 7, 9)))
  println(calcAvgAndStddev(Set(1.0, 2, 3, 4)))
  println(calcAvgAndStddev(0.1 to 1.1 by 0.05))
  println(calcAvgAndStddev(List(BigDecimal(120), BigDecimal(1200))))

  println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")

}


(define (standart-deviation-generator)
  (let ((nums '()))
    (lambda (x)
      (set! nums (cons x nums))
      (let* ((mean (/ (apply + nums) (length nums)))
      (mean-sqr (lambda (y) (expt (- y mean) 2)))
      (variance (/ (apply + (map mean-sqr nums)) (length nums))))
    (sqrt variance)))))

(let loop ((f (standart-deviation-generator))
           (input '(2 4 4 4 5 5 7 9)))
  (if (not (null? input))
    (begin
      (display (f (car input)))
      (newline)
      (loop f (cdr input)))))


class StdDevAccumulator(n=0, sum=0, sumofsquares=0) {
  method <<(num) {
    n += 1
    sum += num
    sumofsquares += num**2
    self
  }

  method stddev {
    sqrt(sumofsquares/n - pow(sum/n, 2))
  }

  method to_s {
    self.stddev.to_s
  }
}

var i = 0
var sd = StdDevAccumulator()
[2,4,4,4,5,5,7,9].each {|n|
    say "adding #{n}: stddev of #{i+=1} samples is #{sd << n}"
}


Object subclass: SDAccum [
    |sum sum2 num|
    SDAccum class >> new [  |o|
        o := super basicNew.
        ^ o init.
    ]
    init [ sum := 0. sum2 := 0. num := 0 ]
    value: aValue [
      sum := sum + aValue.
      sum2 := sum2 + ( aValue * aValue ).
      num := num + 1.
      ^ self stddev
    ]
    count [ ^ num ]
    mean [ num>0 ifTrue: [^ sum / num] ifFalse: [ ^ 0.0 ] ]
    variance [ |m| m := self mean.
               num>0 ifTrue: [^ (sum2/num) - (m*m) ] ifFalse: [ ^ 0.0 ]
             ]
    stddev [ ^ (self variance) sqrt ]
].


-- the minimal table
CREATE TABLE IF NOT EXISTS teststd (n DOUBLE PRECISION NOT NULL);

-- code modularity with view, we could have used a common table expression instead
CREATE VIEW  vteststd AS
  SELECT COUNT(n) AS cnt,
  SUM(n) AS tsum,
  SUM(POWER(n,2)) AS tsqr
FROM teststd;

-- you can of course put this code into every query
CREATE OR REPLACE FUNCTION std_dev() RETURNS DOUBLE PRECISION AS $$
 SELECT SQRT(tsqr/cnt - (tsum/cnt)^2) FROM vteststd;
$$ LANGUAGE SQL;

-- test data is: 2,4,4,4,5,5,7,9
INSERT INTO teststd VALUES (2);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (5);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (5);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (7);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (9);
SELECT std_dev() AS std_deviation;
-- cleanup test data
DELETE FROM teststd;


import Darwin
class stdDev{

    var n:Double = 0.0
    var sum:Double = 0.0
    var sum2:Double = 0.0

    init(){

        let testData:[Double] = [2,4,4,4,5,5,7,9];
        for x in testData{

            var a:Double = calcSd(x)
            println("value \(Int(x)) SD = \(a)");
        }

    }

    func calcSd(x:Double)->Double{

        n += 1
        sum += x
        sum2 += x*x
        return sqrt( sum2 / n - sum*sum / n / n)
    }

}
var aa = stdDev()


oo::class create SDAccum {
    variable sum sum2 num
    constructor {} {
        set sum 0.0
        set sum2 0.0
        set num 0
    }
    method value {x} {
        set sum2 [expr {$sum2 + $x**2}]
        set sum [expr {$sum + $x}]
        incr num
        return [my stddev]
    }
    method count {} {
        return $num
    }
    method mean {} {
        expr {$sum / $num}
    }
    method variance {} {
        expr {$sum2/$num - [my mean]**2}
    }
    method stddev {} {
        expr {sqrt([my variance])}
    }
}

# Demonstration
set sdacc [SDAccum new]
foreach val {2 4 4 4 5 5 7 9} {
    set sd [$sdacc value $val]
}
puts "the standard deviation is: $sd"


• Press [STAT] select [EDIT] followed by [ENTER]
• then enter for list L1 in the table : 2, 4, 4, 4, 5, 5, 7, 9
• Or enter {2,4,4,4,5,5,7,9}→L1
• Press [STAT] select [CALC] then [1-Var Stats] select list L1 followed by [ENTER]
• Then σx (=2) gives the standard deviation of the population


data = Array(2,4,4,4,5,5,7,9)

For i = 0 To UBound(data)
	WScript.StdOut.Write "value = " & data(i) &_
		" running sd = " & sd(data,i)
	WScript.StdOut.WriteLine
Next

Function sd(arr,n)
	mean = 0
	variance = 0
	For j = 0 To n
		mean = mean + arr(j)
	Next
	mean = mean/(n+1)
	For k = 0 To n
		variance = variance + ((arr(k)-mean)^2)
	Next
	variance = variance/(n+1)
	sd = FormatNumber(Sqr(variance),6)
End Function


Function avg(what() As Variant) As Variant
    'treats non-numeric strings as zero
    Dim L0 As Variant, total As Variant
    For L0 = LBound(what) To UBound(what)
        If IsNumeric(what(L0)) Then total = total + what(L0)
    Next
    avg = total / (1 + UBound(what) - LBound(what))
End Function

Function standardDeviation(fp As Variant) As Variant
    Static list() As Variant
    Dim av As Variant, tmp As Variant, L0 As Variant

    'add to sequence if numeric
    If IsNumeric(fp) Then
        On Error GoTo makeArr   'catch undimensioned list
        ReDim Preserve list(UBound(list) + 1)
        On Error GoTo 0
        list(UBound(list)) = fp
    End If

    'get average
    av = avg(list())

    'the actual work
    For L0 = 0 To UBound(list)
        tmp = tmp + ((list(L0) - av) ^ 2)
    Next
    tmp = Sqr(tmp / (UBound(list) + 1))

    standardDeviation = tmp

    Exit Function
makeArr:
    If 9 = Err.Number Then
        ReDim list(0)
    Else
        'something's wrong
        Err.Raise Err.Number
    End If
    Resume Next
End Function

Sub tester()
    Dim x As Variant
    x = Array(2, 4, 4, 4, 5, 5, 7, 9)
    For L0 = 0 To UBound(x)
        Debug.Print standardDeviation(x(L0))
    Next
End Sub


import "/fmt" for Fmt
import "/math" for Nums

var cumStdDev = Fiber.new { |a|
    for (i in 0...a.count) {
        var b = a[0..i]
        System.print("Values  : %(b)")
        Fiber.yield(Nums.popStdDev(b))
    }
}

var a = [2, 4, 4, 4, 5,  5, 7, 9]
while (true) {
    var sd = cumStdDev.call(a)
    if (cumStdDev.isDone) return
    System.print("Std Dev : %(Fmt.f(10, sd, 8))\n")
}


fcn sdf{ fcn(x,xs){
      m:=xs.append(x.toFloat()).sum(0.0)/xs.len();
      (xs.reduce('wrap(p,x){(x-m)*(x-m) +p},0.0)/xs.len()).sqrt()
    }.fp1(L())
}


L(=line) File(‘data.csv’).read_lines()
   I L.index == 0
      line ‘’= ‘,SUM’
   E
      line ‘’= ‘,’sum(line.split(‘,’).map(Int))
   print(line)


package CSV is

   type Row(<>) is tagged private;

   function Line(S: String; Separator: Character := ',') return Row;
   function Next(R: in out Row) return Boolean;
     -- if there is still an item in R, Next advances to it and returns True
   function Item(R: Row) return String;
     -- after calling R.Next i times, this returns the i'th item (if any)

private
   type Row(Length: Natural) is tagged record
      Str: String(1 .. Length);
      Fst: Positive;
      Lst: Natural;
      Nxt: Positive;
      Sep: Character;
   end record;
end CSV;


void
read_csv(list t, text path)
{
    file f;
    list l;

    f_affix(f, path);
    while (f_news(f, l, 0, 0, ",") ^ -1) {
        l_append(t, l);
    }
}

list
sum_columns(list t)
{
    list c, l;
    integer i;

    l_append(c, "SUM");
    for (i, l in t) {
        if (i) {
            integer j, sum;
            text s;

            sum = 0;
            for (j, s in l) {
                sum += atoi(s);
            }

            l_append(c, sum);
        }
    }

    return c;
}

void
add_column(list t, list c)
{
    integer i;
    list l;

    for (i, l in t) {
        l_append(l, c[i]);
    }
}

void
write_csv(list t, text path)
{
    integer i;
    file f;
    list l;

    f_create(f, path, 00644);
    for (i, l in t) {
        f_(f, l[0]);
        l_ocall(l, f_, 2, 1, -1, f, ",");
        f_newline(f);
    }
}

integer
main(void)
{
    list t;

    read_csv(t, "tmp/CSV_data_manipulation.csv");
    add_column(t, sum_columns(t));
    write_csv(t, "tmp/CSV_data_manipulated.csv");

    return 0;
}