(defvar *csv* "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!")

(defun split-string (string delim-char)
  (let ((result '()))
    (do* ((start 0 (1+ end))
	  (end (position delim-char string)
	       (position delim-char string :start start)))
	 ((not end) (reverse (cons (subseq string start) result)))
      (push (subseq string start end) result))))

;;; HTML escape code modified from:
;;; http://www.gigamonkeys.com/book/practical-an-html-generation-library-the-interpreter.html

(defun escape-char (char)
  (case char
    (#\& "&")
    (#\< "<")
    (#\> ">")
    (t (format nil "&#~d;" (char-code char)))))

(defun escape (in)
  (let ((to-escape "<>&"))
    (flet ((needs-escape-p (char) (find char to-escape)))
      (with-output-to-string (out)
	(loop for start = 0 then (1+ pos)
	   for pos = (position-if #'needs-escape-p in :start start)
	   do (write-sequence in out :start start :end pos)
	   when pos do (write-sequence (escape-char (char in pos)) out)
	   while pos)))))

(defun html-row (values headerp)
  (let ((tag (if headerp "th" "td")))
    (with-output-to-string (out)
      (write-string "
" out)
      (dolist (val values)
	(format out "<~A>~A</~A>" tag (escape val) tag))
      (write-string "
" out))))

(defun csv->html (csv)
  (let* ((lines (split-string csv #\Newline))
	 (cols  (split-string (first lines) #\,))
	 (rows  (mapcar (lambda (row) (split-string row #\,)) (rest lines))))
    (with-output-to-string (html)
      (format html "
~C" #\Newline)
      (format html "~C~A~C" #\Tab (html-row cols t) #\Newline)
      (dolist (row rows)
	(format html "~C~A~C" #\Tab (html-row row nil) #\Newline))
      (write-string "
" html))))


void main() {
    import std.stdio;

    immutable input =
        "Character,Speech\n" ~
        "The multitude,The messiah! Show us the messiah!\n" ~
        "Brians mother,<angry>Now you listen here! He's not the messiah; " ~
            "he's a very naughty boy! Now go away!</angry>\n" ~
        "The multitude,Who are you?\n" ~
        "Brians mother,I'm his mother; that's who!\n" ~
        "The multitude,Behold his mother! Behold his mother!";

    "\n<meta charset=\"utf-8\">\n\n\n".write;
    "
\n
\n
".write;

    bool theadDone = false;

    foreach (immutable c; input) {
        switch(c) {
            case '\n':
                if (theadDone) {
                    "
\n
".write;
                } else {
                    "
\n
\n
\n
".write;
                    theadDone = true;
                }
                break;
            case ',':  "	".write; break;
            case '<':  "<".write;      break;
            case '>':  ">".write;      break;
            case '&':  "&".write;     break;
            default:   c.write;           break;
        }
    }

    "
\n
\n
\n\n".write;
}


program csv2html;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Classes;

const
  // Carriage Return/Line Feed
  CRLF    = #13#10;

  // The CSV data
  csvData =
  'Character,Speech'+CRLF+
  'The multitude,The messiah! Show us the messiah!'+CRLF+
  'Brians mother,<angry>Now you listen here! He''s not the messiah; he''s a very naughty boy! Now go away!</angry>'+CRLF+
  'The multitude,Who are you?'+CRLF+
  'Brians mother,I''m his mother; that''s who!'+CRLF+
  'The multitude,Behold his mother! Behold his mother!';

  // HTML header
  htmlHead =
  '<!DOCTYPE html'+CRLF+
  'PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'+CRLF+
  '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+CRLF+
  ''+CRLF+
  ''+CRLF+
  '<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />'+CRLF+
  '<title>CSV-to-HTML Conversion</title>'+CRLF+
  ''+CRLF+
  ''+CRLF+
  ''+CRLF;

  // HTML footer
  htmlFoot =
  ''+CRLF+
  '';

{ Function to split a string into a list using a given delimiter }
procedure SplitString(S, Delim: string; Rslt: TStrings);
var
  i: integer;
  fld: string;
begin
  fld := '';

  for i := Length(S) downto 1 do
    begin
      if S[i] = Delim then
        begin
          Rslt.Insert(0,fld);
          fld := '';
        end
        else
         fld := S[i]+fld;
    end;

  if (fld <> '') then
      Rslt.Insert(0,fld);
end;

{ Simple CSV parser with option to specify that the first row is a header row }
procedure ParseCSV(const csvIn: string; htmlOut: TStrings; FirstRowIsHeader: Boolean = True);
const
  rowstart      = '
';
  rowend        = '
';
  cellendstart  = '	';
  hcellendstart = '	';
  hrowstart     = '
';
  hrowend       = '
';
var
  tmp,pieces: TStrings;
  i: Integer;
begin
  // HTML header
  htmlOut.Text := htmlHead + CRLF + CRLF;

  // Start the HTML table
  htmlOut.Text := htmlOut.Text + '
'  + CRLF;

  // Create stringlist
  tmp := TStringList.Create;
  try
    // Assign CSV data to stringlist and fix occurences of '<' and '>'
    tmp.Text := StringReplace(csvIn,'<','<',[rfReplaceAll]);
    tmp.Text := StringReplace(tmp.Text,'>','>',[rfReplaceAll]);

    // Create stringlist to hold the parts of the split data
    pieces := TStringList.Create;
    try

      // Loop through the CSV rows
      for i := 0 to Pred(tmp.Count) do
        begin
          // Split the current row
          SplitString(tmp[i],',',pieces);

          // Check if first row and FirstRowIsHeader flag set
          if (i = 0) and FirstRowIsHeader then

            // Render HTML
            htmlOut.Text := htmlOut.Text + hrowstart + pieces[0] + hcellendstart + pieces[1] + hrowend + CRLF
            else
            htmlOut.Text := htmlOut.Text + rowstart + pieces[0] + cellendstart + pieces[1] + rowend + CRLF;

        end;

      // Finish the HTML table and end the HTML page
      htmlOut.Text := htmlOut.Text + '
' + CRLF + htmlFoot;

    finally
      pieces.Free;
    end;

  finally
    tmp.Free;
  end;
end;

var
  HTML: TStrings;

begin
  // Create stringlist to hold HTML output
  HTML := TStringList.Create;
  try
    Writeln('Basic:');
    Writeln('');

    // Load and parse the CSV data
    ParseCSV(csvData,HTML,False);

    // Output the HTML to the console
    Writeln(HTML.Text);

    // Save the HTML to a file (in application's folder)
    HTML.SaveToFile('csv2html_basic.html');

    Writeln('');
    Writeln('=====================================');
    Writeln('');

    HTML.Clear;

    Writeln('Extra Credit:');
    Writeln('');

    // Load and parse the CSV data
    ParseCSV(csvData,HTML,True);

    // Output the HTML to the console
    Writeln(HTML.Text);

    // Save the HTML to a file (in application's folder)
    HTML.SaveToFile('csv2html_extra.html');
    Writeln('');
    Writeln('=====================================');

  finally
    HTML.Free;
  end;

  // Keep console window open
  Readln;
end.


;; CSV -> LISTS
(define (csv->row line)  (string-split line ","))
(define (csv->table csv) (map  csv->row (string-split csv "\n")))

;; LISTS->HTML
(define html 'html)
(define  (emit-tag tag  html-proc content )
		 (if (style tag)
		 	(push html (format "<%s style='%a'>" tag (style tag)))
		 	(push html (format "<%s>" tag )))
		 (html-proc content)
		 (push html (format "</%s> " tag )))

;; html procs : 1 tag, 1 proc
(define (h-raw content)
		(push html (format "%s" content)))
(define (h-header headers)
		(for ((h headers)) (emit-tag 'th h-raw h)))
(define (h-row row)
		(for ((item row)) (emit-tag 'td h-raw item)))
(define (h-table table )
	(emit-tag 'tr h-header (first table))
	(for ((row (rest table))) (emit-tag 'tr h-row row)))

(define (html-dump) (string-join (stack->list html) " "))

;; STYLES
(style 'td "text-align:left")
(style 'table "border-spacing: 10px;border:28px ridge orange") ;; special biblical border
(style 'th "color:blue;")


-module( csv_to_html ).

-export( [table_translation/1, task/0] ).

table_translation( CSV ) ->
	[Headers | Contents] = [string:tokens(X, ",") || X <- string:tokens( CSV, "\n")],
	Table = create_html_table:html_table( [{border, "1"}, {cellpadding, "10"}], Headers, Contents ),
	create_html_table:external_format( Table ).

task() -> table_translation( csv() ).

csv() ->
"Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!".


constant input = "Character,Speech\n" &
    "The multitude,The messiah! Show us the messiah!\n" &
    "Brians mother,<angry>Now you listen here! He's not the messiah; " &
        "he's a very naughty boy! Now go away!</angry>\n" &
    "The multitude,Who are you?\n" &
    "Brians mother,I'm his mother; that's who!\n" &
    "The multitude,Behold his mother! Behold his mother!"

puts(1,"
\n
")
for i = 1 to length(input) do
    switch input[i] do
        case '\n' then puts(1,"
\n
")
        case ','  then puts(1,"	")
        case '<'  then puts(1,"<")
        case '>'  then puts(1,">")
        case '&'  then puts(1,"&")
        case else puts(1,input[i])
    end switch
end for
puts(1,"
\n
")


open System
open System.Text
open System.Xml

let data = """
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
"""

let csv =
    Array.map
        (fun (line : string) -> line.Split(','))
        (data.Trim().Split([|'\n';'\r'|],StringSplitOptions.RemoveEmptyEntries))

[<EntryPoint>]
let main argv =
    let style = argv.Length > 0 && argv.[0] = "-h"
    Console.OutputEncoding <- UTF8Encoding()
    let xs = XmlWriterSettings()
    xs.Indent <- true   // be friendly to humans
    use x = XmlWriter.Create(Console.Out, xs)
    x.WriteStartDocument()
    x.WriteDocType("HTML", null, null, null)    // HTML5
    x.WriteStartElement("html")
    x.WriteStartElement("head")
    x.WriteElementString("title", "Rosettacode - CSV to HTML translation")
    if style then
        x.WriteStartElement("style"); x.WriteAttributeString("type", "text/css")
        x.WriteString("""
            table { border-collapse: collapse; }
            td, th { border: 1px solid black; padding: .25em}
            th { background-color: #EEE; }
            tbody th { font-weight: normal; font-size: 85%; }
        """)
        x.WriteEndElement() // style
    x.WriteEndElement() // head
    x.WriteStartElement("body")
    x.WriteStartElement("table")
    x.WriteStartElement("thead"); x.WriteStartElement("tr")
    for part in csv.[0] do x.WriteElementString("th", part)
    x.WriteEndElement(); x.WriteEndElement() // tr thead
    x.WriteStartElement("tbody")
    for line in csv.[1..] do
        x.WriteStartElement("tr")
        x.WriteElementString("th", line.[0])
        x.WriteElementString("td", line.[1])
        x.WriteEndElement() // tr
    x.Close()
    0


USING: csv html.streams prettyprint xml.writer ;

"Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"

string>csv [ simple-table. ] with-html-writer pprint-xml


: BEGIN-COLUMN ." <td>" ;
: END-COLUMN   ." </td>" ;

: BEGIN-ROW ." <tr>" BEGIN-COLUMN ;
: END-ROW END-COLUMN ." </tr>" CR ;

: CSV2HTML
	." <table>" CR BEGIN-ROW
	BEGIN KEY DUP #EOF <> WHILE
		CASE
			      10 OF END-ROW BEGIN-ROW ENDOF
			[CHAR] , OF END-COLUMN BEGIN-COLUMN ENDOF
	                [CHAR] < OF ." <" ENDOF
			[CHAR] > OF ." >" ENDOF
			[CHAR] & OF ." &" ENDOF
			DUP EMIT
		ENDCASE
	REPEAT
	END-ROW ." </table>" CR
;

CSV2HTML BYE


SUBROUTINE CSVTEXT2HTML(FNAME,HEADED)	!Does not recognise quoted strings.
Converts without checking field counts, or noting special characters.
       CHARACTER*(*) FNAME	!Names the input file.
       LOGICAL HEADED		!Perhaps its first line is to be a heading.
       INTEGER MANY		!How long is a piece of string?
       PARAMETER (MANY=666)	!This should suffice.
       CHARACTER*(MANY) ALINE	!A scratchpad for the input.
       INTEGER MARK(0:MANY + 1)	!Fingers the commas on a line.
       INTEGER I,L,N		!Assistants.
       CHARACTER*2 WOT(2)	!I don't see why a "table datum" could not be for either.
       PARAMETER (WOT = (/"th","td"/))	!A table heding or a table datum
       INTEGER IT		!But, one must select appropriately.
       INTEGER KBD,MSG,IN		!A selection.
       COMMON /IOUNITS/ KBD,MSG,IN	!The caller thus avoids collisions.
        OPEN(IN,FILE=FNAME,STATUS="OLD",ACTION="READ",ERR=661)	!Go for the file.
        WRITE (MSG,1)			!Start the blather.
    1   FORMAT ("
")	!By stating that a table follows.
        MARK(0) = 0		!Syncopation for the comma fingers.
        N = 0			!No records read.

   10   READ (IN,11,END = 20) L,ALINE(1:MIN(L,MANY))	!Carefully acquire some text.
   11   FORMAT (Q,A)		!Q = number of characters yet to read, A = characters.
        N = N + 1		!So, a record has been read.
        IF (L.GT.MANY) THEN	!Perhaps it is rather long?
          WRITE (MSG,12) N,L,MANY	!Alas!
   12     FORMAT ("Line ",I0," has length ",I0,"! My limit is ",I0)	!Squawk/
          L = MANY			!The limit actually read.
        END IF			!So much for paranoia.
        IF (N.EQ.1 .AND. HEADED) THEN	!Is the first line to be treated specially?
          WRITE (MSG,*) "
"	!Yep. Nominate a heading.
          IT = 1			!And select "th" rather than "td".
         ELSE				!But mostly,
          IT = 2			!Just another row for the table.
        END IF			!So much for the first line.
        NCOLS = 0		!No commas have been seen.
        DO I = 1,L		!So scan the text for them.
          IF (ICHAR(ALINE(I:I)).EQ.ICHAR(",")) THEN	!Here?
            NCOLS = NCOLS + 1		!Yes!
            MARK(NCOLS) = I		!The texts are between commas.
          END IF			!So much for that character.
        END DO			!On to the next.
        NCOLS = NCOLS + 1	!This is why the + 1 for the size of MARK.
        MARK(NCOLS) = L + 1	!End-of-line is as if a comma was one further along.
        WRITE (MSG,13)		!Now roll all the texts.
     1   (WOT(IT),				!This starting a cell,
     2    ALINE(MARK(I - 1) + 1:MARK(I) - 1),	!This being the text between the commas,
     3    WOT(IT),				!And this ending each cell.
     4    I = 1,NCOLS),			!For this number of columns.
     5   "/tr"			!And this ends the row.
   13   FORMAT ("
",666("<",A,">",A,"</",A,">"))	!How long is a piece of string?
        IF (N.EQ.1 .AND. HEADED) WRITE (MSG,*) "
"	!Finish the possible header.
        GO TO 10		!And try for another record.

   20   CLOSE (IN)		!Finished with input.
        WRITE (MSG,21)		!And finished with output.
   21   FORMAT ("
")	!This writes starting at column one.
       RETURN			!Done!
Confusions.
  661   WRITE (MSG,*) "Can't open file ",FNAME	!Alas.
      END			!So much for the conversion.

      INTEGER KBD,MSG,IN
      COMMON /IOUNITS/ KBD,MSG,IN
      KBD = 5	!Standard input.
      MSG = 6	!Standard output.
      IN = 10	!Some unspecial number.

      CALL CSVTEXT2HTML("Text.csv",.FALSE.)	!The first line is not special.
      WRITE (MSG,*)
      CALL CSVTEXT2HTML("Text.csv",.TRUE.)	!The first line is a heading.
      END


Data "Character,Speech"
Data "The multitude,The messiah! Show us the messiah!"
Data "Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>"
Data "The multitude,Who are you?"
Data "Brian's mother,I'm his mother; that's who!"
Data "The multitude,Behold his mother! Behold his mother!"
Data "***"

Print "<!DOCTYPE html>" & Chr(10) & ""
Print ""
Print "" & Chr(10)
Print ""
Print "
CSV to html translation
"
Print: Print "
"

Dim As Boolean header = true
Dim As String cadenaCSV, txt
Do
    Read cadenaCSV
    If cadenaCSV = "***" then Exit Do

    If header then
        Print "
" & Chr(10) & "
";
    Else
        Print "
";
    End If
    For i As Integer = 1 To Len(cadenaCSV)
        txt = Mid(cadenaCSV, i, 1)
        Select Case txt
        Case ",": If header then Print "	"; Else Print "	";
        Case "<": Print "<";
        Case ">": Print ">";
        Case "&": Print "&";
        Case Else: Print txt;
        End Select
    Next i
    If header then
        Print "
" & Chr(10) & "
" & Chr(10) & "
"
    Else
        Print "
"
    End If

    header = false
Loop Until false

Print "
" & Chr(10) & "
"
Print Chr(10) & ""
Print ""
Sleep


package main

import (
    "bytes"
    "encoding/csv"
    "fmt"
    "html/template"
    "strings"
)

var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`

func main() {
    if h, err := csvToHtml(c); err != nil {
        fmt.Println(err)
    } else {
        fmt.Print(h)
    }
}

func csvToHtml(c string) (string, error) {
    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
    if err != nil {
        return "", err
    }
    var b strings.Builder
    err = template.Must(template.New("").Parse(`

{{range .}}
{{range .}}{{.}}	{{end}}

{{end}}

`)).Execute(&b, data)
    return b.String(), err
}


def formatCell = { cell ->
    "${cell.replaceAll('&','&').replaceAll('<','<')}	"
}

def formatRow = { row ->
    """
${row.split(',').collect { cell -> formatCell(cell) }.join('')}

"""
}

def formatTable = { csv, header=false ->
    def rows = csv.split('\n').collect { row -> formatRow(row) }
    header \
        ? """

${rows[0]}

${rows[1..-1].join('')}

""" \
        : """

${rows.join('')}

"""
}

def formatPage = { title, csv, header=false ->
"""

<title>${title}</title>

${formatTable(csv, header)}
"""
}


--import Data.List.Split (splitOn)    -- if the import is available
splitOn :: Char -> String -> [String] -- otherwise
splitOn delim = foldr (\x rest ->
                        if x == delim then "" : rest
                        else (x:head rest):tail rest) [""]

htmlEscape :: String -> String
htmlEscape =  concatMap escapeChar
              where escapeChar '<' = "<"
                    escapeChar '>' = ">"
                    escapeChar '&' = "&"
                    escapeChar '"' = """ --"
                    escapeChar c   = [c]

toHtmlRow :: [String] -> String
toHtmlRow []   = "

"
toHtmlRow cols = let htmlColumns = concatMap toHtmlCol cols
                  in "
\n" ++ htmlColumns  ++ "
"
               where toHtmlCol x = "  " ++ htmlEscape x ++ "	\n"

csvToTable :: String -> String
csvToTable csv = let rows = map (splitOn ',') $ lines csv
                     html = unlines $ map toHtmlRow rows
                  in "
\n" ++ html ++ "
"

main = interact csvToTable


procedure main(arglist)
    pchar := &letters ++ &digits ++ '!?;. '  # printable chars

    write("
")
    firstHead := (!arglist == "-heading")
    tHead := write
    while row := trim(read()) do {
       if \firstHead then write("
") else tHead("
")
       writes("
")
       while *row > 0 do
         row ?:= ( (=",",writes("	")) |
                         writes( tab(many(pchar)) |
                         ("&#" || ord(move(1))) ),   tab(0))
       write("
")
       if (\firstHead) := &null then write("
\n
")
       tHead := 1
       }
    write("
")
    write("
")
end


require 'strings tables/csv'
encodeHTML=: ('&';'&';'<';'<';'>';'>')&stringreplace

tag=: adverb define
  'starttag endtag'=.m
  (,&.>/)"1 (starttag , ,&endtag) L:0 y
)

markupCells=:    ('';'	') tag
markupHdrCells=: ('';'	') tag
markupRows=:     ('
';'
',LF) tag
markupTable=:    (('
',LF);'
') tag

makeHTMLtablefromCSV=: verb define
  0 makeHTMLtablefromCSV y             NB. default left arg is 0 (no header row)
:
  t=. fixcsv encodeHTML y
  if. x do. t=. ([email protected]{. , [email protected]}.) t
      else. t=. markupCells t
  end.
  ;markupTable markupRows t
)


String csv = "...";
// Use Collectors.joining(...) for streaming, otherwise StringJoiner
StringBuilder html = new StringBuilder("
\n");
Collector collector = Collectors.joining("	", "
", "
\n");
for (String row : csv.split("\n") ) {
    html.append(Arrays.stream(row.split(",")).collect(collector));
}
html.append("
\n");


var csv = "Character,Speech\n" +
	   "The multitude,The messiah! Show us the messiah!\n" +
	   "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" +
	   "The multitude,Who are you?\n" +
	   "Brians mother,I'm his mother; that's who!\n" +
	   "The multitude,Behold his mother! Behold his mother!";

var lines = csv.replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .split(/[\n\r]/)
    .map(function(line) { return line.split(',')})
    .map(function(row) {return '\t\t
' + row[0] + '	' + row[1] + '
';});

console.log('
\n\t
\n'      + lines[0] +
            '\n\t
\n\t
\n' + lines.slice(1).join('\n') +
            '\t
\n
');


jq -R . csv2html.csv | jq -r -s -f csv2html.jq


/* CSV to HTML, in Jsish */
var csv = "Character,Speech\n" +
           "The multitude,The messiah! Show us the messiah!\n" +
           "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" +
           "The multitude,Who are you?\n" +
           "Brians mother,I'm his mother; that's who!\n" +
           "The multitude,Behold his mother! Behold his mother!";

var lines = csv.replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .split('\n')
    .map(function(line) { return line.split(','); })
    .map(function(row) { return '\t\t
' + row[0] + '	' + row[1] + '
'; });

if (Interp.conf('unitTest')) {
    puts('
\n\t
\n' + lines[0] + '\n\t
\n\t
\n'
         + lines.slice(1).join('\n') + '\t
\n
');
}

/*
=!EXPECTSTART!=

Character	Speech

The multitude	The messiah! Show us the messiah!

Brians mother	<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>

The multitude	Who are you?

Brians mother	I'm his mother; that's who!

The multitude	Behold his mother! Behold his mother!

=!EXPECTEND!=
*/


using DataFrames, CSV

using CSV, DataFrames

function csv2html(fname; header::Bool=false)
    csv = CSV.read(fname)
    @assert(size(csv, 2) > 0)
    str = """

csv2html Example

"""
    tags = header ? ("", "	") : ("", "	")

    for i=1:size(csv, 2)
        str *= "            " * tags[1] * csv[1, i] * tags[2] * "\n"
    end

    str *= " "^8 * "
\n"

    for i=2:size(csv, 1)
        str *= "
\n"

        for j=1:size(csv, 2)
            str *= "            " * "" * csv[i, j] * "	\n"
        end

        str *= "
\n"
    end

    str * "
\n\n\n\n"
end

print(csv2html("input.csv", header=true))


// version 1.1.3

val csv =
    "Character,Speech\n" +
    "The multitude,The messiah! Show us the messiah!\n" +
    "Brians mother,<angry>Now you listen here! He's not the messiah; " +
    "he's a very naughty boy! Now go away!</angry>\n" +
    "The multitude,Who are you?\n" +
    "Brians mother,I'm his mother; that's who!\n" +
    "The multitude,Behold his mother! Behold his mother!"

fun main(args: Array<String>) {
    val i = "   "  // indent
    val sb = StringBuilder("
\n$i
\n$i$i")
    for (c in csv) {
        sb.append( when (c) {
            '\n' -> "	\n$i
\n$i
\n$i$i"
            ','  -> "	\n$i$i"
            '&'  -> "&"
            '\'' -> "'"
            '<'  -> "<"
            '>'  -> ">"
            else -> c.toString()
        })
    }
    sb.append("	\n$i
\n
")
    println(sb.toString())
    println()

    // now using first row as a table header
    sb.setLength(0)
    sb.append("
\n$i
\n$i$i
\n$i$i$i")
    val hLength = csv.indexOf('\n') + 1  // find length of first row including CR
    for (c in csv.take(hLength)) {
        sb.append( when (c) {
            '\n' -> "	\n$i$i
\n$i
\n$i
\n$i$i
\n$i$i$i"
            ','  -> "	\n$i$i$i"
            else -> c.toString()
        })
    }
    for (c in csv.drop(hLength)) {
        sb.append( when (c) {
            '\n' -> "	\n$i$i
\n$i$i
\n$i$i$i"
            ','  -> "	\n$i$i$i"
            '&'  -> "&"
            '\'' -> "'"
            '<'  -> "<"
            '>'  -> ">"
            else -> c.toString()
        })
    }
    sb.append("	\n$i$i
\n$i
\n
")
    println(sb.toString())
}


}:l:>     Start loop, enqueue Z (initially 0).
  }:o:    Treat the queue as a stack and
    <:8:= accumulate the octal digits
    /=>&~ of the current number.
  ^:o:

  <:0:-   Get a sentinel negative 1.
  &>@     Enqueue it between the digits and the current number.
  {       Dequeue the first octal digit.

  }:p:
    ~%={+ Rotate each octal digit into place and print it.
  ^:p:

  <:a:~$  Output a newline.
  <:1:x{+ Dequeue the current number and increment it.
^:l:


{def CSV
Character,Speech\n
The multitude,The messiah! Show us the messiah!\n
Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n
The multitude,Who are you\n
Brians mother,I'm his mother; that's who!\n
The multitude,Behold his mother! Behold his mother!\n
}
-> CSV

{def csv2html
 {lambda {:csv}
  {table {@ style="background:#eee;"}
   {S.replace ([^,]*),([^_]*)_
           by {tr {td {@ style="width:120px;"}{b €1}} {td {i €2}}}
           in {S.replace \\n by _ in :csv}}}}}
-> csv2html

{csv2html {CSV}} ->


*        Octal                     04/07/2016
OCTAL    CSECT
         USING  OCTAL,R13          base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    prolog
         ST     R13,4(R15)         "
         ST     R15,8(R13)         "
         LR     R13,R15            "
         LA     R6,0               i=0
LOOPI    LR     R2,R6              x=i
         LA     R9,10              j=10
         LA     R4,PG+23           @pg
LOOP     LR     R3,R2              save x
         SLL    R2,29              shift left  32-3
         SRL    R2,29              shift right 32-3
         CVD    R2,DW              convert octal(j) to pack decimal
         OI     DW+7,X'0F'         prepare unpack
         UNPK   0(1,R4),DW         packed decimal to zoned printable
         LR     R2,R3              restore x
         SRL    R2,3               shift right 3
         BCTR   R4,0               @[email protected]
         BCT    R9,LOOP            j=j-1
         CVD    R2,DW              binary to pack decimal
         OI     DW+7,X'0F'         prepare unpack
         UNPK   0(1,R4),DW         packed decimal to zoned printable
         CVD    R6,DW              convert i to pack decimal
         MVC    ZN12,EM12          load mask
         ED     ZN12,DW+2          packed decimal (PL6) to char (CL12)
         MVC    PG(12),ZN12        output i
         XPRNT  PG,80              print buffer
         C      R6,=F'2147483647'  if i>2**31-1 (integer max)
         BE     ELOOPI             then exit loop on i
         LA     R6,1(R6)           i=i+1
         B      LOOPI              loop on i
ELOOPI   L      R13,4(0,R13)       epilog
         LM     R14,R12,12(R13)    "
         XR     R15,R15            "
         BR     R14                exit
         LTORG
PG       DC     CL80' '            buffer
DW       DS     0D,PL8             15num
ZN12     DS     CL12
EM12     DC     X'40',9X'20',X'2120'  mask CL12 11num
         YREGS
         END    OCTAL


define SRC_LO  $00
define SRC_HI  $01

define DEST_LO $02
define DEST_HI $03

define temp $04		;temp storage used by foo

;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime.

SET_TABLE:
TXA
STA $1000,X
INX
BNE SET_TABLE
;stores the identity table at memory address $1000-$10FF

CLEAR_TABLE:
LDA #0
STA $1200,X
INX
BNE CLEAR_TABLE
;fills the range $1200-$12FF with zeroes.

LDA #$10
STA SRC_HI
LDA #$00
STA SRC_LO
;store memory address $1000 in zero page

LDA #$12
STA DEST_HI
LDA #$00
STA DEST_LO
;store memory address $1200 in zero page

loop:
LDA (SRC_LO),y  ;load accumulator from memory address $1000+y
JSR foo		;convert accumulator to octal
STA (DEST_LO),y ;store accumulator in memory address $1200+y

INY
CPY #$40
BCC loop
BRK

foo:
sta temp           ;store input temporarily
asl                ;bit shift, this places the top bit of the right nibble in the bottom of the left nibble.
pha                ;back this value up
    lda temp
    and #$07       ;take the original input and remove everything except the bottom 3 bits.
    sta temp       ;store it for later. What used to be stored here is no longer needed.
pla                ;get the pushed value back.
and #$F0           ;clear the bottom 4 bits.
ora temp           ;put the bottom 3 bits of the original input back.
and #$7F           ;clear bit 7.
rts


	;-------------------------------------------------------
	; useful equates
	;-------------------------------------------------------
bdos	equ	5	; CP/M BDOS entry
conout	equ	2	; BDOS console output function
cr	equ	13	; ASCII carriage return
lf	equ	10	; ASCII line feed
	;------------------------------------------------------
	; main code begins here
	;------------------------------------------------------
	org	100h	; start of tpa under CP/M
	lxi	h,0	; save CP/M's stack
	dad	sp
	shld	oldstk
	lxi	sp,stack ; set our own stack
	lxi	h,1	; start counting at 1
count:	call	putoct
	call	crlf
	inx	h
	mov	a,h	; check for overflow (hl = 0)
	ora	l
	jnz	count
	;
	; all finished. clean up and exit.
	;
	lhld	oldstk	; get CP/M's stack back
	sphl		; restore it
	ret		; back to the ccp w/o warm booting
	;------------------------------------------------------
	; Console output routine
	; print character in A register to console
	;------------------------------------------------------
putchr:	push	h
	push	d
	push	b
	mov	e,a	; character to E for CP/M
	mvi	c,2	; console output function
	call	bdos	; call on BDOS to perform
	pop	b
	pop	d
	pop	h
	ret
	;------------------------------------------------------
	; output CRLF to console
	;------------------------------------------------------
crlf:	mvi	a,cr
	call	putchr
	mvi	a,lf
	call	putchr
	ret
	;------------------------------------------------------
	; Octal output routine
	; entry:  hl = number to output on console in octal
	; this is a recursive routine and uses 6 bytes of stack
	; space for each digit
	;------------------------------------------------------
putoct: push	b
	push	d
	push	h
	mvi	b,3	; hl = hl >> 3
div2:	call	shlr
	dcr	b
	jnz	div2
	mov	a,l	; test if hl = 0
	ora	h
	cnz	putoct
	pop	h	; get unshifted hl back
	push	h
	mov	a,l	; get low byte
	ani	7	; a = a mod 8
	adi	'0'	; make printable
	call	putchr
	pop	h
	pop	d
	pop	b
	ret
	;-------------------------------------------------------
	; logical shift of 16-bit value in HL right by one bit
	;-------------------------------------------------------
shlr:	ora	a	; clear carry
	mov	a,h	; begin with most significant byte
	rar		; bit 0 goes into carry
	mov	h,a	; put shifted byte back
	mov	a,l	; get least significant byte
	rar		; bit 0 of MSB has shifted in
	mov	l,a
	ret
	;-------------------------------------------------------
	;  data area
	;-------------------------------------------------------
oldstk:	dw	1
stack	equ	$+128	; 64 level stack
	;
	end


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program countOctal64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .ascii "Count : "
sMessValeur:        .fill 11, 1, ' '            // size => 11
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                             // entry of program
    mov x20,0                                     // loop indice
1:                                                // begin loop
    mov x0,x20
    ldr x1,qAdrsMessValeur
    bl conversion8                                // call conversion octal
    ldr x0,qAdrsMessResult
    bl affichageMess                              // display message
    add x20,x20,1
    cmp x20,64
    ble 1b

100:                                              // standard end of the program
    mov x0,0                                      // return code
    mov x8,EXIT                                   // request to exit program
    svc 0                                         // perform the system call

qAdrsMessValeur:          .quad sMessValeur
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsMessResult:          .quad sMessResult

/******************************************************************/
/*     Converting a register to octal                             */
/******************************************************************/
/* x0 contains value and x1 address area   */
/* x0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion8:
    stp x1,lr,[sp,-16]!            // save  registers
    mov x3,x1
    mov x2,LGZONECAL

1:                                 // start loop
    mov x1,x0
    lsr x0,x0,3                    // / by 8
    lsl x4,x0,3
    sub x1,x1,x4                   // compute remainder x1 - (x0 * 8)
    add x1,x1,48                   // digit
    strb w1,[x3,x2]                // store digit on area
    cmp x0,0                       // stop if quotient = 0
    sub x4,x2,1
    csel x2,x4,x2,ne
    bne 1b                         // and loop
                                   // and move digit from left of area
    mov x4,0
2:
    ldrb w1,[x3,x2]
    strb w1,[x3,x4]
    add x2,x2,1
    add x4,x4,1
    cmp x2,LGZONECAL
    ble 2b
                                   // and move spaces in end on area
    mov x0,x4                      // result length
    mov x1,' '                     // space
3:
    strb w1,[x3,x4]                // store space in area
    add x4,x4,1                       // next position
    cmp x4,LGZONECAL
    ble 3b                         // loop if x4 <= area size

100:

    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC PrintOctal(CARD v)
  CHAR ARRAY a(6)
  BYTE i=[0]

  DO
    a(i)=(v&7)+'0
    i==+1
    v=v RSH 3
  UNTIL v=0
  OD

  DO
    i==-1
    Put(a(i))
  UNTIL i=0
  OD
RETURN

PROC Main()
  CARD i=[0]

  DO
    PrintF("decimal=%U octal=",i)
    PrintOctal(i) PutE()
    i==+1
  UNTIL i=0
  OD
RETURN


newline$ ="|"
    '   No escape behaviour, so can't refer to '/n'.
    '   Generally imported csv would have separator CR LF; easily converted first if needed

    csv$ ="Character,Speech"                                                                                +newline$+_
    "The multitude,The messiah! Show us the messiah!"                                                               +newline$+_
    "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" +newline$+_
    "The multitude,Who are you?"                                                                                +newline$+_
    "Brians mother,I'm his mother; that's who!"                                                                     +newline$+_
    "The multitude,Behold his mother! Behold his mother!"

    print ""
    print ""
    print ""
    print ""
    print "
CSV to HTML translation
"
    print "
"
    print "
"

    for i =1 to len( csv$)
        c$ =mid$( csv$, i, 1)
        select case c$
        case "|": print "
": print "
"
        case ",":  print "	";
        case "<":  print "&"+"lt;";
        case ">":  print "&"+"gt;";
        case "&":  print "&"+"amp;";
        case else:   print c$;
        end select
    next i

    print "
"
    print "
"
    print ""
    print ""
    end


with Ada.Text_IO;

procedure Octal is
   package IIO is new Ada.Text_IO.Integer_IO(Integer);
begin
   for I in 0 .. Integer'Last loop
      IIO.Put(I, Base => 8);
      Ada.Text_IO.New_Line;
   end loop;
end Octal;


integer o;

o = 0;
do {
    o_xinteger(8, o);
    o_byte('\n');
    o += 1;
} while (0 < o);


#!/usr/local/bin/a68g --script #

INT oct width = (bits width-1) OVER 3 + 1;
main:
(
  FOR i TO 17 # max int # DO
    printf(($"8r"8r n(oct width)dl$, BIN i))
  OD
)


begin
    string(12) r;
    string(8)  octDigits;
    integer    number;
    octDigits := "01234567";
    number    := -1;
    while number < MAXINTEGER do begin
        integer    v, cPos;
        number := number + 1;
        v      := number;
        % build a string of octal digits in r, representing number %
        % Algol W uses 32 bit integers, so r should be big enough  %
        % the most significant digit is on the right               %
        cPos   := 0;
        while begin
            r( cPos // 1 ) := octDigits( v rem 8 // 1 );
            v :=  v div 8;
            ( v > 0 )
        end do begin
            cPos := cPos + 1
        end while_v_gt_0;
        % show most significant digit on a newline %
        write( r( cPos // 1 ) );
        % continue the line with the remaining digits (if any) %
        for c := cPos - 1 step -1 until 0 do writeon( r( c // 1 ) )
    end while_r_lt_MAXINTEGER
end.


*        Duplicate a string
         MVC    A,=CL64'Hello'     a='Hello'
         MVC    B,A                b=a          memory copy
         MVC    A,=CL64'Goodbye'   a='Goodbye'
         XPRNT  A,L'A              print a
         XPRNT  B,L'B              print b
         ...
*        Make reference to a string a string
         MVC    A,=CL64'Hi!'       a='Hi!'
         LA     R1,A               [email protected]        set pointer
         ST     R1,REFA            [email protected]      store pointer
         XPRNT  A,L'A              print a
         XPRNT  0(R1),L'A          print %refa
         ...
A        DS     CL64               a
B        DS     CL64               b
REFA     DS     A                  @a


myString: DC.B "HELLO WORLD",0
EVEN

LEA myString,A3


.model small
.stack 1024

.data

myString byte "Hello World!",0    ; a null-terminated string

myStruct word 0

.code

mov ax,@data
mov ds,ax       ;load data segment into DS

mov bx,offset myString   ;get the pointer to myString

mov word ptr [ds:myStruct],bx

mov ax,4C00h
int 21h         ;quit program and return to DOS


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program copystr64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szString: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
.align 4
qPtString:    .skip 8
szString1:    .skip 80
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                    // entry of program

                         // display start string
    ldr x0,qAdrszString
    bl affichageMess
                         // copy pointer string
    ldr x0,qAdrszString
    ldr x1,qAdriPtString
    str x0,[x1]
                         // control
    ldr x1,qAdriPtString
    ldr x0,[x1]
    bl affichageMess
                         // copy string
    ldr x0,qAdrszString
    ldr x1,qAdrszString1
1:
    ldrb w2,[x0],1       // read one byte and increment pointer one byte
    strb w2,[x1],1       // store one byte and increment pointer one byte
    cmp x2,#0            // end of string ?
    bne 1b               // no -> loop
                         // control
    ldr x0,qAdrszString1
    bl affichageMess

100:                     // standard end of the program */
    mov x0,0             // return code
    mov x8,EXIT          // request to exit program
    svc 0                // perform the system call
qAdrszString:        .quad szString
qAdriPtString:       .quad qPtString
qAdrszString1:       .quad szString1
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


FS = ","            -- field separator

csv = [[
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
]]

csv = csv:gsub( "<", "<" )
csv = csv:gsub( ">", "&gr;" )

html = { "
" }
for line in string.gmatch( csv, "(.-\n)" ) do
    str = "
"
    for field in string.gmatch( line, "(.-)["..FS.."?\n?]" ) do
        str = str .. "" .. field .. "	"
    end
    str = str .. "
"
    html[#html+1] = str;
end
html[#html+1] = "
"

for _, line in pairs(html) do
    print(line)
end


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

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

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .ascii "Count : "
sMessValeur:        .fill 11, 1, ' '            @ size => 11
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                             @ entry of program
    mov r4,#0                                     @ loop indice
1:                                                @ begin loop
    mov r0,r4
    ldr r1,iAdrsMessValeur
    bl conversion8                                @ call conversion octal
    ldr r0,iAdrsMessResult
    bl affichageMess                              @ display message
    add r4,#1
    cmp r4,#64
    ble 1b

100:                                              @ standard end of the program
    mov r0, #0                                    @ return code
    mov r7, #EXIT                                 @ request to exit program
    svc #0                                        @ perform the system call

iAdrsMessValeur:          .int sMessValeur
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsMessResult:          .int sMessResult

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                          @ save  registres
    mov r2,#0                                      @ counter length
1:                                                 @ loop length calculation
    ldrb r1,[r0,r2]                                @ read octet start position + index
    cmp r1,#0                                      @ if 0 its over
    addne r2,r2,#1                                 @ else add 1 in the length
    bne 1b                                         @ and loop
                                                   @ so here r2 contains the length of the message
    mov r1,r0                                      @ address message in r1
    mov r0,#STDOUT                                 @ code to write to the standard output Linux
    mov r7, #WRITE                                 @ code call system "write"
    svc #0                                         @ call systeme
    pop {r0,r1,r2,r7,lr}                           @ restaur des  2 registres */
    bx lr                                          @ return
/******************************************************************/
/*     Converting a register to octal                             */
/******************************************************************/
/* r0 contains value and r1 address area   */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion8:
    push {r1-r4,lr}                                 @ save registers
    mov r3,r1
    mov r2,#LGZONECAL

1:                                                  @ start loop
    mov r1,r0
    lsr r0,#3                                       @ / by 8
    sub r1,r0,lsl #3                                @ compute remainder r1 - (r0 * 8)
    add r1,#48                                      @ digit
    strb r1,[r3,r2]                                 @ store digit on area
    cmp r0,#0                                       @ stop if quotient = 0
    subne r2,#1                                     @ else previous position
    bne 1b                                          @ and loop
                                                    @ and move digit from left of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]
    add r2,#1
    add r4,#1
    cmp r2,#LGZONECAL
    ble 2b
                                                      @ and move spaces in end on area
    mov r0,r4                                         @ result length
    mov r1,#' '                                       @ space
3:
    strb r1,[r3,r4]                                   @ store space in area
    add r4,#1                                         @ next position
    cmp r4,#LGZONECAL
    ble 3b                                            @ loop if r4 <= area size

100:
    pop {r1-r4,lr}                                    @ restaur registres
    bx lr                                             @return


data: lv_string1 type string value 'Test',
      lv_string2 type string.
lv_string2 = lv_string1.


PROC Main()
  CHAR ARRAY str1,str2,str3(10)

  str1="Atari"
  str2=str1
  SCopy(str3,str1)

  PrintF(" base=%S%E",str1)
  PrintF("alias=%S%E",str2)
  PrintF(" copy=%S%E",str3)
  PutE()

  SCopy(str1,"Action!")

  PrintF(" base=%S%E",str1)
  PrintF("alias=%S%E",str2)
  PrintF(" copy=%S%E",str3)
RETURN


#A translation of the C code posted
html_table := proc(str)
	local char;
     printf("
\n
");
     for char in str do
         if char = "\n" then
         	printf("
\n
")
         elif char = "," then
          printf("	")
         elif char = "<" then
          printf("<")
         elif char = ">" then
          printf(">")
         elif char = "&" then
         	printf("&")
         else
          printf(char)
         end if;
    end do;
    printf("
\n
");
end proc;

html_table("Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!");


a="Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah;he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother;that's who!
The multitude,Behold his mother! Behold his mother!";
(*Naive*)
StringJoin["
\n",Map[StringJoin["
",#,"
\n"]&,
StringSplit[StringReplace[a,{","->"	","<"->"<",">"->">"}],"\n"]]
,"
"]
(*Extra*)
StringJoin["
\n",StringJoin["
",#,"
\n"]&[
StringSplit[StringReplace[a,{","->"	","<"->"<",">"->">"}],"\n"]//First]
,Map[StringJoin["
",#,"
\n"]&,
StringSplit[StringReplace[a,{","->"	","<"->"<",">"->">"}],"\n"]//Rest]
,"
"]


loop 1..40 'i ->
	print ["number in base 10:" pad to :string i 2
		   "number in octal:" pad as.octal i 2]


DllCall("AllocConsole")
Octal(int){
	While int
		out := Mod(int, 8) . out, int := int//8
	return out
}
Loop
{
	FileAppend, % Octal(A_Index) "`n", CONOUT$
	Sleep 200
}


DIM n AS LONG
FOR n = 0 TO &h7FFFFFFF
    PRINT OCT$(n)
NEXT


var str1:String = "Hello";
var str2:String = str1;


Src : String := "Hello";
Dest : String := Src;


(
  STRING src:="Hello", dest;
  dest:=src
)


inputString = fileread(csvFileName);
   % using multiple regular expressions to clear up special chars
htmlFriendly = regexprep(regexprep(regexprep(regexprep(inputString,...
      '&','&'),...
      '"','"'),...
      '<','<'),...
      '>','>');
   % split string into cell array
tableValues = regexp(regexp(htmlFriendly,'(\r\n|\r|\n)','split')',',','split');
   %%% print in html format %%%
   % <Extra Credit> first line gets treated as header
fprintf(1,['
\n\t
'  sprintf('\n\t\t%s	',tableValues{1,:}{:})])
   % print remaining lines of csv as html table (rows 2:end in cell array of csv values)
cellfun(@(x)fprintf(1,['\n\t
'  sprintf('\n\t\t%s	',x{:}) '\n\t
']),tableValues(2:end))
fprintf(1,'\n
')


infile: "input.csv";
outfile: "table.html";
instream: openr(infile);
outstream: openw(outfile);

printf(outstream, "
~%");
nr: 0;
while (line: readline(instream))#false do (
  nr: nr + 1,
  line: ssubst("<", "<", line),
  line: ssubst(">", ">", line),
  value_list: map(lambda([f], strim(" ", f)), split(line, ",")),
  if nr=1 then printf(outstream, "
") else  printf(outstream, "
"),
  printf(outstream, "
"),
  for value in value_list do printf(outstream, "~a	", value),
  printf(outstream, "
"),
  if nr=1 then printf(outstream, "
~%") else  printf(outstream, "
~%"));
printf(outstream, "
~%");

close(instream);
close(outstream);


@echo off
:: {CTRL + C} to exit the batch file

:: Send incrementing decimal values to the :to_Oct function
set loop=0
:loop1
call:to_Oct %loop%
set /a loop+=1
goto loop1

:: Convert the decimal values parsed [%1] to octal and output them on a new line
:to_Oct
set todivide=%1
set "fulloct="

:loop2
set tomod=%todivide%
set /a appendmod=%tomod% %% 8
set fulloct=%appendmod%%fulloct%
if %todivide% lss 8 (
  echo %fulloct%
  exit /b
)
set /a todivide/=8
goto loop2


      N% = 0
      REPEAT
        PRINT FN_tobase(N%, 8, 0)
        N% += 1
      UNTIL FALSE
      END

      REM Convert N% to string in base B% with minimum M% digits:
      DEF FN_tobase(N%, B%, M%)
      LOCAL D%, A$
      REPEAT
        D% = N% MOD B%
        N% DIV= B%
        IF D%<0 D% += B% : N% -= 1
        A$ = CHR$(48 + D% - 7*(D%>9)) + A$
        M% -= 1
      UNTIL (N%=FALSE OR N%=TRUE) AND M%<=0
      =A$


obase = 8			/* Output base is octal. */
for (num = 0; 1; num++) num	/* Loop forever, printing counter. */


get "libhdr"

let start() be
$(  let x = 0
    $(  writeo(x)
        wrch('*N')
        x := x + 1
    $) repeatuntil x = 0
$)


begin
    % strings are (fixed length) values in algol W. Assignment makes a copy   %
    string(10) a, copyOfA;
    a := "some text";
    copyOfA := a;
    % assignment to a will not change copyOfA                                 %
    a := "new value";
    write( a, copyOfA )
end.


String original = 'Test';
String cloned = original;
//"original == cloned" is true

cloned += ' more';
//"original == cloned" is false


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

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/* Initialized data */
.data
szString: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"

/* UnInitialized data */
.bss
.align 4
iPtString:   .skip 4
szString1:    .skip 80

/*  code section */
.text
.global main
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */

    @ display start string
    ldr r0,iAdrszString
    bl affichageMess
    @ copy pointer string
    ldr r0,iAdrszString
    ldr r1,iAdriPtString
    str r0,[r1]
    @ control
    ldr r1,iAdriPtString
    ldr r0,[r1]
    bl affichageMess
    @ copy string
    ldr r0,iAdrszString
    ldr r1,iAdrszString1
1:
    ldrb r2,[r0],#1   @ read one byte and increment pointer one byte
    strb r2,[r1],#1   @ store one byte and increment pointer one byte
    cmp r2,#0          @ end of string ?
    bne 1b            @ no -> loop
    @ control
    ldr r0,iAdrszString1
    bl affichageMess

100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszString:		.int szString
iAdriPtString:		.int iPtString
iAdrszString1:		.int szString1

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */


MCSKIP "WITH" NL
"" CSV to HTML
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,[]
MCSKIP SL WITH ~
MCINS %.
"" C1=th before header output, td afterwards
MCCVAR 1,2
MCSET C1=[th]
"" HTML escapes
MCDEF < AS [[<]]
MCDEF > AS [[>]]
MCDEF & AS [[&]]
"" Main line processing
MCDEF SL N1 OPT , N1 OR NL ALL
AS [[   <tr>]
MCSET T2=1
%L1.MCGO L2 IF T2 GR T1
      [<]%C1.[>]%AT2.[</]%C1.[>]
MCSET T2=T2+1
MCGO L1
%L2.[   </tr>]
MCSET C1=[td]
]
[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>HTML converted from CSV</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css"><!--
th {
        font-weight:bold;
        text-align:left
}
table,td,th {
        border:1px solid;
        border-collapse:collapse
}
td,th {
        padding:10px
}
//-->
</style>
</head>

<body>
<table>]
MCSET S1=1
~MCSET S10=2
~MCSET S1=0
[</table>
</body>
</html>
]


// a method that converts a csv row into a html table row as a string
def toHtmlRow(record, tag)
	htmlrow = "\t
\n"

	// loop through the values in the current csv row
	for i in range(1, len(record))
		htmlrow = htmlrow + "\t\t<" + tag + ">" + (record ~ i) + "</" + tag + ">\n"
	end for

	return htmlrow + "\t
\n"
end def

// get the name of the csv file then open it
print "filename: "
input fname
open fname

// allocate a string to hold the table
htmltable = "
\n"

// add the column names to the table (#0 returns column names as a record object)
htmltable = (htmltable + toHtmlRow(#0, "th"))

// add all other rows to the table
for i in range(1, $dbsize)
	htmltable = (htmltable + toHtmlRow(#i, "td"))
end for

// close the html table
htmltable = htmltable+"
"

println htmltable


+[            Start with n=1 to kick off the loop
[>>++++++++<< Set up {n 0 8} for divmod magic
[->+>-        Then
[>+>>]>       do
[+[-<+>]>+>>] the
<<<<<<]       magic
>>>+          Increment n % 8 so that 0s don't break things
>]            Move into n / 8 and divmod that unless it's 0
-<            Set up sentinel ‑1 then move into the first octal digit
[++++++++ ++++++++ ++++++++ Add 47 to get it to ASCII
 ++++++++ ++++++++ +++++++. and print it
[<]<]         Get to a 0; the cell to the left is the next octal digit
>>[<+>-]      Tape is {0 n}; make it {n 0}
>[>+]         Get to the ‑1
<[[-]<]       Zero the tape for the next iteration
++++++++++.   Print a newline
[-]<+]        Zero it then increment n and go again


#include <stdio.h>

int main()
{
        unsigned int i = 0;
        do { printf("%o\n", i++); } while(i);
        return 0;
}


a: new "Hello"
b: a            ; reference the same string

; changing one string in-place
; will change both strings

'b ++ "World"
print b
print a

c: "Hello"
d: new c        ; make a copy of the older string

; changing one string in-place
; will change only the string in question

'd ++ "World"
print d
print c


string src, dst;
src = "Hello";
dst = src;
src = " world...";
write(dst, src);


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

parse arg inFileName .
if inFileName = '' | inFileName = '.' then inFileName = './data/Brian.csv'
csv = RREadFileLineByLine01.scanFile(inFileName)

header = htmlHeader()
pre    = htmlCsvText(csv, inFileName)
table  = htmlCsvTable(csv, inFileName)
footer = htmlFooter()

say header
say pre
say table
say footer

return

method htmlHeader() public static returns Rexx
  html = '<?xml version="1.0" encoding="UTF-8"?>\n' -
      || '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n' -
      || '\n' -
      || '\n' -
      || '<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>\n' -
      || '<title>RCsv2Html</title>\n' -
      || '\n' -
      || '\n' -
      || '\n' -
      || '
Rosetta Code – NetRexx Sample Output
\n' -
      || '
CSV to HTML translation
\n' -
      || ''

  return html

method htmlFooter() public static returns Rexx
  html = '\n' -
      || '\n' -
      || ''
  return html

method htmlCsvText(csv, fileName = '.') public static returns Rexx
  html = '
Contents of CSV 'fileName'
\n' -
      || '
\n' -
      || ''
  loop row = 1 to csv[0]
    html = html || csv[row]'\n'
    end row
  html = html -
      || '
\n' -
      || ''
  return html

method htmlCsvTable(csv, fileName = '.') public static returns Rexx
  html = '
\n' -
      || '
Translation of CSV 'fileName'
\n' -
      || '
\n' -
      || ''
  html = html -
      || htmlCsvTableRow(csv[1], 'th')'\n' -
      || '
\n' -
      || '
\n' -
      || ''
  loop r_ = 2 to csv[0]
    html = html -
        || htmlCsvTableRow(csv[r_])'\n' -
        || ''
    end r_
  html = html -
      || '
\n' -
      || '
\n' -
      || ''
  return html

method htmlCsvTableRow(row, tag = 'td') public static returns Rexx
  row = row.strip('t')
  row = row.changestr('&', '&') -- need to do this one first to avoid double translation
  row = row.changestr('"', '"')
  row = row.changestr("'", ''')
  row = row.changestr('<', '<')
  row = row.changestr('>', '>')
  elmts = ''
  elmts[0] = 0
  e_ = 0
  loop while row.length() > 0
    parse row elmt ',' row
    e_ = e_ + 1; elmts[0] = e_; elmts[e_] = elmt
    end
  html = '
\n' -
      || ''
  loop e_ = 1 to elmts[0]
    html = html -
        || '<'tag'>'elmts[e_]'</'tag'>\n' -
        || ''
    end e_
  html = html -
      || '
\n' -
      || ''
  return html


using System;

class Program
{
    static void Main()
    {
        var number = 0;
        do
        {
            Console.WriteLine(Convert.ToString(number, 8));
        } while (++number > 0);
    }
}


#include <iostream>

int main()
{
  unsigned i = 0;
  do
  {
    std::cout << std::oct << i << std::endl;
    ++i;
  } while(i != 0);
  return 0;
}


(doseq [i (range)] (println (format "%o" i)))


BEGIN {
  a = "a string"
  b = a
  sub(/a/, "X", a) # modify a
  print b  # b is a copy, not a reference to...
}


Lbl STRCPY
r₁→S
While {r₂}
 {r₂}→{r₁}
 r₁++
 r₂++
End
0→{r₁}
S
Return


babel> "Hello, world\n" dup cp dup 0 "Y" 0 1 move8
babel> << <<
Yello, world
Hello, world


import cgi, strutils

const csvtext = """Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"""

proc row2tr(row: string): string =
  result = "
"
  let cols = xmlEncode(row).split(",")
  for col in cols:
    result.add ""&col&"	"
  result.add "
"

proc csv2html(txt: string): string =
  result = "
\n"
  for row in txt.splitLines():
    result.add "
"&row2tr(row)&"
\n"
  result.add "
"

echo csv2html(csvtext)


MODULE CSV2HTML;
IMPORT
  Object,
  IO,
  IO:FileChannel,
  IO:TextRider,
  SB := ADT:StringBuffer,
  NPCT:Tools,
  NPCT:CGI:Utils,
  Ex := Exception,
  Out;
VAR
  fileChannel: FileChannel.Channel;
  rd: TextRider.Reader;
  line: ARRAY 1024 OF CHAR;
  table: SB.StringBuffer;
  parts: ARRAY 2 OF STRING;

  PROCEDURE DoTableHeader(sb: SB.StringBuffer;parts: ARRAY OF STRING);
  BEGIN
    sb.Append("
"+Utils.EscapeHTML(parts[0])+"	"+Utils.EscapeHTML(parts[1])+"
");
    sb.AppendLn
  END DoTableHeader;

  PROCEDURE DoTableRow(sb: SB.StringBuffer;parts: ARRAY OF STRING);
  BEGIN
    sb.Append("
"+Utils.EscapeHTML(parts[0])+"	"+Utils.EscapeHTML(parts[1])+"
");
    sb.AppendLn
  END DoTableRow;

  PROCEDURE DoTable(sb: SB.StringBuffer): STRING;
  VAR
    aux: SB.StringBuffer;
  BEGIN
     aux := SB.New("
");aux.AppendLn;
     RETURN aux.ToString() + sb.ToString() + "
";
  END DoTable;

BEGIN
  TRY
    fileChannel := FileChannel.OpenUnbuffered("script.csv",{FileChannel.read});
  CATCH Ex.Exception(ex):
    Out.Object(ex.GetMessage());Out.Ln;
    HALT(1)
  END;
  rd := TextRider.ConnectReader(fileChannel);
  (* Extract headers *)
  TRY
    rd.ReadLine(line);
    table := NEW(SB.StringBuffer,2048);
    Tools.Split(Object.NewLatin1(line),",",parts);
    DoTableHeader(table,parts);
  CATCH IO.Error(ex):
    Out.Object(ex.Name() + ": " + ex.GetMessage());Out.Ln;
    HALT(2)
  END;

  (* Extract data *)
  LOOP
    TRY
      rd.ReadLine(line);
      IF (line[0] # 0X)THEN (* skip empty lines *)
        Tools.Split(Object.NewLatin1(line),",",parts);
        DoTableRow(table,parts)
      END
    CATCH IO.Error(ex):
      EXIT
    END
  END;
  Out.Object(DoTable(table));Out.Ln;
  fileChannel.Close()
END CSV2HTML.


       >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. count-in-octal.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
    FUNCTION dec-to-oct
    .
DATA DIVISION.
WORKING-STORAGE SECTION.
01  i                                   PIC 9(18).

PROCEDURE DIVISION.
    PERFORM VARYING i FROM 1 BY 1 UNTIL i = 0
        DISPLAY FUNCTION dec-to-oct(i)
    END-PERFORM
    .
END PROGRAM count-in-octal.

IDENTIFICATION DIVISION.
FUNCTION-ID. dec-to-oct.

DATA DIVISION.
LOCAL-STORAGE SECTION.
01  rem                                 PIC 9.

01  dec                                 PIC 9(18).

LINKAGE SECTION.
01  dec-arg                             PIC 9(18).

01  oct                                 PIC 9(18).

PROCEDURE DIVISION USING dec-arg RETURNING oct.
    MOVE dec-arg TO dec *> Copy is made to avoid modifying reference arg.
    PERFORM WITH TEST AFTER UNTIL dec = 0
        MOVE FUNCTION REM(dec, 8) TO rem
        STRING rem, oct DELIMITED BY SPACES INTO oct
        DIVIDE 8 INTO dec
    END-PERFORM
    .
END FUNCTION dec-to-oct.


n = 0

while true
  console.log n.toString(8)
  n += 1


(loop for i from 0 do (format t "~o~%" i))


      source$ = "Hello, world!"

      REM Copy the contents of a string:
      copy$ = source$
      PRINT copy$

      REM Make an additional reference to a string:
      !^same$ = !^source$
      ?(^same$+4) = ?(^source$+4)
      ?(^same$+5) = ?(^source$+5)
      PRINT same$


a ← "Hello"
b ← a
•Show a‿b
a ↩ "hi"
•Show a‿b


abcdef:?a;
!a:?b;

c=abcdef;
!c:?d;

!a:!b { variables a and b are the same and probably referencing the same string }
!a:!d { variables a and d are also the same but not referencing the same string }


use System.IO.File;
use Data.CSV;

class CsvToHtml {
  function : Main(args : String[]) ~ Nil {
    if(args->Size() = 1) {
      table := CsvTable->New(FileReader->ReadFile(args[0]));
      if(table->IsParsed()) {
        buffer := "
";
        Header(table->GetHeaders(), buffer);
        for(i := 1; i
Size(); i += 1;) {
          Data(table->Get(i), buffer);
        };
        buffer += "
";
        buffer->PrintLine();
      };
    };
  }

  function : Header(row : CsvRow, buffer : String) ~ Nil {
    buffer += "
";
    each(i : row) {
      buffer += "";
      buffer += Encode(row->Get(i));
      buffer += "	";
    };
    buffer += "
";
  }

  function : Data(row : CsvRow, buffer : String) ~ Nil {
    buffer += "
";
    each(i : row) {
      buffer += "";
      buffer += Encode(row->Get(i));
      buffer += "	";
    };
    buffer += "
";
  }

  function : Encode(in : String) ~ String {
    out := "";

    each(i : in) {
      c := in->Get(i);
      select(c) {
        label '&': {
          out->Append("&");

        }

        label '\'': {
          out->Append("'");
        }

        label '<': {
          out->Append("<");
        }

        label '>': {
          out->Append(">");
        }

        other: {
          out->Append(c);
        }
      };
    };

    return out;
  }
}


MODULE CountOctal;
IMPORT StdLog,Strings;

PROCEDURE Do*;
VAR
	i: INTEGER;
	resp: ARRAY 32 OF CHAR;
BEGIN
	FOR i := 0 TO 1000 DO
		Strings.IntToStringForm(i,8,12,' ',TRUE,resp);
		StdLog.String(resp);StdLog.Ln
	END
END Do;
END CountOctal.


include "cowgol.coh";

typedef N is uint16;

sub print_octal(n: N) is
    var buf: uint8[12];
    var p := &buf[11];
    [p] := 0;
    loop
        p := @prev p;
        [p] := '0' + (n as uint8 & 7);
        n := n >> 3;
        if n == 0 then break; end if;
    end loop;
    print(p);
end sub;

var n: N := 0;
loop
    print_octal(n);
    print_nl();
    n := n + 1;
    if n == 0 then break; end if;
end loop;


# version 0.21.1
# using unsigned 8 bit integer, range 0 to 255

(0_u8..255_u8).each { |i| puts i.to_s(8) }


void main() {
    import std.stdio;

    ubyte i;
    do writefln("%o", i++);
    while(i);
}


#include <stdlib.h>	/* exit(), free() */
#include <stdio.h>	/* fputs(), perror(), printf() */
#include <string.h>

int
main()
{
	size_t len;
	char src[] = "Hello";
	char dst1[80], dst2[80];
	char *dst3, *ref;

	/*
	 * Option 1. Use strcpy() from <string.h>.
	 *
	 * DANGER! strcpy() can overflow the destination buffer.
	 * strcpy() is only safe if the source string is shorter than
	 * the destination buffer. We know that "Hello" (6 characters
	 * with the final '\0') easily fits in dst1 (80 characters).
	 */
	strcpy(dst1, src);

	/*
	 * Option 2. Use strlen() and memcpy() from <string.h>, to copy
	 * strlen(src) + 1 bytes including the final '\0'.
	 */
	len = strlen(src);
	if (len >= sizeof dst2) {
		fputs("The buffer is too small!\n", stderr);
		exit(1);
	}
	memcpy(dst2, src, len + 1);

	/*
	 * Option 3. Use strdup() from <string.h>, to allocate a copy.
	 */
	dst3 = strdup(src);
	if (dst3 == NULL) {
		/* Failed to allocate memory! */
		perror("strdup");
		exit(1);
	}

	/* Create another reference to the source string. */
	ref = src;

	/* Modify the source string, not its copies. */
	memset(src, '-', 5);

	printf(" src: %s\n", src);   /*  src: ----- */
	printf("dst1: %s\n", dst1);  /* dst1: Hello */
	printf("dst2: %s\n", dst2);  /* dst2: Hello */
	printf("dst3: %s\n", dst3);  /* dst3: Hello */
	printf(" ref: %s\n", ref);   /*  ref: ----- */

	/* Free memory from strdup(). */
	free(dst3);

	return 0;
}


open Printf

let csv_data = "\
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; \
              he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"

(* General HTML escape *)
let escape =
  let html_escapes = Str.regexp "\\([^A-Za-z0-9 ;!?'/]\\)" in
  let esc s = sprintf "&#%04d;" (Char.code s.[Str.group_beginning 1]) in
  Str.global_substitute html_escapes esc

let nl = Str.regexp "\n\r?"
let coma = Str.regexp ","

let list_of_csv csv =
  List.map (fun l -> Str.split coma l) (Str.split nl csv)

let print_html_table segments =
  printf "
\n";
  List.iter (fun line ->
    printf "
";
    List.iter (fun c -> printf "%s	" (escape c)) line;
    printf "
\n";
  ) segments;
  printf "
\n";
;;

let () =
  print_html_table (list_of_csv csv_data)


$ i = 0
$ loop:
$  write sys$output f$fao( "!OL", i )
$  i = i + 1
$  goto loop


program CountingInOctal;

{$APPTYPE CONSOLE}

uses SysUtils;

function DecToOct(aValue: Integer): string;
var
  lRemainder: Integer;
begin
  Result := '';
  repeat
    lRemainder := aValue mod 8;
    Result := IntToStr(lRemainder) + Result;
    aValue := aValue div 8;
  until aValue = 0;
end;

var
  i: Integer;
begin
  for i := 0 to 20 do
    WriteLn(DecToOct(i));
end.


[Count in octal, for Rosetta Code.
 EDSAC program, Initial Orders 2.]

[Subroutine to print 17-bit non-negative integer in octal,
   with suppression of leading zeros.
 Input: 0F = number (not preserved)
 Workspace: 0D, 4F, 5F]
            T64K GK  [load at location 64]
            A3F [email protected] [plant return link as usual]
            T4D      [clear whole of 4D including sandwich bit]
            A2F      [load 0...010 binary (permanently in 2F)]
            T4F      [(1) marker bit (2) flag to test for leading 0]
            AF       [load number]
            R2F      [shift 3 right]
            A4D      [add marker bit]
            TD       [store number and marker in 0D]
            [email protected]     [mask to isolate 3-bit octal digit]
[Loop to print digits]
     [10]   T5F      [clear acc]
            C1F      [top 5 bits of acc = octal digit]
            U5F      [to 5F for printing]
            S4F      [subtract flag to test for leading 0]
            [email protected]     [skip printing if so]
            O5F      [print digit]
            T5F      [clear acc]
            T4F      [flag = 0, so future 0's are not skipped]
     [18]   T5F      [clear acc]
            AD       [load number + marker bit, as shifted]
            L2F      [shift left 3 more]
            TD       [store back]
            AF       [has marker reached sign bit yet?]
            [email protected]     [loop back if not]
[Last digit separately, in case input = 0]
            T5F      [clear acc]
            C1F T5F O5F
     [28]   ZF       [(planted) jump back to caller]
     [29]   UF       [mask, 001110...0 binary]

[Main routine]
            T96K GK  [load at location 96]
[Constants]
      [0]   PD       [1]
      [1]   #F       [set figures mode]
      [2]   @F       [carriage return]
      [3]   &F       [line feed]
      [4]   K4096F   [null char]
[Variable]
      [5]   PF       [number to be printed]
[Enter with acc = 0]
      [6]   [email protected]      [set teleprinter to figures]
      [7]   [email protected]      [update number, initially 0]
            TF       [also to 0F for printing]
      [9]   [email protected] G64F [call print soubroutine]
            [email protected] [email protected]  [print CR, LF]
            [email protected] [email protected]   [load number, add 1]
            [email protected]      [loop until number overflows and becomes negative]
            [email protected]      [done; print null to flush teleprinter buffer]
            ZF       [halt the machine]
            E6Z      [define entry point]
            PF       [acc = 0 on entry]
[end]


#include <iostream>
#include <string>

int main( ) {
   std::string original ("This is the original");
   std::string my_copy = original;
   std::cout << "This is the copy: " << my_copy << std::endl;
   original = "Now we change the original! ";
   std::cout << "my_copy still is " << my_copy << std::endl;
}


(let [s "hello"
      s1 s]
  (println s s1))


<cfset stringOrig = "I am a string." />
<cfset stringCopy = stringOrig />


F get_prime_factors(=li)
   I li == 1
      R ‘1’
   E
      V res = ‘’
      V f = 2
      L
         I li % f == 0
            res ‘’= f
            li /= f
            I li == 1
               L.break
            res ‘’= ‘ x ’
         E
            f++
      R res

L(x) 1..17
   print(‘#4: #.’.format(x, get_prime_factors(x)))
print(‘2144: ’get_prime_factors(2144))


FUNCTION csvToHtml RETURNS CHARACTER (
   i_lhas_header  AS LOGICAL,
   i_cinput       AS CHARACTER
):

   DEFINE VARIABLE coutput AS CHARACTER   NO-UNDO.

   DEFINE VARIABLE irow    AS INTEGER     NO-UNDO.
   DEFINE VARIABLE icolumn AS INTEGER     NO-UNDO.
   DEFINE VARIABLE crow    AS CHARACTER   NO-UNDO.
   DEFINE VARIABLE ccell   AS CHARACTER   NO-UNDO.

   coutput = "~n~t
".

   DO irow = 1 TO NUM-ENTRIES( i_cinput, "~n":U ):

      coutput = coutput + "~n~t~t
".

      crow = ENTRY( irow, i_cinput, "~n":U ).

      DO icolumn = 1 TO NUM-ENTRIES( crow ):
         ccell = ENTRY( icolumn, crow ).

         coutput = coutput + "~n~t~t~t" + IF i_lhas_header AND irow = 1 THEN "" ELSE "".
         coutput = coutput + REPLACE( REPLACE( REPLACE( ccell, "&", "&" ), "<", "<" ), ">", ">" ).
         coutput = coutput + IF i_lhas_header AND irow = 1 THEN "	" ELSE "	".

      END.

      coutput = coutput + "~n~t~t
".

   END.

   coutput = coutput + "~n~t
~n".

   RETURN coutput.

END FUNCTION. /* csvToHtml */

MESSAGE
   csvToHtml(
      TRUE,
      "Character,Speech" + "~n" +
      "The multitude,The messiah! Show us the messiah!" + "~n" +
      "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" + "~n" +
      "The multitude,Who are you?" + "~n" +
      "Brians mother,I'm his mother; that's who!" + "~n" +
      "The multitude,Behold his mother! Behold his mother!"
   )
VIEW-AS ALERT-BOX.


Stream.iterate(0,&(&1+1)) |> Enum.each(&IO.puts Integer.to_string(&1,8))


(dotimes (i most-positive-fixnum) ;; starting from 0
  (message "%o" i))


F = fun(FF, I) -> io:fwrite("~.8B~n", [I]), FF(FF, I + 1) end.


integer i
i = 0
while 1 do
    printf(1,"%o\n",i)
    i += 1
end while


(let* ((s1     "Hello")        ; s1 is a variable containing a string
       (s1-ref s1)             ; another variable with the same value
       (s2     (copy-seq s1))) ; s2 has a distinct string object with the same contents
  (assert (eq s1 s1-ref))      ; same object
  (assert (not (eq s1 s2)))    ; different object
  (assert (equal s1 s2))       ; same contents

  (fill s2 #\!)                ; overwrite s2
  (princ s1)
  (princ s2))                  ; will print "Hello!!!!!"


VAR
	str1: ARRAY 128 OF CHAR;
	str2: ARRAY 32 OF CHAR;
	str3: ARRAY 25 OF CHAR;


ldsrc:  LDA  src
stdest: STA  dest
        BRZ  done  ; 0-terminated

        LDA  ldsrc
        ADD  one
        STA  ldsrc

        LDA  stdest
        ADD  one
        STA  stdest

        JMP  ldsrc

done:   STP

one:         1

src:         82    ; ASCII
             111
             115
             101
             116
             116
             97
             0

dest:


*        Count in factors          24/03/2017
COUNTFAC CSECT                     assist plig\COUNTFAC
         USING  COUNTFAC,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         L      R6,=F'1'           i=1
       DO WHILE=(C,R6,LE,=F'40')   do i=1 to 40
         LR     R7,R6                n=i
         MVI    F,X'01'              f=true
         MVC    PG,=CL80' '          clear buffer
         LA     R10,PG               pgi=0
         XDECO  R6,XDEC              edit i
         MVC    0(12,R10),XDEC       output i
         LA     R10,12(R10)          pgi=pgi+12
         MVC    0(1,R10),=C'='       output '='
         LA     R10,1(R10)           pgi=pgi+1
       IF C,R7,EQ,=F'1' THEN         if n=1 then
         MVI    0(R10),C'1'            output n
       ELSE     ,                    else
         LA     R8,2                   p=2
       DO WHILE=(CR,R8,LE,R7)          do while p<=n
         LR     R4,R7                    n
         SRDA   R4,32                    ~
         DR     R4,R8                    /p
       IF LTR,R4,Z,R4 THEN               if n//p=0 then
       IF CLI,F,EQ,X'00' THEN              if not f then
         MVC    0(1,R10),=C'*'               output '*'
         LA     R10,1(R10)                   pgi=pgi+1
       ELSE     ,                          else
         MVI    F,X'00'                      f=false
       ENDIF    ,                          endif
         CVD    R8,PP                      convert bin p to packed pp
         MVC    WORK12,MASX12              in fact L13
         EDMK   WORK12,PP+2                edit and mark
         LA     R9,WORK12+12               end of string(p)
         SR     R9,R1                      li=lengh(p)  {r1 from edmk}
         MVC    EDIT12,WORK12              L12<-L13
         LA     R4,EDIT12+12               source+12
         SR     R4,R9                      -lengh(p)
         LR     R5,R9                      lengh(p)
         LR     R2,R10                     target ix
         LR     R3,R9                      lengh(p)
         MVCL   R2,R4                      f=f||p
         AR     R10,R9                     ix=ix+lengh(p)
         LR     R4,R7                      n
         SRDA   R4,32                      ~
         DR     R4,R8                      /p
         LR     R7,R5                      n=n/p
       ELSE     ,                        else
         LA     R8,1(R8)                   p=p+1
       ENDIF    ,                        endif
       ENDDO    ,                      enddo while
       ENDIF    ,                    endif
         XPRNT  PG,L'PG              print buffer
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         L      R13,4(0,R13)       restore previous savearea pointer
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
F        DS     X                  flag first factor
         DS     0D                 alignment for cvd
PP       DS     PL8                packed  CL8
EDIT12   DS     CL12               target  CL12
WORK12   DS     CL13               char    CL13
MASX12   DC     X'40',9X'20',X'212060'     CL13
XDEC     DS     CL12               temp
PG       DS     CL80               buffer
         YREGS
         END    COUNTFAC


PROC PrintFactors(CARD a)
  BYTE notFirst
  CARD p

  IF a=1 THEN
    PrintC(a) RETURN
  FI

  p=2 notFirst=0
  WHILE p<=a
  DO
    IF a MOD p=0 THEN
      IF notFirst THEN
        Put('x)
      FI
      notFirst=1
      PrintC(p)
      a==/p
    ELSE
      p==+1
    FI
  OD
RETURN

PROC Main()
  CARD i

  FOR i=1 TO 1000
  DO
    PrintC(i) Put('=)
    PrintFactors(i)
    PutE()
  OD
RETURN


use HTML::Entities;

sub row {
    my $elem = shift;
    my @cells = map {"<$elem>$_</$elem>"} split ',', shift;
    print '
', @cells, "
\n";
}

my ($first, @rest) = map
    {my $x = $_; chomp $x; encode_entities $x}
    <STDIN>;
print "
\n";
row @ARGV ? 'th' : 'td', $first;
row 'td', $_ foreach @rest;
print "
\n";


let rec countInOctal num : unit =
  printfn "%o" num
  countInOctal (num + 1)

countInOctal 1


USING: kernel math prettyprint ;
0 [ dup .o 1 + t ] loop


: octal ( -- )  8 base ! ;  \ where unavailable

octal ints


program Octal
  implicit none

  integer, parameter :: i64 = selected_int_kind(18)
  integer(i64) :: n = 0

! Will stop when n overflows from
! 9223372036854775807 to -92233720368547758078 (1000000000000000000000 octal)
  do while(n >= 0)
    write(*, "(o0)") n
    n = n + 1
  end do
end program


void main() {
    string src = "This is a string";

    // copy contents:
    auto dest1 = src.idup;

    // copy contents to mutable char array
    auto dest2 = src.dup;

    // copy just the fat reference of the string
    auto dest3 = src;
}


[a string]   # push "a string" on the main stack
d            # duplicate the top value
f            # show the current contents of the main stack


program CopyString;

{$APPTYPE CONSOLE}

var
  s1: string;
  s2: string;
begin
  s1 := 'Goodbye';
  s2 := s1; // S2 points at the same string as S1
  s2 := s2 + ', World!'; // A new string is created for S2

  Writeln(s1);
  Writeln(s2);
end.


with Ada.Command_Line, Ada.Text_IO, Prime_Numbers;

procedure Count is
   package Prime_Nums is new Prime_Numbers
     (Number => Natural, Zero => 0, One => 1, Two => 2); use Prime_Nums;

   procedure Put (List : Number_List) is
   begin
      for Index in List'Range loop
         Ada.Text_IO.Put (Integer'Image (List (Index)));
         if Index /= List'Last then
            Ada.Text_IO.Put (" x");
         end if;
      end loop;
   end Put;

   N     : Natural := 1;
   Max_N : Natural := 15; -- the default for Max_N
begin
   if Ada.Command_Line.Argument_Count = 1 then -- read Max_N from command line
      Max_N := Integer'Value (Ada.Command_Line.Argument (1));
   end if; -- else use the default
   loop
      Ada.Text_IO.Put (Integer'Image (N) & ": ");
      Put (Decompose (N));
      Ada.Text_IO.New_Line;
      N := N + 1;
      exit when N > Max_N;
   end loop;
end Count;


OP +:= = (REF FLEX []INT a, INT b) VOID:
   BEGIN
      [⌈a + 1] INT c;
      c[:⌈a] := a;
      c[⌈a+1:] := b;
      a := c
   END;

PROC factorize = (INT nn) []INT:
   BEGIN
      IF nn = 1 THEN (1)
      ELSE
	  INT k := 2, n := nn;
	  FLEX[0]INT result;
	  WHILE n > 1 DO
	      WHILE n MOD k = 0 DO
		  result +:= k;
		  n := n % k
	      OD;
	      k +:= 1
	  OD;
	  result
      FI
   END;

FLEX[0]INT factors;
FOR i TO 22 DO
    factors := factorize (i);
    print ((whole (i, 0), " = "));
    FOR j TO UPB factors DO
       (j /= 1 | print (" × "));
	print ((whole (factors[j], 0)))
    OD;
    print ((new line))
OD


with javascript_semantics
constant input = """
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"""

puts(1,"
\n
")
for i = 1 to length(input) do
    switch input[i] do
        case '\n' then puts(1,"
\n
")
        case ','  then puts(1,"	")
        case '<'  then puts(1,"<")
        case '>'  then puts(1,">")
        case '&'  then puts(1,"&")
        case else puts(1,input[i])
    end switch
end for
puts(1,"
\n
")


' FB 1.05.0 Win64

Dim ub As UByte = 0 ' only has a range of 0 to 255
Do
   Print Oct(ub, 3)
   ub += 1
Loop Until ub = 0 ' wraps around to 0 when reaches 256
Print
Print "Press any key to quit"
Sleep


i = 0
while true
{
    println[i -> octal]
    i = i + 1
}


fun octal(x: int): int =
  loop ((out,mult,x) = (0,1,x)) = while x > 0 do
    let digit = x % 8
    let out = out + digit * mult
    in (out, mult * 10, x / 8)
  in out

fun main(n: int): [n]int =
  map octal (iota n)


window 1, @"Count in Octal"

defstr word
dim as short i
text ,,,,, 50

print @"dec",@"oct"
for i = 0 to 25
  print i,oct(i)
next

HandleEvents


package main

import (
    "fmt"
    "math"
)

func main() {
    for i := int8(0); ; i++ {
        fmt.Printf("%o\n", i)
        if i == math.MaxInt8 {
            break
        }
    }
}


local :orgininal "this is the original"
local :scopy concat( original "" )
!. scopy


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

 /* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes                       */
/************************************/
.include "../constantes.inc"
.equ NBFACT,    33
.equ MAXI,      1<<31

//.equ NOMBRE, 65537
//.equ NOMBRE, 99999999
.equ NOMBRE, 2144
//.equ NOMBRE, 529
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessNumber:       .asciz "Number @ : "
szMessResultFact:   .asciz "@ "
szCarriageReturn:   .asciz "\n"
szErrorGen:         .asciz "Program error !!!\n"
szMessPrime:        .asciz "This number is prime.\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:           .skip 24
tbZoneDecom:         .skip 8 * NBFACT          // factor 4 bytes, number of each factor 4 bytes
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                             @ entry of program
    ldr r7,iNombre                @ number
    mov r0,r7
    ldr r1,iAdrsZoneConv
    bl conversion10               @ call décimal conversion
    ldr r0,iAdrszMessNumber
    ldr r1,iAdrsZoneConv          @ insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess              @ display message
    mov r0,r7
    ldr r1,iAdrtbZoneDecom
    bl decompFact
    cmp r0,#-1
    beq 98f                       @ error ?
    mov r1,r0
    ldr r0,iAdrtbZoneDecom
    bl displayDivisors

    b 100f
98:
    ldr r0,iAdrszErrorGen
    bl affichageMess
100:                              @ standard end of the program
    mov r0, #0                    @ return code
    mov r7, #EXIT                 @ request to exit program
    svc #0                        @ perform the system call
iAdrszCarriageReturn:    .int szCarriageReturn
iAdrszMessResultFact:    .int szMessResultFact
iAdrszErrorGen:          .int szErrorGen
iAdrsZoneConv:           .int sZoneConv
iAdrtbZoneDecom:         .int tbZoneDecom
iAdrszMessNumber:        .int szMessNumber
iNombre:                 .int NOMBRE
/******************************************************************/
/*     display divisors function                         */
/******************************************************************/
/* r0 contains address of divisors area */
/* r1 contains the number of area items  */
displayDivisors:
    push {r2-r8,lr}            @ save  registers
    cmp r1,#0
    beq 100f
    mov r2,r1
    mov r3,#0                   @ indice
    mov r4,r0
1:
    add r5,r4,r3,lsl #3
    ldr r7,[r5]                 @ load factor
    ldr r6,[r5,#4]              @ load number of factor
    mov r8,#0                   @ display factor counter
2:
    mov r0,r7
    ldr r1,iAdrsZoneConv
    bl conversion10             @ call décimal conversion
    ldr r0,iAdrszMessResultFact
    ldr r1,iAdrsZoneConv        @ insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess            @ display message
    add r8,#1                   @ increment counter
    cmp r8,r6                   @ same factors number ?
    blt 2b
    add r3,#1                   @ other ithem
    cmp r3,r2                   @ items maxi ?
    blt 1b
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
    b 100f

100:
    pop {r2-r8,lr}             @ restaur registers
    bx lr                       @ return
/******************************************************************/
/*     factor decomposition                                               */
/******************************************************************/
/* r0 contains number */
/* r1 contains address of divisors area */
/* r0 return divisors items in table */
decompFact:
    push {r1-r8,lr}            @ save  registers
    mov r5,r1
    mov r8,r0                  @ save number
    bl isPrime                 @ prime ?
    cmp r0,#1
    beq 98f                    @ yes is prime
    mov r4,#0                  @ raz indice
    mov r1,#2                  @ first divisor
    mov r6,#0                  @ previous divisor
    mov r7,#0                  @ number of same divisors
2:
    mov r0,r8                  @ dividende
    bl division                @  r1 divisor r2 quotient r3 remainder
    cmp r3,#0
    bne 5f                     @ if remainder <> zero  -> no divisor
    mov r8,r2                  @ else quotient -> new dividende
    cmp r1,r6                  @ same divisor ?
    beq 4f                     @ yes
    cmp r6,#0                  @ no but is the first divisor ?
    beq 3f                     @ yes
    str r6,[r5,r4,lsl #2]      @ else store in the table
    add r4,r4,#1               @ and increment counter
    str r7,[r5,r4,lsl #2]      @ store counter
    add r4,r4,#1               @ next item
    mov r7,#0                  @ and raz counter
3:
    mov r6,r1                  @ new divisor
4:
    add r7,r7,#1               @ increment counter
    b 7f                       @ and loop

    /* not divisor -> increment next divisor */
5:
    cmp r1,#2                  @ if divisor = 2 -> add 1
    addeq r1,#1
    addne r1,#2                @ else add 2
    b 2b

    /* divisor -> test if new dividende is prime */
7:
    mov r3,r1                  @ save divisor
    cmp r8,#1                  @ dividende = 1 ? -> end
    beq 10f
    mov r0,r8                  @ new dividende is prime ?
    mov r1,#0
    bl isPrime                 @ the new dividende is prime ?
    cmp r0,#1
    bne 10f                    @ the new dividende is not prime

    cmp r8,r6                  @ else dividende is same divisor ?
    beq 9f                     @ yes
    cmp r6,#0                  @ no but is the first divisor ?
    beq 8f                     @ yes it is a first
    str r6,[r5,r4,lsl #2]      @ else store in table
    add r4,r4,#1               @ and increment counter
    str r7,[r5,r4,lsl #2]      @ and store counter
    add r4,r4,#1               @ next item
8:
    mov r6,r8                  @ new dividende -> divisor prec
    mov r7,#0                  @ and raz counter
9:
    add r7,r7,#1               @ increment counter
    b 11f

10:
    mov r1,r3                  @ current divisor = new divisor
    cmp r1,r8                  @ current divisor  > new dividende ?
    ble 2b                     @ no -> loop

    /* end decomposition */
11:
    str r6,[r5,r4,lsl #2]      @ store last divisor
    add r4,r4,#1
    str r7,[r5,r4,lsl #2]      @ and store last number of same divisors
    add r4,r4,#1
    lsr r0,r4,#1               @ return number of table items
    mov r3,#0
    str r3,[r5,r4,lsl #2]      @ store zéro in last table item
    add r4,r4,#1
    str r3,[r5,r4,lsl #2]      @ and zero in counter same divisor
    b 100f

98:
    ldr r0,iAdrszMessPrime
    bl   affichageMess
    mov r0,#1                   @ return code
    b 100f
99:
    ldr r0,iAdrszErrorGen
    bl   affichageMess
    mov r0,#-1                  @ error code
    b 100f
100:
    pop {r1-r8,lr}              @ restaur registers
    bx lr
iAdrszMessPrime:           .int szMessPrime

/***************************************************/
/*   check if a number is prime              */
/***************************************************/
/* r0 contains the number            */
/* r0 return 1 if prime  0 else */
@2147483647
@4294967297
@131071
isPrime:
    push {r1-r6,lr}    @ save registers
    cmp r0,#0
    beq 90f
    cmp r0,#17
    bhi 1f
    cmp r0,#3
    bls 80f            @ for 1,2,3 return prime
    cmp r0,#5
    beq 80f            @ for 5 return prime
    cmp r0,#7
    beq 80f            @ for 7 return prime
    cmp r0,#11
    beq 80f            @ for 11 return prime
    cmp r0,#13
    beq 80f            @ for 13 return prime
    cmp r0,#17
    beq 80f            @ for 17 return prime
1:
    tst r0,#1          @ even ?
    beq 90f            @ yes -> not prime
    mov r2,r0          @ save number
    sub r1,r0,#1       @ exposant n - 1
    mov r0,#3          @ base
    bl moduloPuR32     @ compute base power n - 1 modulo n
    cmp r0,#1
    bne 90f            @ if <> 1  -> not prime

    mov r0,#5
    bl moduloPuR32
    cmp r0,#1
    bne 90f

    mov r0,#7
    bl moduloPuR32
    cmp r0,#1
    bne 90f

    mov r0,#11
    bl moduloPuR32
    cmp r0,#1
    bne 90f

    mov r0,#13
    bl moduloPuR32
    cmp r0,#1
    bne 90f

    mov r0,#17
    bl moduloPuR32
    cmp r0,#1
    bne 90f
80:
    mov r0,#1        @ is prime
    b 100f
90:
    mov r0,#0        @ no prime
100:                 @ fin standard de la fonction
    pop {r1-r6,lr}   @ restaur des registres
    bx lr            @ retour de la fonction en utilisant lr
/********************************************************/
/*   Calcul modulo de b puissance e modulo m  */
/*    Exemple 4 puissance 13 modulo 497 = 445         */
/*                                             */
/********************************************************/
/* r0  nombre  */
/* r1 exposant */
/* r2 modulo   */
/* r0 return result  */
moduloPuR32:
    push {r1-r7,lr}    @ save registers
    cmp r0,#0          @ verif <> zero
    beq 100f
    cmp r2,#0          @ verif <> zero
    beq 100f           @
1:
    mov r4,r2          @ save modulo
    mov r5,r1          @ save exposant
    mov r6,r0          @ save base
    mov r3,#1          @ start result

    mov r1,#0          @ division de r0,r1 par r2
    bl division32R
    mov r6,r2          @ base <- remainder
2:
    tst r5,#1          @  exposant even or odd
    beq 3f
    umull r0,r1,r6,r3
    mov r2,r4
    bl division32R
    mov r3,r2          @ result <- remainder
3:
    umull r0,r1,r6,r6
    mov r2,r4
    bl division32R
    mov r6,r2          @ base <- remainder

    lsr r5,#1          @ left shift 1 bit
    cmp r5,#0          @ end ?
    bne 2b
    mov r0,r3
100:                   @ fin standard de la fonction
    pop {r1-r7,lr}     @ restaur des registres
    bx lr              @ retour de la fonction en utilisant lr

/***************************************************/
/*   division number 64 bits in 2 registers by number 32 bits */
/***************************************************/
/* r0 contains lower part dividende   */
/* r1 contains upper part dividende   */
/* r2 contains divisor   */
/* r0 return lower part quotient    */
/* r1 return upper part quotient    */
/* r2 return remainder               */
division32R:
    push {r3-r9,lr}    @ save registers
    mov r6,#0          @ init upper upper part remainder  !!
    mov r7,r1          @ init upper part remainder with upper part dividende
    mov r8,r0          @ init lower part remainder with lower part dividende
    mov r9,#0          @ upper part quotient
    mov r4,#0          @ lower part quotient
    mov r5,#32         @ bits number
1:                     @ begin loop
    lsl r6,#1          @ shift upper upper part remainder
    lsls r7,#1         @ shift upper  part remainder
    orrcs r6,#1
    lsls r8,#1         @ shift lower  part remainder
    orrcs r7,#1
    lsls r4,#1         @ shift lower part quotient
    lsl r9,#1          @ shift upper part quotient
    orrcs r9,#1
                       @ divisor sustract  upper  part remainder
    subs r7,r2
    sbcs  r6,#0        @ and substract carry
    bmi 2f             @ négative ?

                       @ positive or equal
    orr r4,#1          @ 1 -> right bit quotient
    b 3f
2:                     @ negative
    orr r4,#0          @ 0 -> right bit quotient
    adds r7,r2         @ and restaur remainder
    adc  r6,#0
3:
    subs r5,#1         @ decrement bit size
    bgt 1b             @ end ?
    mov r0,r4          @ lower part quotient
    mov r1,r9          @ upper part quotient
    mov r2,r7          @ remainder
100:                   @ function end
    pop {r3-r9,lr}     @ restaur registers
    bx lr

/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"


<?php
$csv = <<<EOT
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
EOT;

function convert($csv)
{
  $out = [];
  array_map(function($ln) use(&$out) {
      $ln    = htmlentities($ln);
      $out[] = count($out) == 0
        ? '

'.implode('	',explode(',',$ln))."

\n"
        : '
'.implode('	',explode(',',$ln))."
\n";
    }, explode("\n",$csv));
  return '
'.implode('',$out).'
';
}

echo convert($csv);


println 'decimal  octal'
for (def i = 0; i <= Integer.MAX_VALUE; i++) {
    printf ('%7d  %#5o\n', i, i)
}


import Numeric (showOct)

main :: IO ()
main =
  mapM_
    (putStrLn . flip showOct "")
    [1 ..]


link convert   # To get exbase10 method

procedure main()
    limit := 8r37777777777
    every write(exbase10(seq(0)\limit, 8))
end


(define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing
    → #syntax:string-copy
(define s "abc")
(define t (string-copy s))
    t → "abc"
(eq? s t) → #t ;; same reference, same object


[ Copy a string
  =============

  A program for the EDSAC

  Copies the source string into storage
  tank 6, which is assumed to be free,
  and then prints it from there

  Works with Initial Orders 2 ]

        T56K
        GK

[  0 ]  [email protected]      [ copy the string ]
[  1 ]  T192F
[  2 ]  [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
[ 17 ]  O192F     [ print the copy  ]
[ 18 ]  H192F
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
[ 30 ]  ZF
[ 31 ]  PF
[ 32 ]  PD
[ 33 ]  P1F
[ 34 ]  *F
        RF
        OF
        SF
        EF
        TF
        TF
        AF
        !F
        CF
        OF
        DF
        ED

        EZPF


var src := "Hello";
var dst := src;          //  copying the reference
var copy := src.clone(); //  copying the content


loop 1..30 'x [
    fs: [1]
    if x<>1 -> fs: factors.prime x
    print [pad to :string x 3 "=" join.with:" x " to [:string] fs]
]