/* NetRexx */
options replace format comments java crossref symbols nobinary utf8

numeric digits 30

x = 2.5
y = 3
pad = 40
say
say 'Java Math constants & functions:'
say Rexx('  Euler''s number (e):').left(pad)                    Math.E
say Rexx('  Pi:').left(pad)                                     Math.PI
say Rexx('  Square root of' x':').left(pad)                     Math.sqrt(x)
say Rexx('  Log(e) of' x':').left(pad)                          Math.log(x)
say Rexx('  Log(e) of e:').left(pad)                            Math.log(Math.E)
say Rexx('  Log(10) of' x':').left(pad)                         Math.log10(x)
say Rexx('  Log(10) of 10:').left(pad)                          Math.log10(10)
say Rexx('  Exponential (e**x) of' x':').left(pad)              Math.exp(x)
say Rexx('  Exponential (e**x) of log(e)' x':').left(pad)       Math.exp(Math.log(x))
say Rexx('  Abs of' x':').left(pad)                             Math.abs(x.todouble)
say Rexx('  Abs of' (-x)':').left(pad)                          Math.abs((-x).todouble)
say Rexx('  Floor of' x':').left(pad)                           Math.floor(x)
say Rexx('  Floor of' (-x)':').left(pad)                        Math.floor((-x))
say Rexx('  Ceiling of' x':').left(pad)                         Math.ceil(x)
say Rexx('  Ceiling of' (-x)':').left(pad)                      Math.ceil((-x))
say Rexx(' ' x 'to the power of' y':').left(pad)                Math.pow(x, y)
say Rexx(' ' x 'to the power of' 1 / y':').left(pad)            Math.pow(x, 1 / y)
say Rexx('  10 to the power of log10' x':').left(pad)           Math.pow(10, Math.log10(x))

-- Extras
say Rexx('  Cube root of' x':').left(pad)                       Math.cbrt(x)
say Rexx('  Hypotenuse of' 3 'x' 4 'right triangle:').left(pad) Math.hypot(3, 4)
say Rexx('  Max of' (-x) '&' x':').left(pad)                    Math.max((-x).todouble, x)
say Rexx('  Min of' (-x) '&' x':').left(pad)                    Math.min((-x).todouble, x)
say Rexx('  Signum of' x':').left(pad)                          Math.signum((x).todouble)
say Rexx('  Signum of' x '-' x':').left(pad)                    Math.signum((x - x).todouble)
say Rexx('  Signum of' (-x)':').left(pad)                       Math.signum((-x).todouble)

say
say 'NetRexx built-in support for numeric data:'
say Rexx('  Abs of' x':').left(pad)                        x.abs()
say Rexx('  Abs of' (-x)':').left(pad)                     (-x).abs()
say Rexx('  Sign of' x':').left(pad)                       x.sign()
say Rexx('  Sign of' x '-' x':').left(pad)                 (x - x).sign()
say Rexx('  Sign of' (-x)':').left(pad)                    (-x).sign()
say Rexx('  Max of' (-x) '&' x':').left(pad)               (-x).max(x)
say Rexx('  Min of' (-x) '&' x':').left(pad)               (-x).min(x)
say Rexx('  Truncate' x 'by' y':').left(pad)               x.trunc(y)
say Rexx('  Format (with rounding)' x 'by' y':').left(pad) x.format(y, 0)


MODE FIELD = REAL; # FIELD can be REAL, LONG REAL etc, or COMPL, FRAC etc #
MODE VEC = [0]FIELD;
MODE MAT = [0,0]FIELD;

PROC to reduced row echelon form = (REF MAT m)VOID: (
    INT lead col := 2 LWB m;

    FOR this row FROM LWB m TO UPB m DO
        IF lead col > 2 UPB m THEN return FI;
        INT other row := this row;
        WHILE m[other row,lead col] = 0 DO
            other row +:= 1;
            IF other row > UPB m THEN
                other row := this row;
                lead col +:= 1;
                IF lead col > 2 UPB m THEN return FI
            FI
        OD;
        IF this row /= other row THEN
            VEC swap = m[this row,lead col:];
            m[this row,lead col:] := m[other row,lead col:];
            m[other row,lead col:] := swap
        FI;
        FIELD scale = 1/m[this row,lead col];
        IF scale /= 1 THEN
            m[this row,lead col] := 1;
            FOR col FROM lead col+1 TO 2 UPB m DO m[this row,col] *:= scale OD
        FI;
        FOR other row FROM LWB m TO UPB m DO
            IF this row /= other row THEN
                REAL scale = m[other row,lead col];
                m[other row,lead col]:=0;
                FOR col FROM lead col+1 TO 2 UPB m DO m[other row,col] -:= scale*m[this row,col] OD
            FI
        OD;
        lead col +:= 1
    OD;
    return: EMPTY
);

[3,4]FIELD mat := (
   ( 1, 2, -1, -4),
   ( 2, 3, -1, -11),
   (-2, 0, -3, 22)
);

to reduced row echelon form( mat );

FORMAT
  real repr = $g(-7,4)$,
  vec repr = $"("n(2 UPB mat-1)(f(real repr)", ")f(real repr)")"$,
  mat repr = $"("n(1 UPB mat-1)(f(vec repr)", "lx)f(vec repr)")"$;

printf((mat repr, mat, $l$))


import math

var x, y = 12.5

echo E
echo PI
echo sqrt(x)
echo ln(x)
echo log10(x)
echo exp(x)
echo abs(x)
echo floor(x)
echo ceil(x)
echo pow(x, y)


Float->Pi();
Float->E();
4.0->SquareRoot();
1.5->Log();
# exponential is not supported
3.99->Abs();
3.99->Floor();
3.99->Ceiling();
4.5->Ceiling(2.0);


Float.pi    (* pi *)
sqrt x      (* square root *)
log x       (* natural logarithm--log base 10 also available (log10) *)
exp x       (* exponential *)
abs_float x (* absolute value *)
abs x       (* absolute value (for integers) *)
floor x     (* floor *)
ceil x      (* ceiling *)
x ** y      (* power *)
-. x        (* negation for floats *)


e         % e
pi        % pi
sqrt(pi)  % square root
log(e)    % natural logarithm
exp(pi)   % exponential
abs(-e)   % absolute value
floor(pi) % floor
ceil(pi)  % ceiling
e**pi     % power


begin
    % replaces M with it's reduced row echelon form              %
    % M should have bounds ( 0 :: rMax, 0 :: cMax )              %
    procedure toReducedRowEchelonForm ( real    array M ( *, * )
                                      ; integer value rMax, cMax
                                      ) ;
    begin
        integer lead;
        lead := 0;
        for r := 0 until rMax do begin
            integer i;
            if lead > cMax then goto done;
            i := r;
            while M( i, lead ) = 0 do begin
                i := i + 1;
                if rMax = i then begin
                    i    := r;
                    lead := lead + 1;
                    if cMax = lead then goto done
                end if_rowCount_eq_i
            end while_M_i_lead_eq_0 ;
            % Swap rows i and r %
            for c := 0 until cMax do begin
                real t;
                t         := M( i, c );
                M( i, c ) := M( r, c );
                M( r, c ) := t
            end swap_rows_i_and_r ;
            If M( r, lead ) not = 0 then begin
                % divide row r by M[r, lead] %
                real rLead;
                rLead := M( r, lead );
                for c := 0 until cMax do M( r, c ) := M( r, c ) / rLead
            end if_M_r_lead_ne_0 ;
            for i := 0 until rMax do begin
                if i not = r then begin
                    % Subtract M[i, lead] multiplied by row r from row i %
                    real iLead;
                    iLead := M( i, lead );
                    for c := 0 until cMax do M( i, c ) := M( i, c ) - ( iLead * M( r, c ) )
                end if_i_ne_r
            end for_i ;
            lead := lead + 1
        end for_r ;
done:
    end toReducedRowEchelonForm ;
    % test the toReducedRowEchelonForm procedure %
    begin
        real array m( 0 :: 2, 0 :: 3 );
        M( 0, 0 ) :=  1; M( 0, 1 ) :=  2; M( 0, 2 ) := -1; M( 0, 3 ) :=  -4;
        M( 1, 0 ) :=  2; M( 1, 1 ) :=  3; M( 1, 2 ) := -1; M( 1, 3 ) := -11;
        M( 2, 0 ) := -2; M( 2, 1 ) :=  0; M( 2, 2 ) := -3; M( 2, 3 ) :=  22;
        toReducedRowEchelonForm( M, 2, 3 );
        r_format := "A"; s_w := 0; r_w := 6; r_d := 1; % set output formating %
        for r := 0 until 2 do begin
            write( M( r, 0 ) );
            for c := 1 until 3 do writeon( " ", M( r, c ) );
        end for_r
    end
end.


ToReducedRowEchelonForm(M){
    rowCount 	:= M.Count()		; the number of rows in M
    columnCount := M.1.Count()		; the number of columns in M
    r := lead := 1
    while (r <= rowCount) {
        if (columnCount < lead)
            return M
        i := r
        while (M[i, lead] = 0) {
            i++
            if (rowCount+1 = i) {
                i := r, 	lead++
                if (columnCount+1 = lead)
                    return M
            }
        }
        if (i<>r)
            for col, v in M[i]		; Swap rows i and r
                tempVal := M[i, col],	M[i, col] := M[r, col],		M[r, col] := tempVal

        num := M[r, lead]
        if (M[r, lead] <> 0)
            for col, val in M[r]
                M[r, col] /= num	; If M[r, lead] is not 0 divide row r by M[r, lead]

        i := 2
        while (i <= rowCount) {
            num := M[i, lead]
            if (i <> r)
                for col, val in M[i]	; Subtract M[i, lead] multiplied by row r from row i
                    M[i, col] -= num * M[r, col]
            i++
        }
        lead++,		r++
    }
    return M
}


byte X

Proc Main()

 Open (1,"D:FILENAME.TXT",4,0)
 Do
  X=GetD(1)
  Put(X)
  Until EOF(1)
 Od
 Close(1)

Return


File := FileOpen("input.txt", "r")
while !File.AtEOF
    MsgBox, % File.Read(1)


import: math

: testReal
   E println
   Pi println
   9 sqrt println
   2 ln println
   2 exp println
   -3.4 abs println
   3.4 exp println

   2.4 floor println
   3.9 floor println
   5.5 floor println
  -2.4 floor println
  -3.9 floor println
  -5.5 floor println

   2.4 ceil println
   3.9 ceil println
   5.5 ceil println
  -2.4 ceil println
  -3.9 ceil println
  -5.5 ceil println ;


/* Rexx */

-- MathLoadFuncs & MathDropFuncs are no longer needed and are effectively NOPs
-- but MathLoadFuncs does return its copyright statement when given a string argument
RxMathCopyright = MathLoadFuncs('')
say RxMathCopyright

numeric digits 16

x = 2.5
y = 3
pad = 40
digs = digits()
say
say 'Working with precision' digs
say 'Math constants & functions:'
say ('  Euler''s number (e):')~left(pad)                    RxCalcExp(1, digs)
say ('  Pi:')~left(pad)                                     RxCalcPi(digs)
say ('  Square root of' x':')~left(pad)                     RxCalcSqrt(x, digs)
say ('  Log(e) of' x':')~left(pad)                          RxCalcLog(x, digs)
say ('  Log(e) of e:')~left(pad)                            RxCalcLog(RxCalcExp(1, digs), digs)
say ('  Log(10) of' x':')~left(pad)                         RxCalcLog10(x, digs)
say ('  Log(10) of 10:')~left(pad)                          RxCalcLog10(10, digs)
say ('  Exponential (e**x) of' x':')~left(pad)              RxCalcExp(x, digs)
say ('  Exponential (e**x) of log(e)' x':')~left(pad)       RxCalcExp(RxCalcLog(x, digs), digs)
say (' ' x 'to the power of' y':')~left(pad)                RxCalcPower(x, y, digs)
say (' ' x 'to the power of 1/'y':')~left(pad)              RxCalcPower(x, 1 / y, digs)
say ('  10 to the power of log10' x':')~left(pad)           RxCalcPower(10, RxCalcLog10(x), digs)

say
say 'Rexx built-in support for numeric data:'
say ('  Abs of' x':')~left(pad)                             x~abs()
say ('  Abs of' (-x)':')~left(pad)                          (-x)~abs()
say ('  Sign of' x':')~left(pad)                            x~sign()
say ('  Sign of' x '-' x':')~left(pad)                      (x - x)~sign()
say ('  Sign of' (-x)':')~left(pad)                         (-x)~sign()
say ('  Max of' (-x) '&' x':')~left(pad)                    (-x)~max(x)
say ('  Min of' (-x) '&' x':')~left(pad)                    (-x)~min(x)
say ('  Truncate' x 'by' y':')~left(pad)                    x~trunc(y)
say ('  Format (with rounding)' x 'by' y':')~left(pad)      x~format(y, 0)

say
say 'Use RYO functions for floor & ceiling:'
say ('  Floor of' x':')~left(pad)                           floor(x)
say ('  Floor of' (-x)':')~left(pad)                        floor((-x))
say ('  Ceiling of' x':')~left(pad)                         ceiling(x)
say ('  Ceiling of' (-x)':')~left(pad)                      ceiling((-x))

return

-- floor and ceiling functions are not part of ooRexx
floor: procedure
  return arg(1)~trunc() - (arg(1) < 0) * (arg(1) \= arg(1)~trunc())

ceiling: procedure
  return arg(1)~trunc() + (arg(1) > 0) * (arg(1) \= arg(1)~trunc())

::requires 'RxMath' library


Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]]
ToReducedRowEchelonForm($ivMatrix)

Func ToReducedRowEchelonForm($matrix)
	Local $clonematrix, $i
	Local $lead = 0
	Local $rowCount = UBound($matrix) - 1
	Local $columnCount = UBound($matrix, 2) - 1
	For $r = 0 To $rowCount
		If $columnCount = $lead Then ExitLoop
		$i = $r
		While $matrix[$i][$lead] = 0
			$i += 1
			If $rowCount = $i Then
				$i = $r
				$lead += 1
				If $columnCount = $lead Then ExitLoop
			EndIf
		WEnd
		; There´s no built in Function to swap Rows of a 2-Dimensional Array
		; We need to clone our matrix to swap complete lines
		$clonematrix = $matrix ; Swap Lines, no
		For $s = 0 To $columnCount
			$matrix[$r][$s] = $clonematrix[$i][$s]
			$matrix[$i][$s] = $clonematrix[$r][$s]
		Next
		Local $m = $matrix[$r][$lead]
		For $k = 0 To $columnCount
			$matrix[$r][$k] = $matrix[$r][$k] / $m
		Next
		For $i = 0 To $rowCount
			If $i <> $r Then
				Local $m = $matrix[$i][$lead]
				For $k = 0 To $columnCount
					$matrix[$i][$k] -= $m * $matrix[$r][$k]
				Next
			EndIf
		Next
		$lead += 1
	Next
	; Console Output
	For $i = 0 To $rowCount
		ConsoleWrite("[")
		For $k = 0 To $columnCount
			ConsoleWrite($matrix[$i][$k])
			If $k <> $columnCount Then ConsoleWrite(",")
		Next
		ConsoleWrite("]" & @CRLF)
	Next
	; End of Console Output
	Return $matrix
EndFunc   ;==>ToReducedRowEchelonForm


f = freefile
filename$ = "file.txt"

open f, filename$

while not eof(f)
	print chr(readbyte(f));
end while
close f
end


{ForAll
 [
  {Exp 1.}           %% 2.7183   Euler's number: not predefined
  4. * {Atan2 1. 1.} %% 3.1416   pi: not predefined
  {Sqrt 81.}         %% 9.0      square root; expects a float
  {Log 2.7183}       %% 1.0      natural logarithm
  {Abs ~1}           %% 1        absolute value; expects a float or an integer
  {Floor 1.999}      %% 1.0      floor; expects and returns a float
  {Ceil 1.999}       %% 2.0      ceiling; expects and returns a float
  {Pow 2 3}          %% 8        power; both arguments must be of the same type
 ]
 Show}


	{ Euler’s constant }
	exp(1)
	{ principal square root of `x` }
	sqrt(x)
	{ natural logarithm }
	ln(x)
	{ exponential }
	exp(x)
	{ absolute value }
	abs(x)


use POSIX; # for floor() and ceil()

exp(1); # e
4 * atan2(1, 1); # pi
sqrt($x); # square root
log($x); # natural logarithm; log10() available in POSIX module
exp($x); # exponential
abs($x); # absolute value
floor($x); # floor
ceil($x); # ceiling
$x ** $y; # power

use Math::Trig;
pi; # alternate way to get pi

use Math::Complex;
pi; # alternate way to get pi


arraybase 1
global matrix
dim matrix = {{1, 2, -1, -4}, {2, 3, -1, -11}, { -2, 0, -3, 22}}

call RREF (matrix)

for row = 1 to 3
    for col = 1 to 4
        if matrix[row, col] = 0 then
            print "0"; chr(9);
        else
            print matrix[row, col]; chr(9);
        end if
    next
    print
next
end

subroutine RREF(m)
    nrows = matrix[?,]
    ncols = matrix[,?]
    lead = 1
    for r = 1 to nrows
        if lead >= ncols then exit for
        i = r
        while matrix[i, lead] = 0
            i += 1
            if i = nrows then
                i = r
                lead += 1
                if lead = ncols then exit for
            end if
        end while
        for j = 1 to ncols
            temp = matrix[i, j]
            matrix[i, j] = matrix[r, j]
            matrix[r, j] = temp
        next
        n = matrix[r, lead]
        if n <> 1 then
            for j = 0 to ncols
                matrix[r, j] /= n
            next
        end if
        for i = 1 to nrows
            if i <> r then
                n = matrix[i, lead]
                for j = 1 to ncols
                    matrix[i, j] -= matrix[r, j] * n
                next
            end if
        next
        lead += 1
    next
end subroutine


      DIM matrix(2,3)
      matrix() = 1, 2, -1, -4, \
      \          2, 3, -1, -11, \
      \         -2, 0, -3, 22
      PROCrref(matrix())
      FOR row% = 0 TO 2
        FOR col% = 0 TO 3
          PRINT matrix(row%,col%);
        NEXT
        PRINT
      NEXT row%
      END

      DEF PROCrref(m())
      LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
      nrows% = DIM(m(),1)+1
      ncols% = DIM(m(),2)+1
      FOR r% = 0 TO nrows%-1
        IF lead% >= ncols% EXIT FOR
        i% = r%
        WHILE m(i%,lead%) = 0
          i% += 1
          IF i% = nrows% THEN
            i% = r%
            lead% += 1
            IF lead% = ncols% EXIT FOR
          ENDIF
        ENDWHILE
        FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
        n = m(r%,lead%)
        IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
        FOR i% = 0 TO nrows%-1
          IF i% <> r% THEN
            n = m(i%,lead%)
            FOR j% = 0 TO ncols%-1
              m(i%,j%) -= m(r%,j%) * n
            NEXT
          ENDIF
        NEXT
        lead% += 1
      NEXT r%
      ENDPROC


#include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))

#define EL_Type int

typedef struct sMtx {
    int     dim_x, dim_y;
    EL_Type *m_stor;
    EL_Type **mtx;
} *Matrix, sMatrix;

typedef struct sRvec {
    int     dim_x;
    EL_Type *m_stor;
} *RowVec, sRowVec;

Matrix NewMatrix( int x_dim, int y_dim )
{
    int n;
    Matrix m;
    m = TALLOC( 1, sMatrix);
    n = x_dim * y_dim;
    m->dim_x = x_dim;
    m->dim_y = y_dim;
    m->m_stor = TALLOC(n, EL_Type);
    m->mtx = TALLOC(m->dim_y, EL_Type *);
    for(n=0; n<y_dim; n++) {
        m->mtx[n] = m->m_stor+n*x_dim;
    }
    return m;
}

void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
    int ix;
    EL_Type *mr;
    mr = m->mtx[irow];
    for(ix=0; ix<m->dim_x; ix++)
        mr[ix] = v[ix];
}

Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
    Matrix m;
    int iy;
    m = NewMatrix(x_dim, y_dim);
    for (iy=0; iy<y_dim; iy++)
        MtxSetRow(m, iy, v[iy]);
    return m;
}

void MtxDisplay( Matrix m )
{
    int iy, ix;
    const char *sc;
    for (iy=0; iy<m->dim_y; iy++) {
        printf("   ");
        sc = " ";
        for (ix=0; ix<m->dim_x; ix++) {
            printf("%s %3d", sc, m->mtx[iy][ix]);
            sc = ",";
        }
        printf("\n");
    }
    printf("\n");
}

void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
    int ix;
    EL_Type *drow, *srow;
    drow = m->mtx[ixrdest];
    srow = m->mtx[ixrsrc];
    for (ix=0; ix<m->dim_x; ix++)
        drow[ix] += mplr * srow[ix];
//	printf("Mul row %d by %d and add to row %d\n", ixrsrc, mplr, ixrdest);
//	MtxDisplay(m);
}

void MtxSwapRows( Matrix m, int rix1, int rix2)
{
    EL_Type *r1, *r2, temp;
    int ix;
    if (rix1 == rix2) return;
    r1 = m->mtx[rix1];
    r2 = m->mtx[rix2];
    for (ix=0; ix<m->dim_x; ix++)
        temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
//	printf("Swap rows %d and %d\n", rix1, rix2);
//	MtxDisplay(m);
}

void MtxNormalizeRow( Matrix m, int rix, int lead)
{
    int ix;
    EL_Type *drow;
    EL_Type lv;
    drow = m->mtx[rix];
    lv = drow[lead];
    for (ix=0; ix<m->dim_x; ix++)
        drow[ix] /= lv;
//	printf("Normalize row %d\n", rix);
//	MtxDisplay(m);
}

#define MtxGet( m, rix, cix ) m->mtx[rix][cix]

void MtxToReducedREForm(Matrix m)
{
    int lead;
    int rix, iix;
    EL_Type lv;
    int rowCount = m->dim_y;

    lead = 0;
    for (rix=0; rix<rowCount; rix++) {
        if (lead >= m->dim_x)
            return;
        iix = rix;
        while (0 == MtxGet(m, iix,lead)) {
            iix++;
            if (iix == rowCount) {
                iix = rix;
                lead++;
                if (lead == m->dim_x)
                    return;
            }
        }
        MtxSwapRows(m, iix, rix );
        MtxNormalizeRow(m, rix, lead );
        for (iix=0; iix<rowCount; iix++) {
            if ( iix != rix ) {
                lv = MtxGet(m, iix, lead );
                MtxMulAndAddRows(m,iix, rix, -lv) ;
            }
        }
        lead++;
    }
}

int main()
{
    Matrix m1;
    static EL_Type r1[] = {1,2,-1,-4};
    static EL_Type r2[] = {2,3,-1,-11};
    static EL_Type r3[] = {-2,0,-3,22};
    static EL_Type *im[] = { r1, r2, r3 };

    m1 = InitMatrix( 4,3, im );
    printf("Initial\n");
    MtxDisplay(m1);
    MtxToReducedREForm(m1);
    printf("Reduced R-E form\n");
    MtxDisplay(m1);
    return 0;
}


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

int main(void)
{
    /* If your native locale doesn't use UTF-8 encoding
     * you need to replace the empty string with a
     * locale like "en_US.utf8"
     */
    char *locale = setlocale(LC_ALL, "");
    FILE *in = fopen("input.txt", "r");

    wint_t c;
    while ((c = fgetwc(in)) != WEOF)
        putwchar(c);
    fclose(in);

    return EXIT_SUCCESS;
}


#include <fstream>
#include <iostream>
#include <locale>

using namespace std;

int main(void)
{
    /* If your native locale doesn't use UTF-8 encoding
     * you need to replace the empty string with a
     * locale like "en_US.utf8"
     */
    std::locale::global(std::locale("")); // for C++
    std::cout.imbue(std::locale());
    ifstream in("input.txt");

    wchar_t c;
    while ((c = in.get()) != in.eof())
        wcout<<c;
    in.close();

    return EXIT_SUCCESS;
}


using System;
using System.IO;
using System.Text;

namespace RosettaFileByChar
{
    class Program
    {
        static char GetNextCharacter(StreamReader streamReader) => (char)streamReader.Read();

        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            char c;
            using (FileStream fs = File.OpenRead("input.txt"))
            {
                using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8))
                {
                    while (!streamReader.EndOfStream)
                    {
                        c = GetNextCharacter(streamReader);
                        Console.Write(c);
                    }
                }
            }
        }
    }
}


;; CLISP puts the external formats into a separate package
#+clisp (import 'charset:utf-8 'keyword)

(with-open-file (s "input.txt" :external-format :utf-8)
  (loop for c = (read-char s nil)
        while c
        do (format t "~a" c)))


?E                  -- Euler number
?PI                 -- pi
?log(E)             -- natural logarithm
?log10(10)          -- base 10 logarithm
?exp(log(5))        -- exponential
?sqrt(5)            -- square root
?abs(-1.2)          -- absolute value
?floor(-1.2)        -- floor,    -2
?ceil(-1.2)         -- ceiling,  -1
?round(-1.8)        -- rounded,  -2
?trunc(-1.8)        -- truncate, -1
?power(E,log(5))    -- displays 5.0
?power(10,log10(5)) -- displays 5.0
?INVLN10            -- displays 0.434..
?exp(1/INVLN10)     -- displays 10.0


M_E; //e
M_PI; //pi
sqrt(x); //square root
log(x); //natural logarithm--log base 10 also available (log10)
exp(x); //exponential
abs(x); //absolute value
floor(x); //floor
ceil(x); //ceiling
pow(x,y); //power


main =>
  println(math.e),
  println(math.pi),
  nl,

  println(sqrt(2)),
  nl,

  println(log(10)),                % base e
  println(log(math.pi,10)),        % some base, here pi
  println(log2(10)),               % base 2
  println(exp(2.302585092994046)),
  nl,

  println(abs(- math.e)),
  nl,
  println(floor(sqrt(101))),
  println(ceiling(sqrt(101))),
  nl,
  println(math.pi**math.e),        % power
  println(pow(math.pi,math.e)),    % power
  nl.


V f = File(‘input.txt’)
V line = 3

L 0 .< line - 1
   f.read_line()
print(f.read_line())


using System;

namespace rref
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] matrix = new int[3, 4]{
                {  1, 2, -1,  -4 },
                {  2, 3, -1, -11 },
                { -2, 0, -3,  22 }
            };
            matrix = rref(matrix);
        }

        private static int[,] rref(int[,] matrix)
        {
            int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
            for (int r = 0; r < rowCount; r++)
            {
                if (columnCount <= lead) break;
                int i = r;
                while (matrix[i, lead] == 0)
                {
                    i++;
                    if (i == rowCount)
                    {
                        i = r;
                        lead++;
                        if (columnCount == lead)
                        {
                        lead--;
                        break;
                        }
                    }
                }
                for (int j = 0; j < columnCount; j++)
                {
                    int temp = matrix[r, j];
                    matrix[r, j] = matrix[i, j];
                    matrix[i, j] = temp;
                }
                int div = matrix[r, lead];
                if(div != 0)
                    for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
                for (int j = 0; j < rowCount; j++)
                {
                    if (j != r)
                    {
                        int sub = matrix[j, lead];
                        for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
                    }
                }
                lead++;
            }
            return matrix;
        }
    }
}


File.open("input.txt") do |file|
  file.each_char { |c| p c }
end


program Read_a_file_character_by_character_UTF8;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Classes;

function GetNextCharacter(StreamReader: TStreamReader): char;
begin
  Result := chr(StreamReader.Read);
end;

const
  FileName: TFileName = 'input.txt';

begin
  if not FileExists(FileName) then
    raise Exception.Create('Error: File not exist.');

  var F := TStreamReader.Create(FileName, TEncoding.UTF8);

  while not F.EndOfStream do
  begin
    var c := GetNextCharacter(F);
    write(c);
  end;
  readln;
end.


#helper function that deals with non-ASCII code points
local (read-utf8-char) file tmp:
    !read-byte file
    if = :eof dup:
        drop
        raise :unicode-error
    resize-blob tmp ++ dup len tmp
    set-to tmp
    try:
        return !decode!utf-8 tmp
    catch unicode-error:
        if < 3 len tmp:
            raise :unicode-error
        (read-utf8-char) file tmp

#reader function
read-utf8-char file:
    !read-byte file
    if = :eof dup:
        return
    local :tmp make-blob 1
    set-to tmp 0
    try:
        return !decode!utf-8 tmp
    catch unicode-error:
        (read-utf8-char) file tmp

#if the module is used as a script, read from the file "input.txt",
#showing each code point separately
if = (name) :(main):
    local :file !open :read "input.txt"

    while true:
        read-utf8-char file
        if = :eof dup:
            drop
            !close file
            return
        !.


USING: kernel io io.encodings.utf8 io.files strings ;
IN: rosetta-code.read-one

"input.txt" utf8 [
    [ read1 dup ] [ 1string write ] while drop
] with-file-reader


Dim As Long f
f = Freefile

Dim As String filename = "file.txt"
Dim As String*1 txt

Open filename For Binary As #f
While Not Eof(f)
    txt = String(Lof(f), 0)
    Get #f, , txt
    Print txt;
Wend
Close #f
Sleep


(scl 12)  # 12 places after decimal point
(load "@lib/math.l")

(prinl (format (exp 1.0) *Scl))        # e, exp
(prinl (format pi *Scl))               # pi

(prinl (format (pow 2.0 0.5) *Scl))    # sqare root
(prinl (format (sqrt 2.0 1.0) *Scl))

(prinl (format (log 2.0) *Scl))        # logarithm
(prinl (format (exp 4.0) *Scl))        # exponential

(prinl (format (abs -7.2) *Scl))       # absolute value
(prinl (abs -123))

(prinl (format (pow 3.0 4.0) *Scl))    # power


/* e  not available other than by using exp(1q0).*/
/* pi not available other than by using a trig function such as: pi=4*atan(1) */
y = sqrt(x);
y = log(x);
y = log2(x);
y = log10(x);
y = exp(x);
y = abs(x);
y = floor(x);
y = ceil(x);
a = x**y;      /* power */
/* extra functions: */
y = erf(x);    /* the error function. */
y = erfc(x);   /* the error function complemented. */
y = gamma (x);
y = loggamma (x);


pi        ;;; Number Pi
sqrt(x)   ;;; Square root
log(x)    ;;; Natural logarithm
exp(x)    ;;; Exponential function
abs(x)    ;;; Absolute value
x ** y    ;;; x to the power y


Write-Host ([Math]::E)
Write-Host ([Math]::Pi)
Write-Host ([Math]::Sqrt(2))
Write-Host ([Math]::Log(2))
Write-Host ([Math]::Exp(2))
Write-Host ([Math]::Abs(-2))
Write-Host ([Math]::Floor(3.14))
Write-Host ([Math]::Ceiling(3.14))
Write-Host ([Math]::Pow(2, 3))


BYTE FUNC ReadLine(CHAR ARRAY fname CARD index CHAR ARRAY result)
  CHAR ARRAY line(255)
  CARD curr
  BYTE status,dev=[1]

  Close(dev)
  Open(dev,fname,4)
  curr=1 status=1
  WHILE Eof(dev)=0
  DO
    InputSD(dev,line)
    IF curr=index THEN
      SCopy(result,line)
      status=0
      EXIT
    FI
    curr==+1
  OD
  Close(dev)
RETURN (status)

PROC Test(CHAR ARRAY fname CARD index)
  CHAR ARRAY result(255)
  BYTE status

  PrintF("Reading %U line...%E",index)
  status=ReadLine(fname,index,result)
  IF status=0 THEN
    IF result(0)=0 THEN
      PrintF("%U line is empty.%E%E",index)
    ELSE
      PrintF("%U line is:%E""%S""%E%E",index,result)
    FI
  ELSEIF status=1 THEN
    PrintF("File contains less than %U lines.%E%E",index)
  FI
RETURN

PROC Main()
  CHAR ARRAY fname="H6:READ__96.ACT"

  PrintF("Reading ""%S""...%E%E",fname)
  Test(fname,7)
  Test(fname,24)
  Test(fname,50)
RETURN


with Ada.Text_IO;  use Ada.Text_IO;

procedure Rosetta_Read is
   File : File_Type;
begin
   Open (File => File,
         Mode => In_File,
         Name => "rosetta_read.adb");
   Set_Line (File, To => 7);

   declare
      Line_7 : constant String := Get_Line (File);
   begin
      if Line_7'Length = 0 then
         Put_Line ("Line 7 is empty.");
      else
         Put_Line (Line_7);
      end if;
   end;

   Close (File);
exception
   when End_Error =>
      Put_Line ("The file contains fewer than 7 lines.");
      Close (File);
   when Storage_Error =>
      Put_Line ("Line 7 is too long to load.");
      Close (File);
end Rosetta_Read;


void
read_line(text &line, text path, integer n)
{
    file f;

    f.affix(path);

    call_n(n, f_slip, f);

    f.line(line);
}

integer
main(void)
{
    if (1 < argc()) {
        text line;

        read_line(line, argv(1), 6);

        o_("7th line is:\n", line, "\n");
    }

    0;
}


#include <algorithm> // for std::swap
#include <cstddef>
#include <cassert>

// Matrix traits: This describes how a matrix is accessed. By
// externalizing this information into a traits class, the same code
// can be used both with native arrays and matrix classes. To use the
// default implementation of the traits class, a matrix type has to
// provide the following definitions as members:
//
// * typedef ... index_type;
//   - The type used for indexing (e.g. size_t)
// * typedef ... value_type;
//   - The element type of the matrix (e.g. double)
// * index_type min_row() const;
//   - returns the minimal allowed row index
// * index_type max_row() const;
//   - returns the maximal allowed row index
// * index_type min_column() const;
//   - returns the minimal allowed column index
// * index_type max_column() const;
//   - returns the maximal allowed column index
// * value_type& operator()(index_type i, index_type k)
//   - returns a reference to the element i,k, where
//     min_row() <= i <= max_row()
//     min_column() <= k <= max_column()
// * value_type operator()(index_type i, index_type k) const
//   - returns the value of element i,k
//
// Note that the functions are all inline and simple, so the compiler
// should completely optimize them away.
template<typename MatrixType> struct matrix_traits
{
  typedef typename MatrixType::index_type index_type;
  typedef typename MatrixType::value_type value_type;
  static index_type min_row(MatrixType const& A)
  { return A.min_row(); }
  static index_type max_row(MatrixType const& A)
  { return A.max_row(); }
  static index_type min_column(MatrixType const& A)
  { return A.min_column(); }
  static index_type max_column(MatrixType const& A)
  { return A.max_column(); }
  static value_type& element(MatrixType& A, index_type i, index_type k)
  { return A(i,k); }
  static value_type element(MatrixType const& A, index_type i, index_type k)
  { return A(i,k); }
};

// specialization of the matrix traits for built-in two-dimensional
// arrays
template<typename T, std::size_t rows, std::size_t columns>
 struct matrix_traits<T[rows][columns]>
{
  typedef std::size_t index_type;
  typedef T value_type;
  static index_type min_row(T const (&)[rows][columns])
  { return 0; }
  static index_type max_row(T const (&)[rows][columns])
  { return rows-1; }
  static index_type min_column(T const (&)[rows][columns])
  { return 0; }
  static index_type max_column(T const (&)[rows][columns])
  { return columns-1; }
  static value_type& element(T (&A)[rows][columns],
                             index_type i, index_type k)
  { return A[i][k]; }
  static value_type element(T const (&A)[rows][columns],
                            index_type i, index_type k)
  { return A[i][k]; }
};

// Swap rows i and k of a matrix A
// Note that due to the reference, both dimensions are preserved for
// built-in arrays
template<typename MatrixType>
 void swap_rows(MatrixType& A,
                 typename matrix_traits<MatrixType>::index_type i,
                 typename matrix_traits<MatrixType>::index_type k)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  // check indices
  assert(mt.min_row(A) <= i);
  assert(i <= mt.max_row(A));

  assert(mt.min_row(A) <= k);
  assert(k <= mt.max_row(A));

  for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
    std::swap(mt.element(A, i, col), mt.element(A, k, col));
}

// divide row i of matrix A by v
template<typename MatrixType>
 void divide_row(MatrixType& A,
                  typename matrix_traits<MatrixType>::index_type i,
                  typename matrix_traits<MatrixType>::value_type v)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  assert(mt.min_row(A) <= i);
  assert(i <= mt.max_row(A));

  assert(v != 0);

  for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
    mt.element(A, i, col) /= v;
}

// in matrix A, add v times row k to row i
template<typename MatrixType>
 void add_multiple_row(MatrixType& A,
                  typename matrix_traits<MatrixType>::index_type i,
                  typename matrix_traits<MatrixType>::index_type k,
                  typename matrix_traits<MatrixType>::value_type v)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  assert(mt.min_row(A) <= i);
  assert(i <= mt.max_row(A));

  assert(mt.min_row(A) <= k);
  assert(k <= mt.max_row(A));

  for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
    mt.element(A, i, col) += v * mt.element(A, k, col);
}

// convert A to reduced row echelon form
template<typename MatrixType>
 void to_reduced_row_echelon_form(MatrixType& A)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  index_type lead = mt.min_row(A);

  for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
  {
    if (lead > mt.max_column(A))
      return;
    index_type i = row;
    while (mt.element(A, i, lead) == 0)
    {
      ++i;
      if (i > mt.max_row(A))
      {
        i = row;
        ++lead;
        if (lead > mt.max_column(A))
          return;
      }
    }
    swap_rows(A, i, row);
    divide_row(A, row, mt.element(A, row, lead));
    for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
    {
      if (i != row)
        add_multiple_row(A, i, row, -mt.element(A, i, lead));
    }
  }
}

// test code
#include <iostream>

int main()
{
  double M[3][4] = { {  1, 2, -1,  -4 },
                     {  2, 3, -1, -11 },
                     { -2, 0, -3,  22 } };

  to_reduced_row_echelon_form(M);
  for (int i = 0; i < 3; ++i)
  {
    for (int j = 0; j < 4; ++j)
      std::cout << M[i][j] << '\t';
    std::cout << "\n";
  }

  return EXIT_SUCCESS;
}


import io.{InputStreamReader, FileInputStream}

r = InputStreamReader( FileInputStream('input.txt'), 'UTF-8' )

while (ch = r.read()) != -1
  print( chr(ch) )

r.close()


package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

func Runer(r io.RuneReader) func() (rune, error) {
    return func() (r rune, err error) {
        r, _, err = r.ReadRune()
        return
    }
}

func main() {
    runes := Runer(bufio.NewReader(os.Stdin))
    for r, err := runes(); err != nil; r,err = runes() {
        fmt.Printf("%c", r)
    }
}


#!/usr/bin/env runhaskell

{- The procedure to read a UTF-8 character is just:

   hGetChar :: Handle -> IO Char

   assuming that the encoding for the handle has been set to utf8.
-}

import System.Environment (getArgs)
import System.IO (
        Handle, IOMode (..),
        hGetChar, hIsEOF, hSetEncoding, stdin, utf8, withFile
    )
import Control.Monad (forM_, unless)
import Text.Printf (printf)
import Data.Char (ord)

processCharacters :: Handle -> IO ()
processCharacters h = do
  done <- hIsEOF h
  unless done $ do
    c <- hGetChar h
    putStrLn $ printf "U+%04X" (ord c)
    processCharacters h

processOneFile :: Handle -> IO ()
processOneFile h = do
  hSetEncoding h utf8
  processCharacters h

{- You can specify one or more files on the command line, or if no
   files are specified, it reads from standard input.
-}
main :: IO ()
main = do
  args <- getArgs
  case args of
    [] -> processOneFile stdin
    xs -> forM_ xs $ \name -> do
      putStrLn name
      withFile name ReadMode processOneFile


Debug #E
Debug #PI
Debug Sqr(f)
Debug Log(f)
Debug Exp(f)
Debug Log10(f)
Debug Abs(f)
Debug Pow(f,f)


import math

math.e          # e
math.pi         # pi
math.sqrt(x)    # square root  (Also commonly seen as x ** 0.5 to obviate importing the math module)
math.log(x)     # natural logarithm
math.log10(x)   # base 10 logarithm
math.exp(x)     # e raised to the power of x
abs(x)          # absolute value
math.floor(x)   # floor
math.ceil(x)    # ceiling
x ** y          # exponentiation
pow(x, y[, n])  # exponentiation [, modulo n (useful in certain encryption/decryption algorithms)]

# The math module constants and functions can, of course, be imported directly by:
#   from math import e, pi, sqrt, log, log10, exp, floor, ceil


exp(1)             # e
pi                 # pi
sqrt(x)            # square root
log(x)             # natural logarithm
log10(x)           # base 10 logarithm
log(x, y)          # arbitrary base logarithm
exp(x)             # exponential
abs(x)             # absolute value
floor(x)           # floor
ceiling(x)         # ceiling
x^y                # power


(exp 1)         ; e
pi              ; pi
(sqrt x)        ; square root
(log x)         ; natural logarithm
(exp x)         ; exponential
(abs x)         ; absolute value
(floor x)       ; floor
(ceiling x)     ; ceiling
(expt x y)      ; power


# reads the line with number "number" (counting from 1)       #
# from the file named "file name" and returns the text of the #
# in "line". If an error occurs, the result is FALSE and a    #
# message is returned in "err". If no error occurs, TRUE is   #
# returned                                                    #
PROC read specific line = ( STRING     file name
                          , INT        number        # line 7 #
                          , REF STRING line
                          , REF STRING err
                          )BOOL:
     IF FILE    input file;
        line := "";
        open( input file, file name, stand in channel ) /= 0
     THEN
        # failed to open the file #
        err := "Unable to open """ + file name + """";
        FALSE
     ELSE
        # file opened OK #
        err         := "";
        BOOL at eof := FALSE;
        # set the EOF handler for the file #
        on logical file end( input file
                           , ( REF FILE f )BOOL:
                             BEGIN
                                 # note that we reached EOF on the #
                                 # latest read #
                                 at eof := TRUE;

                                 # return TRUE so processing can continue #
                                 TRUE
                             END
                           );
         INT    line number := 0;
         STRING text;
         WHILE line number < number
           AND NOT at eof
         DO
             get( input file, ( text, newline ) );
             line number +:= 1
         OD;
         # close the file #
         close( input file );
         # return the line or an error message depending on whether #
         # we got a line with the required number or not            #
         IF line number = number
         THEN
             # got the required line #
             line := text;
             TRUE
         ELSE
             # not enough lines in the file #
             err  := """" + file name + """ is too short";
             FALSE
         FI
     FI; # read specific line #
main:(
    # read the seventh line of this source and print it #
    # (or an error message if we can't)                 #
    STRING line;
    STRING err;
    IF read specific line( "read-specific-line.a68", 7, line, err )
    THEN
        # got the line #
        print( ( "line seven is: """ + line + """", newline ) )
    ELSE
        # got an error #
        print( ( "unable to read line: """ + err + """" ) )
    FI
)


#include <hopper.h>
#define MAX_LINE_SIZE  1000
main:
   v=0, fd=0
   fsearch("-r $'\n'","archivo.txt")(v)
   fopen(OPEN_READ,"archivo.txt")(fd)
   {"Line #7 = "}, fgetsline(fd,MAX_LINE_SIZE,7,v), println
   try
      fgetsline(fd,MAX_LINE_SIZE,10,v),
   catch(e)
      {"Error search line (code=",e,"): "},get str error
   finish
   println
   fclose(fd)
exit(0)


(defun convert-to-row-echelon-form (matrix)
  (let* ((dimensions (array-dimensions matrix))
	 (row-count (first dimensions))
	 (column-count (second dimensions))
	 (lead 0))
    (labels ((find-pivot (start lead)
	       (let ((i start))
		 (loop
		    :while (zerop (aref matrix i lead))
		    :do (progn
			  (incf i)
			  (when (= i row-count)
			    (setf i start)
			    (incf lead)
			    (when (= lead column-count)
			      (return-from convert-to-row-echelon-form matrix))))
		    :finally (return (values i lead)))))
	     (swap-rows (r1 r2)
	       (loop
		  :for c :upfrom 0 :below column-count
		  :do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
	     (divide-row (r value)
	       (loop
		  :for c :upfrom 0 :below column-count
		  :do (setf (aref matrix r c)
			    (/ (aref matrix r c) value)))))
      (loop
	 :for r :upfrom 0 :below row-count
	 :when (<= column-count lead)
	 :do (return matrix)
	 :do (multiple-value-bind (i nlead) (find-pivot r lead)
	       (setf lead nlead)
	       (swap-rows i r)
	       (divide-row r (aref matrix r lead))
	       (loop
		  :for i :upfrom 0 :below row-count
		  :when (/= i r)
		  :do (let ((scale (aref matrix i lead)))
			(loop
			   :for c :upfrom 0 :below column-count
			   :do (decf (aref matrix i c)
				     (* scale (aref matrix r c))))))
	       (incf lead))
	 :finally (return matrix)))))


import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Main {

    public static void main(String[] args) throws IOException {
        var reader = new FileReader("input.txt", StandardCharsets.UTF_8);
        while (true) {
            int c = reader.read();
            if (c == -1) break;
            System.out.print(Character.toChars(c));
        }
    }
}


def readc:
  inputs + "\n" | explode[] | [.] | implode;


open("myfilename") do f
    while !eof(f)
        c = read(f, Char)
        println(c)
    end
end


// version 1.1.2

import java.io.File

const val EOF = -1

fun main(args: Array<String>) {
    val reader = File("input.txt").reader()  // uses UTF-8 by default
    reader.use {
        while (true) {
            val c = reader.read()
            if (c == EOF) break
            print(c.toChar()) // echo to console
        }
    }
}


-- Return whether the given string is a single ASCII character.
function is_ascii (str)
  return string.match(str, "[\0-\x7F]")
end

-- Return whether the given string is an initial byte in a multibyte sequence.
function is_init (str)
    return string.match(str, "[\xC2-\xF4]")
end

-- Return whether the given string is a continuation byte in a multibyte sequence.
function is_cont (str)
    return string.match(str, "[\x80-\xBF]")
end

-- Accept a filestream.
-- Return the next UTF8 character in the file.
function read_char (file)
    local multibyte -- build a valid multibyte Unicode character

    for c in file:lines(1) do
        if is_ascii(c) then
            if multibyte then
                -- We've finished reading a Unicode character; unread the next byte,
                -- and return the Unicode character.
                file:seek("cur", -1)
                return multibyte
            else
                return c
            end
        elseif is_init(c) then
            if multibyte then
                file:seek("cur", -1)
                return multibyte
            else
                multibyte = c
            end
        elseif is_cont(c) then
            multibyte = multibyte .. c
        else
            assert(false)
        end
    end
end

-- Test.
function read_all ()
    testfile = io.open("tmp.txt", "w")
    testfile:write("𝄞AöЖ€𝄞Ελληνικάyä®€成长汉\n")
    testfile:close()
    testfile = io.open("tmp.txt", "r")

    while true do
        local c = read_char(testfile)
        if not c then return else io.write(" ", c) end
    end
end


say e;            # e
say π; # or pi    # pi
say τ; # or tau   # tau

# Common mathmatical function are availble
# as subroutines and as numeric methods.
# It is a matter of personal taste and
# programming style as to which is used.
say sqrt 2;       # Square root
say 2.sqrt;       # Square root

# If you omit a base, does natural logarithm
say log 2;        # Natural logarithm
say 2.log;        # Natural logarithm

# Specify a base if other than e
say log 4, 10;    # Base 10 logarithm
say 4.log(10);    # Base 10 logarithm
say 4.log10;      # Convenience, base 10 only logarithm

say exp 7;        # Exponentiation base e
say 7.exp;        # Exponentiation base e

# Specify a base if other than e
say exp 7, 4;     # Exponentiation
say 7.exp(4);     # Exponentiation
say 4 ** 7;       # Exponentiation

say abs -2;       # Absolute value
say (-2).abs;     # Absolute value

say floor -3.5;   # Floor
say (-3.5).floor; # Floor

say ceiling pi;   # Ceiling
say pi.ceiling;   # Ceiling

say e ** π\i + 1 ≅ 0; # :-)


a=abs(y)                       /*takes the absolute value of y.*/


FileReadLine, OutputVar, filename.txt, 7
if ErrorLevel
   MsgBox, There was an error reading the 7th line of the file


#!/usr/bin/awk -f
#usage: readnthline.awk -v lineno=6 filename

FNR==lineno { storedline=$0; found++ }

END {
    if (found < 1) {
        print "ERROR: Line", lineno, "not found"
        exit 1
    }
    print storedline
}


f = freefile
filename$ = "input.txt"
open f, filename$

lineapedida = 7
cont = 0
while not (eof(f))
    linea$ = readline(f)
    cont += 1
    if cont = lineapedida then
	if trim(linea$) = "" then print "The 7th line is empty" else print linea$
	exit while
    end if
end while
if cont < lineapedida then print "There are only "; cont; " lines in the file"
close f
end


@echo off

for /f "skip=6 tokens=*" %%i in (file.txt) do (
  set line7=%%i
  goto break
)
:break
echo Line 7 is: %line7%
pause>nul


import std.stdio, std.algorithm, std.array, std.conv;

void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
    if (M.empty)
        return;
    immutable nrows = M.length;
    immutable ncols = M[0].length;

    size_t lead;
    foreach (immutable r; 0 .. nrows) {
        if (ncols <= lead)
            return;
        {
            size_t i = r;
            while (M[i][lead] == 0) {
                i++;
                if (nrows == i) {
                    i = r;
                    lead++;
                    if (ncols == lead)
                        return;
                }
            }
            swap(M[i], M[r]);
        }

        M[r][] /= M[r][lead];
        foreach (j, ref mj; M)
            if (j != r)
                mj[] -= M[r][] * mj[lead];
        lead++;
    }
}

void main() {
    auto A = [[ 1, 2, -1,  -4],
              [ 2, 3, -1, -11],
              [-2, 0, -3,  22]];

    A.toReducedRowEchelonForm;
    writefln("%(%(%2d %)\n%)", A);
}


Module checkit {
      \\ prepare a file
      \\ Save.Doc and Append.Doc  to file, Load.Doc and Merge.Doc from file
      document a$
      a$={First Line
            Second line
            Third Line
            Ελληνικά Greek Letters
            yä®€
            成长汉
            }
      Save.Doc a$, "checkthis.txt", 2  ' 2 for UTF-8
      b$="*"
      final$=""
      buffer Clear bytes as byte*16
      Buffer One as byte
      Buffer Two as byte*2
      Buffer Three as byte*3
      Locale 1033
      open "checkthis.txt" for input as #f
      seek#f, 4 ' skip BOM
      While b$<>"" {
            GetOneUtf8Char(&b$)
            final$+=b$
      }
      close #f
      Report final$
      Sub GetOneUtf8Char(&ch$)
            ch$=""
            if Eof(#f) then Exit Sub
            Get #f, One
            Return Bytes, 0:=Eval(one, 0)
            local mrk=Eval(one, 0)
           Try ok {
                  If Binary.And(mrk, 0xE0)=0xC0 then {
                        Get #f,one
                        Return Bytes, 1:=Eval$(one, 0,1)
                        ch$=Eval$(Bytes, 0, 2)
                  } Else.if Binary.And(mrk, 0xF0)=0xE0 then {
                        Get #f,two
                        Return Bytes, 1:=Eval$(two,0,2)
                        ch$=Eval$(Bytes, 0, 3)
                  } Else.if Binary.And(mrk, 0xF8)=0xF0 then {
                        Get #f,three
                        Return Bytes, 1:=Eval$(three, 0, 3)
                        ch$=Eval$(Bytes, 0, 4)
                  } Else ch$=Eval$(Bytes, 0, 1)
            }
            if Error or not ok then ch$="" : exit sub
            ch$=left$(string$(ch$ as Utf8dec),1)
      End Sub
}
checkit


str = OpenRead["file.txt"];
ToString[Read[str, "Character"], CharacterEncoding -> "UTF-8"]


/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20

runSample(arg)
return

-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
method readCharacters(fName) public static binary returns String
  slurped = String('')
  slrp = StringBuilder()
  fr = Reader null
  fFile = File(fName)
  EOF = int -1 -- End Of File indicator
  do
    fr = BufferedReader(FileReader(fFile))
    ic = int
    cc = char
    -- read the contents of the file one character at a time
    loop label rdr forever
      -- Reader.read reads a single character as an integer value in the range 0 - 65535 [0x00 - 0xffff]
      -- or -1 on end of stream i.e. End Of File
      ic = fr.read()
      if ic == EOF then leave rdr
      cc = Rexx(ic).d2c
      slrp.append(cc)
      end rdr
    -- load the results of the read into a variable
    slurped = slrp.toString()
  catch fex = FileNotFoundException
    fex.printStackTrace()
  catch iex = IOException
    iex.printStackTrace()
  finally
    if fr \= null then do
      fr.close()
      catch iex = IOException
        iex.printStackTrace()
      end
  end
  return slurped

-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
method encodingDetails(str = String) public static
  stlen = str.length()
  cplen = Character.codePointCount(str, 0, stlen)
  say 'Unicode: length="'stlen'" code_point_count="'cplen'" string="'str'"'
  loop ix = 0 to stlen - 1
    cp = Rexx(Character.codePointAt(str, ix))
    cc = Rexx(Character.charCount(cp))
    say '  'formatCodePoint(ix, cc, cp)
    if cc > 1 then do
      surrogates = [Rexx(Character.highSurrogate(cp)).c2d(), Rexx(Character.lowSurrogate(cp)).c2d()]
      loop sx = 0 to cc - 1
        ix = ix + sx
        cp = surrogates[sx]
        say '  'formatCodePoint(ix, 1, cp)
        end sx
      end
    end ix
  say
  return

-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
-- @see http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
-- @since Java 1.7
method formatCodePoint(ix, cc, cp) private static
  scp = Rexx(Character.toChars(cp))
  icp = cp.d2x(8).x2d(9) -- signed to unsigned conversion
  ocp = Rexx(Integer.toOctalString(icp))
  x_utf16 = ''
  x_utf8  = ''
  do
    b_utf16 = String(scp).getBytes('UTF-16BE')
    b_utf8  = String(scp).getBytes('UTF-8')
    loop bv = 0 to b_utf16.length - 1 by 2
      x_utf16 = x_utf16 Rexx(b_utf16[bv]).d2x(2) || Rexx(b_utf16[bv + 1]).d2x(2)
      end bv
    loop bv = 0 to b_utf8.length - 1
      x_utf8 = x_utf8 Rexx(b_utf8[bv]).d2x(2)
      end bv
    x_utf16 = x_utf16.space(1, ',')
    x_utf8  = x_utf8.space(1, ',')
  catch ex = UnsupportedEncodingException
    ex.printStackTrace()
  end
  cpName = Character.getName(cp)
  fmt =                        -
    'CodePoint:'               -
    'index="'ix.right(3, 0)'"' -
    'character_count="'cc'"'   -
    'id="U+'cp.d2x(5)'"'       -
    'hex="0x'cp.d2x(6)'"'      -
    'dec="'icp.right(7, 0)'"'  -
    'oct="'ocp.right(7, 0)'"'  -
    'char="'scp'"'             -
    'utf-16="'x_utf16'"'       -
    'utf-8="'x_utf8'"'         -
    'name="'cpName'"'
  return fmt

-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
method runSample(arg) public static
  parse arg fileNames
  if fileNames = '' then fileNames = 'data/utf8-001.txt'
  loop while fileNames \= ''
    parse fileNames fileName fileNames
    slurped = readCharacters(fileName)
    say "Input:" slurped
    encodingDetails(slurped)
    end
  say
  return


>> const
   e                    euler           ln10            ln2             lnpi
   log10e               log2e           pi              pihalf          piquarter
   rpi                  sqrt2           sqrt2r          sqrt3           sqrtpi
   tworpi


x.abs #absolute value
x.magnitude #absolute value
x.floor #floor
x.ceil #ceiling
x ** y #power
include Math
E #e
PI #pi
sqrt(x) #square root
log(x) #natural logarithm
log(x, y) #logarithm base y
log10(x) #base 10 logarithm
exp(x) #exponential


print "exp:";chr$(9);   EXP(1)
print "PI:";chr$(9);    22/7
print "Sqr2:";chr$(9);  SQR(2)
print "Log2:";chr$(9);  LOG(2) : REM Base 10
print "Exp2:";chr$(9);  EXP(2)
print "Abs2:";chr$(9);  ABS(-2)
print "Floor:";chr$(9); INT(1.534)
print "ceil:";chr$(9);  val(using("###",1.534))
print "Power:";chr$(9); 1.23^4


use std::f64::consts::*;

fn main() {
    // e (base of the natural logarithm)
    let mut x = E;
    // π
    x += PI;
    // square root
    x = x.sqrt();
    // logarithm (any base allowed)
    x = x.ln();
    // ceiling (smallest integer not less than this number--not the same as round up)
    x = x.ceil();
    // exponential (ex)
    x = x.exp();
    // absolute value (a.k.a. "magnitude")
    x = x.abs();
    // floor (largest integer less than or equal to this number--not the same as truncate or int)
    x = x.floor();
    // power (xy)
    x = x.powf(x);

    assert_eq!(x, 4.0);
}


      filepath$ = @lib$ + "..\licence.txt"
      requiredline% = 7

      file% = OPENIN(filepath$)
      IF file%=0 ERROR 100, "File could not be opened"
      FOR i% = 1 TO requiredline%
        IF EOF#file% ERROR 100, "File contains too few lines"
        INPUT #file%, text$
      NEXT
      CLOSE #file%

      IF ASCtext$=10 text$ = MID$(text$,2)
      PRINT text$


#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>

/* following code assumes all file operations succeed. In practice,
 * return codes from open, close, fstat, mmap, munmap all need to be
 * checked for error.
*/
int read_file_line(const char *path, int line_no)
{
	struct stat s;
	char *buf;
	off_t start = -1, end = -1;
	size_t i;
	int ln, fd, ret = 1;

	if (line_no == 1) start = 0;
	else if (line_no < 1){
		warn("line_no too small");
		return 0; /* line_no starts at 1; less is error */
	}

	line_no--; /* back to zero based, easier */

	fd = open(path, O_RDONLY);
	fstat(fd, &s);

	/* Map the whole file.  If the file is huge (up to GBs), OS will swap
	 * pages in and out, and because search for lines goes sequentially
	 * and never accesses more than one page at a time, penalty is low.
	 * If the file is HUGE, such that OS can't find an address space to map
	 * it, we got a real problem.  In practice one would repeatedly map small
	 * chunks, say 1MB at a time, and find the offsets of the line along the
	 * way.  Although, if file is really so huge, the line itself can't be
	 * guaranteed small enough to be "stored in memory", so there.
	 */
	buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

	/* optional; if the file is large, tell OS to read ahead */
	madvise(buf, s.st_size, MADV_SEQUENTIAL);

	for (i = ln = 0; i < s.st_size && ln <= line_no; i++) {
		if (buf[i] != '\n') continue;

		if (++ln == line_no) start = i + 1;
		else if (ln == line_no + 1) end = i + 1;
	}

	if (start >= s.st_size || start < 0) {
		warn("file does not have line %d", line_no + 1);
		ret = 0;
	} else {
		/* 	do something with the line here, like
		write(STDOUT_FILENO, buf + start, end - start);
			or copy it out, or something
		*/
	}

	munmap(buf, s.st_size);
	close(fd);

	return ret;
}


function ToReducedRowEchelonForm(sequence M)
    integer lead,rowCount,columnCount,i
    sequence temp
    lead = 1
    rowCount = length(M)
    columnCount = length(M[1])
    for r = 1 to rowCount do
        if columnCount <= lead then
            exit
        end if
        i = r
        while M[i][lead] = 0 do
            i += 1
            if rowCount = i then
                i = r
                lead += 1
                if columnCount = lead then
                    exit
                end if
            end if
        end while
        temp = M[i]
        M[i] = M[r]
        M[r] = temp
        M[r] /= M[r][lead]
        for j = 1 to rowCount do
            if j != r then
                M[j] -= M[j][lead]*M[r]
            end if
        end for
        lead += 1
    end for
    return M
end function

? ToReducedRowEchelonForm(
    { { 1, 2, -1, -4 },
      { 2, 3, -1, -11 },
      { -2, 0, -3, 22 } })


USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .


import unicode

proc readUtf8(f: File): string =
  ## Return next UTF-8 character as a string.
  while true:
    result.add f.readChar()
    if result.validateUtf8() == -1: break

iterator readUtf8(f: File): string =
  ## Yield successive UTF-8 characters from file "f".
  var res: string
  while not f.endOfFile:
    res.setLen(0)
    while true:
      res.add f.readChar()
      if res.validateUtf8() == -1: break
    yield res


(* Read a file char by char *)
   program ReadFileByChar;
   var
      InputFile,OutputFile: file of char;
      InputChar: char;
   begin
      Assign(InputFile, 'testin.txt');
      Reset(InputFile);
      Assign(OutputFile, 'testout.txt');
      Rewrite(OutputFile);
      while not Eof(InputFile) do
      begin
         Read(InputFile, InputChar);
         Write(OutputFile, InputChar)
      end;
      Close(InputFile);
      Close(OutputFile)
   end.


binmode STDOUT, ':utf8';  # so we can print wide chars without warning

open my $fh, "<:encoding(UTF-8)", "input.txt" or die "$!\n";

while (read $fh, my $char, 1) {
    printf "got character $char [U+%04x]\n", ord $char;
}

close $fh;


constant INVALID_UTF8 = #FFFD

function get_one_utf8_char(integer fn)
-- returns INVALID_UTF8 on error, else a string of 1..4 bytes representing one character
object res
integer headb, bytes, c

    -- headb = first byte of utf-8 character:
    headb = getc(fn)
    if headb=-1 then return -1 end if
    res = ""&headb

    -- calculate length of utf-8 character in bytes (1..4):
    if    headb<0           then bytes = 0  -- (utf-8 starts at #0)
    elsif headb<=0b01111111 then bytes = 1  -- 0b_0xxx_xxxx
    elsif headb<=0b10111111 then bytes = 0  -- (it's a tail byte)
    elsif headb<=0b11011111 then bytes = 2  -- 0b_110x_xxxx
    elsif headb<=0b11101111 then bytes = 3  -- 0b_1110_xxxx
    elsif headb<=0b11110100 then bytes = 4  -- 0b_1111_0xzz
    else                         bytes = 0  -- (utf-8 ends at #10FFFF)
    end if

    -- 2..4 bytes encoding (tail range: 0b_1000_0000..0b_1011_1111);
    for j=1 to bytes-1 do                   -- tail bytes are valid?
        c = getc(fn)
        if c<#80 or c>#BF then
            bytes = 0                       -- invalid tail byte or eof
            exit
        end if
        res &= c
    end for

    -- 1 byte encoding (head range: 0b_0000_0000..0b_0111_1111):
    if bytes=1 then
        c = headb                               -- UTF-8 = ASCII

    -- 2 bytes encoding (head range: 0b_1100_0000..0b_1101_1111):
    elsif bytes=2 then
        c = and_bits(headb, #1F)*#40 +          -- 0b110[7..11] headb
            and_bits(res[2], #3F)               -- 0b10[1..6] tail
        if c>#7FF then ?9/0 end if              -- sanity check
        if c<#80 then                           -- long form?
            res = INVALID_UTF8
        end if

    -- 3 bytes encoding (head range: 0b_1110_0000..0b_1110_1111):
    elsif bytes=3 then
        c = and_bits(headb, #0F)*#1000 +        -- 0b1110[13..16] head
            and_bits(res[2], #3F)*#40 +         -- 0b10[7..12] tail
            and_bits(res[3], #3F)               -- 0b10[1..6] tail
        if c>#FFFF then ?9/0 end if             -- sanity check
        if c<#800                               -- long form?
        or (c>=#D800 and c<=#DFFF) then         -- utf-16 incompatible
            res = INVALID_UTF8
        end if

    -- 4 bytes encoding (head range: 0b_1111_0000..0b_1111_0111):
    elsif bytes=4 then
        c = and_bits(headb, #07)*#040000 +      -- 0b11110[19..21] head
            and_bits(res[2], #3F)*#1000 +       -- 0b10[13..18] tail
            and_bits(res[3], #3F)*#0040 +       -- 0b10[7..12] tail
            and_bits(res[4], #3F)               -- 0b10[1..6] tail
        if c<#10000                             -- long form?
        or c>#10FFFF then
            res = INVALID_UTF8                  -- utf-8 ends at #10FFFF
        end if

    -- bytes = 0; current byte is not encoded correctly:
    else
        res = INVALID_UTF8
    end if

    return res
end function


object RealConstantsFunctions extends App{
  println(math.E)                // e
  println(math.Pi)               // pi
  println(math.sqrt(2.0))        // square root
  println(math.log(math.E))      // log to base e
  println(math.log10(10.0))      // log to base 10
  println(math.exp(1.0))         // exponential
  println(math.abs(-1))          // absolute value
  println(math.floor(-2.5))      // floor
  println(math.ceil(-2.5))       // ceiling
  println(math.pow(2.5, 3.5))    // power
}


(sqrt x) ;square root
(log x) ;natural logarithm
(exp x) ;exponential
(abs x) ;absolute value
(floor x) ;floor
(ceiling x) ;ceiling
(expt x y) ;power


Num.e     # e
Num.pi    # pi
x.sqrt    # square root
x.log     # natural logarithm
x.log10   # base 10 logarithm
x.exp     # e raised to the power of x
x.abs     # absolute value
x.floor   # floor
x.ceil    # ceiling
x**y      # exponentiation


using System;
using System.IO;

namespace GetLine
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine(GetLine(args[0], uint.Parse(args[1])));
        }

        private static string GetLine(string path, uint line)
        {
            using (var reader = new StreamReader(path))
            {
                try
                {
                    for (uint i = 0; i <= line; i++)
                    {
                        if (reader.EndOfStream)
                            return string.Format("There {1} less than {0} line{2} in the file.", line,
                                                 ((line == 1) ? "is" : "are"), ((line == 1) ? "" : "s"));

                        if (i == line)
                            return reader.ReadLine();

                        reader.ReadLine();
                    }
                }
                catch (IOException ex)
                {
                    return ex.Message;
                }
                catch (OutOfMemoryException ex)
                {
                    return ex.Message;
                }
            }

            throw new Exception("Something bad happened.");
        }
    }
}


#include <string>
#include <fstream>
#include <iostream>

int main( ) {
   std::cout << "Which file do you want to look at ?\n" ;
   std::string input ;
   std::getline( std::cin , input ) ;
   std::ifstream infile( input.c_str( ) , std::ios::in ) ;
   std::string file( input ) ;
   std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
   std::getline( std::cin , input ) ;
   int linenumber = std::stoi( input ) ;
   int lines_read = 0 ;
   std::string line ;
   if ( infile.is_open( ) ) {
      while ( infile ) {
	 getline( infile , line ) ;
	 lines_read++ ;
	 if ( lines_read == linenumber ) {
	    std::cout << line << std::endl ;
	    break ;
	 }
      }
      infile.close( ) ;
      if ( lines_read < linenumber )
	 std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
      return 0 ;
   }
   else {
      std::cerr << "Could not find file " << file << " !\n" ;
      return 1 ;
   }
}


module Rref
  implicit none
contains
  subroutine to_rref(matrix)
    real, dimension(:,:), intent(inout) :: matrix

    integer :: pivot, norow, nocolumn
    integer :: r, i
    real, dimension(:), allocatable :: trow

    pivot = 1
    norow = size(matrix, 1)
    nocolumn = size(matrix, 2)

    allocate(trow(nocolumn))

    do r = 1, norow
       if ( nocolumn <= pivot ) exit
       i = r
       do while ( matrix(i, pivot) == 0 )
          i = i + 1
          if ( norow == i ) then
             i = r
             pivot = pivot + 1
             if ( nocolumn == pivot ) return
          end if
       end do
       trow = matrix(i, :)
       matrix(i, :) = matrix(r, :)
       matrix(r, :) = trow
       matrix(r, :) = matrix(r, :) / matrix(r, pivot)
       do i = 1, norow
          if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
       end do
       pivot = pivot + 1
    end do
    deallocate(trow)
  end subroutine to_rref
end module Rref


(in "wordlist"
  (while (char)
    (process @))


def get_next_character(f):
  # note: assumes valid utf-8
  c = f.read(1)
  while c:
    while True:
      try:
        yield c.decode('utf-8')
      except UnicodeDecodeError:
        # we've encountered a multibyte character
        # read another byte and try again
        c += f.read(1)
      else:
        # c was a valid char, and was yielded, continue
        c = f.read(1)
        break

# Usage:
with open("input.txt","rb") as f:
    for c in get_next_character(f):
        print(c)


f = FREEFILE
filename$ = "file.txt"

OPEN filename$ FOR BINARY AS #f
WHILE NOT EOF(f)
    char$ = STR$(LOF(f))
    GET #f, , char$
    PRINT char$;
WEND
CLOSE #f


#lang racket
; This file contains utf-8 charachters: λ, α, γ ...
(for ([c (in-port read-char (open-input-file "read-file.rkt"))])
  (display c))


/*REXX program  reads and displays  a file char by char, returning   'EOF'   when done. */
parse arg iFID .                                 /*iFID:     is the fileID to be read.  */
                                                 /* [↓]  show the file's contents.      */
if iFID\==''  then do j=1  until  x=='EOF'       /*J  count's the file's characters.    */
                   x=getchar(iFID);    y=        /*get a character  or  an 'EOF'.       */
                   if x>>' '   then y=x          /*display   X   if presentable.        */
                   say  right(j, 12)     'character,  (hex,char)'      c2x(x)      y
                   end   /*j*/                   /* [↑]  only display  X  if not low hex*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
getchar: procedure;  parse arg z;  if chars(z)==0  then return 'EOF';     return charin(z)


numerics E.
numerics Pi.
n sqrt.
n log10. "base 10 logarithm"
n ln. "natural logarithm"
n log: m. "arbitrary base logarithm"
n exp. "exponential"
n abs. "absolute value"
n floor.
n ceiling.
n raisedTo: anotherNumber


Float e.
Float pi.
aNumber sqrt.
aNumber log. "base 10 logarithm"
aNumber ln. "natural logarithm"
aNumber exp. "exponential"
aNumber abs. "absolute value"
aNumber floor.
aNumber ceiling.
aNumber raisedTo: anotherNumber


// e:
print(M_E);

// π:
print(M_PI);

// square root:
let five = sqrt(25);

// logarithm
// natural:
let one = log(M_E);
// base-2:
let six = log2(64);
// base-10
let three = log10(1000);

// exponential
let e_cubed = exp(3);

// absolute value
let ten = abs(-10);

// floor
let seven = floor(7.8);

// ceiling
let four = ceil(3.2);

// power
let eighty_one = pow(3, 4);


Math.e; (* e *)
Math.pi; (* pi *)
Math.sqrt x; (* square root *)
Math.ln x; (* natural logarithm--log base 10 also available (Math.log10) *)
Math.exp x; (* exponential *)
abs x; (* absolute value *)
floor x; (* floor *)
ceil x; (* ceiling *)
Math.pow (x, y); (* power *)
~ x; (* negation *)


scalar x=2
scalar y=3
di exp(1)
di _pi
di c(pi)
di sqrt(x)
di log(x)
di log10(x)
di exp(x)
di abs(x)
di floor(x)
di ceil(x)
di x^y


import Darwin

M_E // e
M_PI // pi
sqrt(x) // square root--cube root also available (cbrt)
log(x) // natural logarithm--log base 10 also available (log10)
exp(x) // exponential
abs(x) // absolute value
floor(x) // floor
ceil(x) // ceiling
pow(x,y) // power


(defn read-nth-line
  "Read line-number from the given text file. The first line has the number 1."
  [file line-number]
  (with-open [rdr (clojure.java.io/reader file)]
    (nth (line-seq rdr) (dec line-number))))


(defun read-nth-line (file n &aux (line-number 0))
  "Read the nth line from a text file. The first line has the number 1"
  (assert (> n 0) (n))
  (with-open-file (stream file)
    (loop for line = (read-line stream nil nil)
          if (and (null line) (< line-number n))
            do (error "file ~a is too short, just ~a, not ~a lines long"
                      file line-number n)
          do (incf line-number)
          if (and line (= line-number n))
            do (return line))))


void main() {
    import std.stdio, std.file, std.string;
    auto file_lines = readText("input.txt").splitLines();
    //file_lines becomes an array of strings, each line is one element
    writeln((file_lines.length > 6) ? file_lines[6] : "line not found");
}


#include once "matmult.bas"

sub rowswap( byval M as Matrix, i as uinteger, j as uinteger )
    dim as integer k
    for k = 0 to ubound(M.m, 2)
        swap M.m(j, k), M.m(i, k)
    next k
end sub

function rowech(byval M as Matrix) as Matrix
    dim as uinteger lead = 0, rowCount = 1+ubound(M.m, 1), colCount = 1+ubound(M.m, 2)
    dim as uinteger r, i, j
    dim as double K
    for r = 0 to rowCount-1
        if lead >= colCount then exit for
        i = r
        while M.m(i, lead) = 0
            i += 1
            if i = rowCount then
                i = r
                lead += 1
                if lead = colCount then exit for
            endif
        wend
        rowswap M, r, i
        K = M.m(r,lead)
        if K <> 0 then
            for j = 0 to colCount-1
                M.m(r,j) /= K
            next j
        endif
        for i = 0 to rowCount-1
            if i <> r then
                K = M.m(i, lead)
                for j = 0 to colCount-1
                    M.m(i,j) -= M.m(r,j) * K
                next j
            endif
        next i
        lead += 1
    next r
    return M
end function

dim as Matrix M = Matrix (3, 4)
dim as Matrix N

M.m(0,0) = 1 : M.m(0,1) = 2 : M.m(0,2) = -1 : M.M(0,3) = -4
M.m(1,0) = 2 : M.m(1,1) = 3 : M.m(1,2) = -1 : M.m(1,3) = -11
M.m(2,0) = -2: M.m(2,1) = 0 : M.m(2,2) = -3 : M.m(2,3) = 22

dim as integer i, j

N = rowech(M)
for i=0 to 2
    for j = 0 to 3
        print N.m(i, j),
    next j
    print
next i


fp = fopen("C:\Ring\ReadMe.txt","r")
r = fgetc(fp)
while isstring(r)
      r = fgetc(fp)
      see r
end
fclose(fp)


File.open('input.txt', 'r:utf-8') do |f|
  f.each_char{|c| p c}
end


open file.txt" for binary as #f
numChars = 1              ' specify number of characters to read
a$ = input$(#f,numChars)  ' read number of characters specified
b$ = input$(#f,1)         ' read one character
close #f


use std::{
    convert::TryFrom,
    fmt::{Debug, Display, Formatter},
    io::Read,
};

pub struct ReadUtf8<I: Iterator> {
    source: std::iter::Peekable<I>,
}

impl<R: Read> From<R> for ReadUtf8<std::io::Bytes<R>> {
    fn from(source: R) -> Self {
        ReadUtf8 {
            source: source.bytes().peekable(),
        }
    }
}

impl<I, E> Iterator for ReadUtf8<I>
where
    I: Iterator<Item = Result<u8, E>>,
{
    type Item = Result<char, Error<E>>;

    fn next(&mut self) -> Option<Self::Item> {
        self.source.next().map(|next| match next {
            Ok(lead) => self.complete_char(lead),
            Err(e) => Err(Error::SourceError(e)),
        })
    }
}

impl<I, E> ReadUtf8<I>
where
    I: Iterator<Item = Result<u8, E>>,
{
    fn continuation(&mut self) -> Result<u32, Error<E>> {
        if let Some(Ok(byte)) = self.source.peek() {
            let byte = *byte;

            return if byte & 0b1100_0000 == 0b1000_0000 {
                self.source.next();
                Ok((byte & 0b0011_1111) as u32)
            } else {
                Err(Error::InvalidByte(byte))
            };
        }

        match self.source.next() {
            None => Err(Error::InputTruncated),
            Some(Err(e)) => Err(Error::SourceError(e)),
            Some(Ok(_)) => unreachable!(),
        }
    }

    fn complete_char(&mut self, lead: u8) -> Result<char, Error<E>> {
        let a = lead as u32; // Let's name the bytes in the sequence

        let result = if a & 0b1000_0000 == 0 {
            Ok(a)
        } else if lead & 0b1110_0000 == 0b1100_0000 {
            let b = self.continuation()?;
            Ok((a & 0b0001_1111) << 6 | b)
        } else if a & 0b1111_0000 == 0b1110_0000 {
            let b = self.continuation()?;
            let c = self.continuation()?;
            Ok((a & 0b0000_1111) << 12 | b << 6 | c)
        } else if a & 0b1111_1000 == 0b1111_0000 {
            let b = self.continuation()?;
            let c = self.continuation()?;
            let d = self.continuation()?;
            Ok((a & 0b0000_0111) << 18 | b << 12 | c << 6 | d)
        } else {
            Err(Error::InvalidByte(lead))
        };

        Ok(char::try_from(result?).unwrap())
    }
}

#[derive(Debug, Clone)]
pub enum Error<E> {
    InvalidByte(u8),
    InputTruncated,
    SourceError(E),
}

impl<E: Display> Display for Error<E> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidByte(b) => write!(f, "invalid byte 0x{:x}", b),
            Self::InputTruncated => write!(f, "character truncated"),
            Self::SourceError(e) => e.fmt(f),
        }
    }
}

fn main() -> std::io::Result<()> {
    for (index, value) in ReadUtf8::from(std::fs::File::open("test.txt")?).enumerate() {
        match value {
            Ok(c) => print!("{}", c),

            Err(e) => {
                print!("\u{fffd}");
                eprintln!("offset {}: {}", index, e);
            }
        }
    }

    Ok(())
}


$ include "seed7_05.s7i";
  include "utf8.s7i";

const proc: main is func
  local
    var file: inFile is STD_NULL;
    var char: ch is ' ';
  begin
    OUT := STD_UTF8_OUT;
    inFile := openUtf8("readAFileCharacterByCharacterUtf8.in", "r");
    if inFile <> STD_NULL then
      while hasNext(inFile) do
        ch := getc(inFile);
        writeln("got character " <& ch <& " [U+" <& ord(ch) radix 16 <& "]");
      end while;
      close(inFile);
    end if;
  end func;


var file = File('input.txt')        # the input file contains: "aă€⼥"
var fh = file.open_r                # equivalent with: file.open('<:utf8')
fh.each_char { |char|
    printf("got character #{char} [U+%04x]\n", char.ord)
}


|utfStream|
utfStream := 'input' asFilename readStream asUTF8EncodedStream.
[utfStream atEnd] whileFalse:[
    Transcript showCR:'got char ',utfStream next.
].
utfStream close.


expr {exp(1)}       ;# e
expr {4 * atan(1)}  ;# pi -- also, simpler: expr acos(-1)
expr {sqrt($x)}     ;# square root
expr {log($x)}      ;# natural logarithm, also log10
expr {exp($x)}      ;# exponential
expr {abs($x)}      ;# absolute value
expr {floor($x)}    ;# floor
expr {ceil($x)}     ;# ceiling
expr {$x**$y}       ;# power, also pow($x,$y)


FUNCTION floor(x)
    IF x > 0 THEN
       LET floor = INT(x)
    ELSE
       IF x <> INT(x) THEN LET floor = INT(x) - 1 ELSE LET floor = INT(x)
    END IF
END FUNCTION

PRINT "e     = "; EXP(1)          ! e  NOT available
PRINT "PI    = "; PI

LET x = 12.345
LET y = 1.23

PRINT "sqrt  = "; SQR(x), x^0.5   ! square root- NB the unusual NAME
PRINT "ln    = "; LOG(x)          ! natural logarithm BASE e
PRINT "log2  = "; LOG2(x)         ! BASE 2 logarithm
PRINT "log10 = "; LOG10(x)        ! BASE 10 logarithm
PRINT "log   = "; LOG(x)/LOG(y)   ! arbitrary BASE logarithm
PRINT "exp   = "; EXP(x)          ! exponential
PRINT "abs   = "; ABS(-1)         ! ABSOLUTE value
PRINT "floor = "; floor(x)        ! floor easily implemented AS functions
PRINT "ceil  = "; CEIL(x)         ! ceiling
PRINT "power = "; x ^ y           ! power
END


program Read_a_specific_line_from_a_file;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function ReadLine(position: Cardinal; FileName: TFileName): string;
begin
  Result := '';

  if not FileExists(FileName) then
    raise Exception.Create('Error: File does not exist.');

  var F: TextFile;
  var line: string;
  AssignFile(F, FileName);
  Reset(F);
  for var _ := 1 to position do
  begin
    if Eof(F) then
    begin
      CloseFile(F);

      raise Exception.Create(Format('Error: The file "%s" is too short. Cannot read line %d',
        [FileName, position]));
    end;

    Readln(F, line);
  end;
  CloseFile(F);
  Result := line;
end;

begin
  Writeln(ReadLine(7, 'test'));
  Readln;
end.


defmodule LineReader do
  def get_line(filename, line) do
    File.stream!(filename)
    |> Stream.with_index
    |> Stream.filter(fn {_value, index} -> index == line-1 end)
    |> Enum.at(0)
    |> print_line
  end
  defp print_line({value, _line_number}), do: String.trim(value)
  defp print_line(_), do: {:error, "Invalid Line"}
end


package main

import "fmt"

type matrix [][]float64

func (m matrix) print() {
    for _, r := range m {
        fmt.Println(r)
    }
    fmt.Println("")
}

func main() {
    m := matrix{
        { 1, 2, -1,  -4},
        { 2, 3, -1, -11},
        {-2, 0, -3,  22},
    }
    m.print()
    rref(m)
    m.print()
}

func rref(m matrix) {
    lead := 0
    rowCount := len(m)
    columnCount := len(m[0])
    for r := 0; r < rowCount; r++ {
        if lead >= columnCount {
            return
        }
        i := r
        for m[i][lead] == 0 {
            i++
            if rowCount == i {
                i = r
                lead++
                if columnCount == lead {
                    return
                }
            }
        }
        m[i], m[r] = m[r], m[i]
        f := 1 / m[r][lead]
        for j, _ := range m[r] {
            m[r][j] *= f
        }
        for i = 0; i < rowCount; i++ {
            if i != r {
                f = m[i][lead]
                for j, e := range m[r] {
                    m[i][j] -= e * f
                }
            }
        }
        lead++
    }
}


import "io" for File

File.open("input.txt") { |file|
    var offset = 0
    var char = "" // stores each byte read till we have a complete UTF encoded character
    while(true) {
        var b = file.readBytes(1, offset)
        if (b == "") return // end of stream
        char = char + b
        if (char.codePoints[0] >= 0) {  // a UTF encoded character is complete
            System.write(char)          // print it
            char = ""                   // reset store
        }
        offset = offset + 1
    }
}


fcn readUTF8c(chr,s=""){ // transform UTF-8 character stream
   s+=chr;
   try{ s.len(8); return(s) }
   catch{ if(s.len()>6) throw(__exception) } // 6 bytes max for UTF-8
   return(Void.Again,s);  // call me again with s & another character
}


echo $(( exp(1) ))      # e
echo $(( acos(-1) ))    # PI
x=5
echo $(( sqrt(x) ))     # square root
echo $(( log(x) ))      # logarithm base e
echo $(( log2(x) ))     # logarithm base 2
echo $(( log10(x) ))    # logarithm base 10
echo $(( exp(x) ))      # exponential
x=-42
echo $(( abs(x) ))      # absolute value
x=-5.5
echo $(( floor(x) ))    # floor
echo $(( ceil(x) ))     # ceiling
x=10 y=3
echo $(( pow(x,y) ))    # power


-module( read_a_specific_line ).

-export( [from_file/2, task/0] ).

from_file( File, N ) -> line_nr( N, read_a_file_line_by_line:into_list(File) ).

task() ->
       Lines = read_a_file_line_by_line:into_list( "read_a_specific_line.erl" ),
       Line_7 = line_nr( 7, Lines ),
       Line_7.

line_nr( N, Lines ) ->
         try
         case lists:nth( N, Lines )
         of "\n" -> erlang:exit( empty_line )
         ; Line -> Line
         end

         catch
         _Type:Error0 ->
                Error = line_nr_error( Error0 ),
                io:fwrite( "Error: ~p~n", [Error] ),
                erlang:exit( Error )

         end.

line_nr_error( function_clause ) -> too_few_lines_in_file;
line_nr_error( Error ) -> Error.


open System
open System.IO

[<EntryPoint>]
let main args =
    let n = Int32.Parse(args.[1]) - 1
    use r = new StreamReader(args.[0])
    let lines = Seq.unfold (
                    fun (reader : StreamReader) ->
                    if (reader.EndOfStream) then None
                    else Some(reader.ReadLine(), reader)) r
    let line = Seq.nth n lines  // Seq.nth throws an ArgumentException,
                                // if not not enough lines available
    Console.WriteLine(line)
    0


enum Pivoting {
    NONE({ i, it -> 1 }),
    PARTIAL({ i, it -> - (it[i].abs()) }),
    SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });

    public final Closure comparer

    private Pivoting(Closure c) {
        comparer = c
    }
}

def isReducibleMatrix = { matrix ->
    def m = matrix.size()
    m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}

def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
    assert isReducibleMatrix(matrix)
    def m = matrix.size()
    def n = matrix[0].size()
    (0..<m).each { i ->
        matrix[i..<m].sort(pivoting.comparer.curry(i))
        matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
        ((0..<i) + ((i+1)..<m)).each { k ->
            (i..<n).reverse().each { j ->
                matrix[k][j] -= matrix[i][j]*matrix[k][i]
            }
        }
    }
    matrix
}


var e = 1.exp

System.print("e         = %(e)")
System.print("pi        = %(Num.pi)")
System.print("sqrt(2)   = %(2.sqrt)")
System.print("ln(3)     = %(3.log)")    // log base e
System.print("exp(2)    = %(2.exp)")
System.print("abs(-e)   = %((-e).abs)")
System.print("floor(e)  = %(e.floor)")
System.print("ceil(e)   = %(e.ceil)")
System.print("pow(e, 2) = %(e.pow(2))")


include c:\cxpl\codes;                          \intrinsic 'code' declarations

func real Power(X, Y);  \X raised to the Y power
real X, Y;
return Exp(Y*Ln(X));

real E, Pi;
[Format(4, 16);                                 \places shown before and after .
E:= Exp(1.0);
RlOut(0, E);  CrLf(0);
RlOut(0, Ln(E));  CrLf(0);
CrLf(0);
Pi:= ATan2(0.0, -1.0);                          \Pi is also a defined constant
RlOut(0, Pi);  CrLf(0);
RlOut(0, Cos(Pi));  CrLf(0);
CrLf(0);
RlOut(0, Sqrt(2.0));  CrLf(0);                  \Sqrt is a call to an intrinsic
RlOut(0, Log(100.0));  CrLf(0);
RlOut(0, Ln(Exp(123.456789)));  CrLf(0);
CrLf(0);
RlOut(0, abs(-1234.5));  CrLf(0);               \abs works for both reals & ints
CrLf(0);
RlOut(0, float(fix(1.999-0.5)));  CrLf(0);      \floor   rounds toward -infinity
RlOut(0, float(fix(1.001+0.5)));  CrLf(0);      \ceiling rounds toward +infinity
RlOut(0, Power(sqrt(2.0), 4.0));  CrLf(0);      \sqrt is an inline function and
]                                               \ can be used for both reals & ints


print "e     = ", euler
print "pi    = ", pi

x = 12.345
y = 1.23

print "sqrt  = ", sqrt(2)              // square root
print "ln    = ", log(euler)           // natural logarithm base e
print "log   = ", log(x, y)	       // arbitrary base y logarithm
print "exp   = ", exp(euler)           // exponential
print "abs   = ", abs(-1)              // absolute value
print "floor = ", floor(-euler)        // floor
print "ceil  = ", ceil(-euler)         // ceiling
print "power = ", x ^ y, "  ", x ** y  // power
end


const std = @import("std");

pub fn main() void {
    var x: f64 = -1.2345;
    std.debug.print("e = {d}\n", .{std.math.e});
    std.debug.print("pi = {d}\n", .{std.math.pi});
    std.debug.print("sqrt(4) = {d}\n", .{std.math.sqrt(4)});
    std.debug.print("ln(e) = {d}\n", .{std.math.ln(std.math.e)});
    std.debug.print("exp(x) = {d}\n", .{std.math.exp(x)});
    std.debug.print("abs(x) = {d}\n", .{std.math.absFloat(x)});
    std.debug.print("floor(x) = {d}\n", .{std.math.floor(x)});
    std.debug.print("ceil(x) = {d}\n", .{std.math.ceil(x)});
    std.debug.print("pow(f64, -x, x) = {d}\n", .{std.math.pow(f64, -x, x)});
}


(0.0).e        // Euler's number, a property of all floats
(0.0).e.pi     // pi, yep, all floats
(2.0).sqrt()   // square root
(2.0).log()    // natural (base e) logarithm
(2.0).log10()  // log base 10
(0.0).e.pow(x) // e^x
(-10.0).abs()  // absolute value, both floats and ints
x.pow(y)       // x raised to the y power
x.ceil()       // ceiling
x.floor()      // floor


USING: continuations fry io io.encodings.utf8 io.files kernel
math ;
IN: rosetta-code.nth-line

: nth-line ( path encoding n -- str/f )
    [ f ] 3dip '[
        [ _ [ drop readln [ return ] unless* ] times ]
        with-return
    ] with-file-reader ;

: nth-line-demo ( -- )
    "input.txt" utf8 7 nth-line [ "line not found" ] unless*
    print ;

MAIN: nth-line-demo


      MODULE SAMPLER    !To sample a record from a file.                SAM00100
       CONTAINS                                                         SAM00200
        CHARACTER*20 FUNCTION GETREC(N,F,IS)    !Returns a status.      SAM00300
Careful. Some compilers get confused over the function name's usage.    SAM00400
         INTEGER N              !The desired record number.             SAM00500
         INTEGER F              !Of this file.                          SAM00600
         CHARACTER*(*) IS       !Stashed here.                          SAM00700
         INTEGER I,L            !Assistants.                            SAM00800
          IS = ""               !Clear previous content, even if null...SAM00900
          IF (N.LE.0) THEN      !Start on errors.                       SAM01000
            WRITE (GETREC,1) "!No record",N     !Could never be found.  SAM01100
    1       FORMAT (A,1X,I0)                    !Message, number.       SAM01200
          ELSE IF (F.LE.0) THEN                 !Obviously wrong?       SAM01300
            WRITE (GETREC,1) "!No unit number",F!Positive is valid.     SAM01400
          ELSE IF (LEN(IS).LE.0) THEN           !Space awaits?          SAM01500
            WRITE (GETREC,1) "!String size",LEN(IS)     !Nope.          SAM01600
          ELSE                  !Otherwise, there is hope.              SAM01700
            REWIND (F)          !Clarify the file position.             SAM01800
            DO I = 1,N - 1      !Grind up to the desired record.        SAM01900
              READ (F,2,END=3)  !Ignoring any content.                  SAM02000
            END DO              !Are we there yet?                      SAM02100
            READ (F,2,END = 3) L,IS(1:MIN(L,LEN(IS)))    !At last.      SAM02200
    2       FORMAT (Q,A)        !Q = characters yet unread.             SAM02300
            IF (L.LT.LEN(IS)) IS(L + 1:) = ""   !Clear the tail.        SAM02400
            IF (L.GT.LEN(IS)) THEN              !Now for more silliness.SAM02500
              WRITE (GETREC,1) "+Length",L      !Too long to fit in IS. SAM02600
            ELSE IF (L.LE.0) THEN               !A zero-length record   SAM02700
              WRITE (GETREC,1) "+Null"          !Is not the same        SAM02800
            ELSE IF (IS.EQ."") THEN             !As a record            SAM02900
              WRITE (GETREC,1) "+Blank",L       !Containing spaces.     SAM03000
            ELSE                                !But otherwise,         SAM03100
              WRITE (GETREC,1) " Length",L      !Note the leading space.SAM03200
            END IF              !Righto, we've decided.                 SAM03300
          END IF                !And, no more options.                  SAM03400
          RETURN                !So, done.                              SAM03500
    3     WRITE (GETREC,1) "!End on read",I     !An alternative ending. SAM03600
        END FUNCTION GETREC     !That was interesting.                  SAM03700
      END MODULE SAMPLER        !Just a sample of possibility.          SAM03800
                                                                        SAM03900
      PROGRAM POKE                                                      POK00100
      USE SAMPLER                                                       POK00200
      INTEGER ENUFF     !Some sizes.                                    POK00300
      PARAMETER (ENUFF = 666)   !Sufficient?                            POK00400
      CHARACTER*(ENUFF) STUFF   !Lots of memory these days.             POK00500
      CHARACTER*20 RESULT                                               POK00600
      INTEGER MSG,F     !I/O unit numbers.                              POK00700
      MSG = 6           !Standard output.                               POK00800
      F = 10            !Chooose a unit number.                         POK00900
      WRITE (MSG,*) "      To select record 7 from a disc file."        POK01000
                                                                        POK01100
      WRITE (MSG,*) "As a FORMATTED file."                              POK01200
      OPEN (F,FILE="FileSlurpN.for",STATUS="OLD",ACTION="READ")         POK01300
      RESULT = GETREC(7,F,STUFF)                                        POK01400
      WRITE (MSG,1) "Result",RESULT                                     POK01500
      WRITE (MSG,1) "Record",STUFF                                      POK01600
    1 FORMAT (A,":",A)                                                  POK01700
                                                                        POK01800
      CLOSE (F)                                                         POK01900
      WRITE (MSG,*) "As a random-access unformatted file."              POK02000
      OPEN (F,FILE="FileSlurpN.for",STATUS="OLD",ACTION="READ",         POK02100
     1 ACCESS="DIRECT",FORM="UNFORMATTED",RECL=82)      !Not 80!        POK02200
      STUFF = "Cleared."                                                POK02300
      READ (F,REC = 7,ERR = 666) STUFF(1:80)                            POK02400
      WRITE (MSG,1) "Record",STUFF(1:80)                                POK02500
      STOP                                                              POK02600
  666 WRITE (MSG,*) "Can't get the record!"                             POK02700
      END       !That was easy.                                         POK02800


import Data.List (find)

rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
  where rows = length m
        cols = length $ head m

        f m _    []              = m
        f m lead (r : rs)
            | indices == Nothing = m
            | otherwise          = f m' (lead' + 1) rs
          where indices = find p l
                p (col, row) = m !! row !! col /= 0
                l = [(col, row) |
                    col <- [lead .. cols - 1],
                    row <- [r .. rows - 1]]

                Just (lead', i) = indices
                newRow = map (/ m !! i !! lead') $ m !! i

                m' = zipWith g [0..] $
                    replace r newRow $
                    replace i (m !! r) m
                g n row
                    | n == r    = row
                    | otherwise = zipWith h newRow row
                  where h = subtract . (* row !! lead')

replace :: Int -> a -> [a] -> [a]
{- Replaces the element at the given index. -}
replace n e l = a ++ e : b
  where (a, _ : b) = splitAt n l


procedure main(A)
    tM := [[  1,  2, -1, -4],
           [  2,  3, -1,-11],
           [ -2,  0, -3, 22]]
    showMat(rref(tM))
end

procedure rref(M)
    lead := 1
    rCount := *\M | stop("no Matrix?")
    cCount := *(M[1]) | 0
    every r := !rCount do {
        i := r
        while M[i,lead] = 0 do {
            if (i+:=1) > rCount then {
                i := r
                if cCount < (lead +:= 1) then stop("can't reduce")
                }
            }
        M[i] :=: M[r]
        if 0 ~= (m0 := M[r,lead]) then every !M[r] /:= real(m0)
        every r ~= (i := !rCount) do {
            every !(mr := copy(M[r])) *:= M[i,lead]
            every M[i,j := !cCount] -:= mr[j]
            }
        lead +:= 1
        }
    return M
end

procedure showMat(M)
    every r := !M do every writes(right(!r,5)||" " | "\n")
end


' FB 1.05.0 Win64

Open "input.txt" For Input As #1
Dim line_ As String
Dim count As Integer = 0
While Not Eof(1)
  Line Input #1, line_  '' read each line
  count += 1
  If count = 7 Then
    line_ = Trim(line_, Any !" \t")   '' remove any leading or trailing spaces or tabs
    If line_ = "" Then
      Print "The 7th line is empty"
    Else
      Print "The 7th line is : "; line_
    End If
    Exit While
  End If
Wend
If count < 7 Then
  Print "There are only"; count; " lines in the file"
End If
Close #1
Print
Print "Press any key to quit"
Sleep


nthLine[filename, lineNum] :=
{
   line = nth[lines[filenameToURL[filename]], lineNum-1]
   if line != undef
      return line
   else
   {
      println["The file $filename does not contain a line number $lineNum"]
      return undef
   }
}


window 1

long     i = 1
Str255   s, lineSeven
CFURLRef url

url = openpanel 1, @"Select text file"
if ( url )
  open "I", 2, url
  while ( not eof(2) )
    line input #2, s
    if ( i == 7 )
      lineSeven = s : break
    end if
    i++
  wend
  close 2

  if ( lineSeven[0] )
    print lineSeven
  else
    print "File did not contain seven lines, or line was empty."
  end if
end if

HandleEvents


NB.*pivot v Pivot at row, column
NB. form: (row,col) pivot M
pivot=: dyad define
  'r c'=. x
  col=. c{"1 y
  y - (col - r = i.#y) */ (r{y) % r{col
)

NB.*gauss_jordan v Gauss-Jordan elimination (full pivoting)
NB. y is: matrix
NB. x is: optional minimum tolerance, default 1e_15.
NB.   If a column below the current pivot has numbers of magnitude all
NB.   less then x, it is treated as all zeros.
gauss_jordan=: verb define
  1e_15 gauss_jordan y
:
  mtx=. y
  'r c'=. $mtx
  rows=. i.r
  i=. j=. 0
  max=. i.>./
  while. (i<r) *. j<c do.
    k=. max col=. | i}. j{"1 mtx
    if. 0 < x-k{col do.           NB. if all col < tol, set to 0:
      mtx=. 0 (<(i}.rows);j) } mtx
    else.                         NB. otherwise sort and pivot:
      if. k do.
        mtx=. (<i,i+k) C. mtx
      end.
      mtx=. (i,j) pivot mtx
      i=. >:i
    end.
    j=. >:j
  end.
  mtx
)