--thanks, random python guy
langs = {'ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog',
'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus',
'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache',
'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocaml-brief',
'sas', 'actionscript3', 'qbasic', 'perl', 'bnf', 'cobol', 'powershell',
'php', 'kixtart', 'visualfoxpro', 'mirc', 'make', 'javascript', 'cpp',
'sdlbasic', 'cadlisp', 'php-brief', 'rails', 'verilog', 'xml', 'csharp',
'actionscript', 'nsis', 'bash', 'typoscript', 'freebasic', 'dot',
'applescript', 'haskell', 'dos', 'oracle8', 'cfdg', 'glsl', 'lotusscript',
'mpasm', 'latex', 'sql', 'klonec', 'ruby', 'ocaml', 'smarty', 'python',
'oracle11', 'caddcl', 'robots', 'groovy', 'smalltalk', 'diff', 'fortran',
'cfm', 'lua', 'modula3', 'vb', 'autoit', 'java', 'text', 'scala',
'lotusformulas', 'pixelbender', 'reg', '_div', 'whitespace', 'providex',
'asp', 'css', 'lolcode', 'lisp', 'inno', 'mysql', 'plsql', 'matlab',
'oobas', 'vim', 'delphi', 'xorg_conf', 'gml', 'prolog', 'bf', 'per',
'scheme', 'mxml', 'd', 'basic4gl', 'm68k', 'gnuplot', 'idl', 'abap',
'intercal', 'c_mac', 'thinbasic', 'java5', 'xpp', 'boo', 'klonecpp',
'blitzbasic', 'eiffel', 'povray', 'c', 'gettext'}

for line in io.lines() do
  for i, v in ipairs(langs) do
	line = line:gsub("<" .. v .. ">", "<lang " .. v .. ">")
    line = line:gsub("<code " .. v .. ">", "<lang " .. v .. ">")
    line = line:gsub("</" .. v .. ">", "</" .. "lang>")  --the weird concatenation is to prevent the markup from breaking
    line = line:gsub("</" .. "code>", "</" .. "lang>")
  end
  print(line)
end


#Used <#/lang> to desensitize wiki
txt := FileTools[Text][ReadFile]("C:/Users/username/Desktop/text.txt"):
#langs should be a real list of programming languages
langs := ['foo', 'bar', 'baz', 'barf'];
for lan in langs do
	txt := StringTools:-SubstituteAll(txt, cat("<", lan, ">"), cat ("<lang ", lan, ">")):
	txt := StringTools:-SubstituteAll(txt, cat("</", lan, ">"), "<#/lang>"):
	txt := StringTools:-SubstituteAll(txt, cat("<code ", lan, ">"), cat ("<lang ", lan, ">")):
	txt := StringTools:-SubstituteAll(txt, "</code>", "<#/lang>"):
end do;
print(txt);


import re, strutils

const
  Langs = ["ada", "cpp-qt", "pascal", "lscript", "z80", "visualprolog",
           "html4strict", "cil", "objc", "asm", "progress", "teraterm", "hq9plus",
           "genero", "tsql", "email", "pic16", "tcl", "apt_sources", "io", "apache",
           "vhdl", "avisynth", "winbatch", "vbnet", "ini", "scilab", "ocaml-brief",
           "sas", "actionscript3", "qbasic", "perl", "bnf", "cobol", "powershell",
           "php", "kixtart", "visualfoxpro", "mirc", "make", "javascript", "cpp",
           "sdlbasic", "cadlisp", "php-brief", "rails", "verilog", "xml", "csharp",
           "actionscript", "nsis", "bash", "typoscript", "freebasic", "dot",
           "applescript", "haskell", "dos", "oracle8", "cfdg", "glsl", "lotusscript",
           "mpasm", "latex", "sql", "klonec", "ruby", "ocaml", "smarty", "python",
           "oracle11", "caddcl", "robots", "groovy", "smalltalk", "diff", "fortran",
           "cfm", "lua", "modula3", "vb", "autoit", "java", "text", "scala",
           "lotusformulas", "pixelbender", "reg", "_div", "whitespace", "providex",
           "asp", "css", "lolcode", "lisp", "inno", "mysql", "plsql", "matlab",
           "oobas", "vim", "delphi", "xorg_conf", "gml", "prolog", "bf", "per",
           "scheme", "mxml", "d", "basic4gl", "m68k", "gnuplot", "idl", "abap",
           "intercal", "c_mac", "thinbasic", "java5", "xpp", "boo", "klonecpp",
           "blitzbasic", "eiffel", "povray", "c", "gettext"]

var text = stdin.readAll()

for lang in Langs:
  text = text.replace("<$#>" % lang, "<lang $#>" % lang)
  text = text.replace("</$#>" % lang, "


#load "str.cma"

let langs =
  Str.split (Str.regexp " ")
    "actionscript ada algol68 amigae applescript autohotkey awk bash basic \
     befunge bf c cfm cobol cpp csharp d delphi e eiffel factor false forth \
     fortran fsharp haskell haxe j java javascript lisaac lisp logo lua m4 \
     mathematica maxscript modula3 moo objc ocaml octave oz pascal perl \
     raku php pike pop11 powershell prolog python qbasic r rebol ruby \
     scala scheme slate smalltalk tcl ti89b vbnet vedit"

let read_in ic =
  let buf = Buffer.create 16384
  and tmp = String.create 4096 in
  let rec aux() =
    let bytes = input ic tmp 0 4096 in
    if bytes > 0 then begin
      Buffer.add_substring buf tmp 0 bytes;
      aux()
    end
  in
  (try aux() with End_of_file -> ());
  (Buffer.contents buf)

let repl pat tpl str =
  let reg = Str.regexp_string_case_fold pat in
  let str = Str.global_replace reg tpl str in
  (str)

(* change <%s> to <lang %s> *)
let repl1 lang str =
  let pat = "<" ^ lang ^ ">"
  and tpl = "<lang " ^ lang ^ ">" in
  (repl pat tpl str)

(* change </%s> to </la\ng> *)
let repl2 lang str =
  let pat = "</" ^ lang ^ ">"
  and tpl = "</lang"^">" in
  (repl pat tpl str)

(* change <code %s> to <lang %s> *)
let repl3 lang str =
  let pat = "<code " ^ lang ^ ">"
  and tpl = "<lang " ^ lang ^ ">" in
  (repl pat tpl str)

(* change </code> to </la\ng> *)
let repl4 lang str =
  let pat = "</code>"
  and tpl = "</lang"^">" in
  (repl pat tpl str)

let () =
  print_string (
    List.fold_left (fun str lang ->
        (repl4 lang (repl3 lang (repl2 lang (repl1 lang str))))
      ) (read_in stdin) langs)


my @langs = qw(ada cpp-qt pascal lscript z80 visualprolog
html4strict cil objc asm progress teraterm hq9plus genero tsql
email pic16 tcl apt_sources io apache vhdl avisynth winbatch
vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf
cobol powershell php kixtart visualfoxpro mirc make javascript
cpp sdlbasic cadlisp php-brief rails verilog xml csharp
actionscript nsis bash typoscript freebasic dot applescript
haskell dos oracle8 cfdg glsl lotusscript mpasm latex sql klonec
ruby ocaml smarty python oracle11 caddcl robots groovy smalltalk
diff fortran cfm lua modula3 vb autoit java text scala
lotusformulas pixelbender reg _div whitespace providex asp css
lolcode lisp inno mysql plsql matlab oobas vim delphi xorg_conf
gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl abap
intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel
povray c gettext);

my $text = join "", <STDIN>;
my $slang="/lang";
for (@langs) {
    $text =~ s|<$_>|<lang $_>|g;
    $text =~ s|</$_>|<$slang>|g;
}

$text =~ s|<code (.+?)>(.*?)</code>|<lang $1>$2<$slang>|sg;

print $text;


with javascript_semantics
constant ltext = `_div abap actionscript actionscript3 ada apache
applescript apt_sources asm asp autoit avisynth bash basic4gl bf
blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp
cpp-qt csharp css d delphi diff dos dot eiffel email fortran
freebasic genero gettext glsl gml gnuplot groovy haskell hq9plus
html4strict idl ini inno intercal io java java5 javascript kixtart
klonec klonecpp latex lisp lolcode lotusformulas lotusscript
lscript lua m68k make matlab mirc modula3 mpasm mxml mysql nsis
objc ocaml ocaml-brief oobas oracle11 oracle8 pascal per perl php
php-brief pic16 pixelbender plsql povray powershell progress
prolog providex python qbasic r rails reg robots ruby sas scala
scheme scilab sdlbasic smalltalk smarty sql tcl teraterm text
thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro
visualprolog whitespace winbatch xml xorg_conf xpp z80`,
         langs = split(substitute(ltext,"\n"," "))

function fix_tags(string text)
    for i=1 to length(langs) do
        string lang = langs[i],
               openl = sprintf("<%s>",{lang}),
               openc = sprintf("<code %s>",{lang}),
               lopen = sprintf("<lang %s>",{lang}),
               closl = sprintf("</%s>",{lang}),
               closc = sprintf("</%s>",{"code"}),
               lclos = sprintf("</%s>",{"lang"})
        text = substitute_all(text,{openl,openc,closl,closc},
                                   {lopen,lopen,lclos,lclos})
    end for
    return text
end function

constant test = """
lorem ipsum <c>some c code</c>dolor sit amet, <csharp>some
csharp code</csharp> consectetur adipisicing elit, <code r>
some r code </code>sed do eiusmod tempor incididunt
"""
puts(1,fix_tags(test))


#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(let Lang '("ada" "awk" "c" "forth" "prolog" "python" "z80")
   (in NIL
      (while (echo "<")
         (let S (till ">" T)
            (cond
               ((pre? "code " S) (prin "<lang" (cddddr (chop S))))
               ((member S Lang) (prin "<lang " S))
               ((= S "/code") (prin "</lang"))
               ((and (pre? "/" S) (member (pack (cdr (chop S))) Lang))
                  (prin "</lang") )
               (T (prin "<" S)) ) ) ) ) )
(bye)


If Not OpenConsole()
  End
ElseIf CountProgramParameters() <> 2
  PrintN("Usage: "+GetFilePart(ProgramFilename())+" InFile OutFile")
  End
EndIf

Define Infile$ =ProgramParameter(), Outfile$=ProgramParameter()
If ReadFile(0,Infile$)
  NewList Out$()
  Define line$, part$, new$, pos1, pos2
  While Not Eof(0)
    line$=ReadString(0): pos2=0
    Repeat
      pos1=FindString(line$,"<",pos2)
      pos2=FindString(line$,">",pos1)
      If pos1 And pos2
        part$=Mid(line$,pos1+1,pos2-pos1-1)
        If Mid(part$,1,1)="/"
          new$="<"+"/lang>" ; Line split to avoid problem forum coding
        ElseIf Mid(part$,1,5)="code "
          new$="<lang "+Mid(part$,6)+">"
        Else
          new$="<lang "+part$+">"
        EndIf
        line$=ReplaceString(line$,"<"+part$+">",new$)
      Else
        Break
      EndIf
    ForEver
    AddElement(Out$()): Out$()=line$
  Wend
  CloseFile(0)
  If CreateFile(1, Outfile$)
    ForEach Out$()
      WriteStringN(1,Out$())
    Next
    CloseFile(1)
  EndIf
EndIf


# coding: utf-8

import sys
import re

langs = ['ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog',
'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus',
'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache',
'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocaml-brief',
'sas', 'actionscript3', 'qbasic', 'perl', 'bnf', 'cobol', 'powershell',
'php', 'kixtart', 'visualfoxpro', 'mirc', 'make', 'javascript', 'cpp',
'sdlbasic', 'cadlisp', 'php-brief', 'rails', 'verilog', 'xml', 'csharp',
'actionscript', 'nsis', 'bash', 'typoscript', 'freebasic', 'dot',
'applescript', 'haskell', 'dos', 'oracle8', 'cfdg', 'glsl', 'lotusscript',
'mpasm', 'latex', 'sql', 'klonec', 'ruby', 'ocaml', 'smarty', 'python',
'oracle11', 'caddcl', 'robots', 'groovy', 'smalltalk', 'diff', 'fortran',
'cfm', 'lua', 'modula3', 'vb', 'autoit', 'java', 'text', 'scala',
'lotusformulas', 'pixelbender', 'reg', '_div', 'whitespace', 'providex',
'asp', 'css', 'lolcode', 'lisp', 'inno', 'mysql', 'plsql', 'matlab',
'oobas', 'vim', 'delphi', 'xorg_conf', 'gml', 'prolog', 'bf', 'per',
'scheme', 'mxml', 'd', 'basic4gl', 'm68k', 'gnuplot', 'idl', 'abap',
'intercal', 'c_mac', 'thinbasic', 'java5', 'xpp', 'boo', 'klonecpp',
'blitzbasic', 'eiffel', 'povray', 'c', 'gettext']

slang = '/lang'
code='code'

text = sys.stdin.read()

for i in langs:
    text = text.replace("<%s>" % i,"<lang %s>" % i)
    text = text.replace("</%s>" % i, "<%s>" % slang)

text = re.sub("(?s)<%s (.+?)>(.*?)</%s>"%(code,code), r"<lang \1>\2<%s>" % slang, text)

sys.stdout.write(text)


fixtags <- function(page)
{
   langs <- c("c", "c-sharp", "r")   # a complete list is required, obviously
   langs <- paste(langs, collapse="|")
   page <- gsub(paste("<(", langs, ")>", sep=""), "<lang \\1>", page)
   page <- gsub(paste("</(", langs, ")>", sep=""), "</#####lang>", page)
   page <- gsub(paste("", sep=""), "<lang \\1>", page)
   page <- gsub(paste("", sep=""), "</#####lang>", page)
   page
}

page <- "lorem ipsum <c>some c code</c>dolor sit amet,<c-sharp>some c-sharp code</c-sharp>
consectetur adipisicing elit,some r codesed do eiusmod tempor incididunt"
fixtags(page)


#lang racket

(define lang-names '("X" "Y" "Z"))

(define rx
  (regexp (string-join lang-names "|"
                       #:before-first "<((/?(?:code)?)(?:( )?("
                       #:after-last "))?)>")))

(let loop () ; does all in a single scan
  (define m (regexp-match rx (current-input-port) 0 #f (current-output-port)))
  (when m
    (define-values [all pfx space lang] (apply values (cdr m)))
    (printf "<~a>"
      (cond [(not lang) (if (equal? pfx #"/code") #"/lang" all)]
            [space (if (equal? pfx #"code") (bytes-append #"lang " lang) all)]
            [(equal? pfx #"") (bytes-append #"lang " lang)]
            [(equal? pfx #"/") #"/lang"]
            [else all]))
    (loop)))


my @langs = <
    abap actionscript actionscript3 ada apache applescript apt_sources
    asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c caddcl
    cadlisp cfdg cfm cil c_mac cobol cpp cpp-qt csharp css d delphi
    diff _div dos dot eiffel email fortran freebasic genero gettext
    glsl gml gnuplot groovy haskell hq9plus html4strict idl ini inno
    intercal io java java5 javascript kixtart klonec klonecpp latex lisp
    lolcode lotusformulas lotusscript lscript lua m68k make matlab mirc
    modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11
    oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray
    powershell progress prolog providex python qbasic rails reg robots
    ruby sas scala scheme scilab sdlbasic smalltalk smarty sql tcl teraterm
    text thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro
    visualprolog whitespace winbatch xml xorg_conf xpp z80
>;

$_ = slurp;

for @langs -> $l {
    s:g:i [ '<' 'lang '?  $l '>' ] = "<lang $l>";
    s:g [ '</' $l '>' ] = '</' ~ 'lang>';
}

s:g [ '<code '(.+?) '>' (.*?) '</code>' ] = "<lang $0>{$1}</"~"lang>";

.say;


/*REXX program  fixes (changes)  depreciated  HTML  code tags  with  newer tags.        */
@="<";  old.=;        old.1 = @'%s>'         ;     new.1 = @"lang %s>"
                      old.2 = @'/%s>'        ;     new.2 = @"/lang>"
                      old.3 = @'code %s>'    ;     new.3 = @"lang %s>"
                      old.4 = @'/code>'      ;     new.4 = @"/lang>"

iFID = 'Wikisource.txt'                          /*the  Input File  IDentifier.         */
oFID = 'converted.txt'                           /*the Output   "      "                */

  do  while lines(iFID)\==0                      /*keep reading the file until finished.*/
  $= linein(iFID)                                /*read a record from the input file.   */
                     do j=1  while old.j \== ''  /*change old ──► new  until  finished. */
                     $= changestr(old.j,$,new.j) /*let REXX do the heavy lifting.       */
                     end   /*j*/
  call lineout oFID,$                            /*write re-formatted record to output. */
  end   /*while*/                                /*stick a fork in it,  we're all done. */


# get all stdin in one string
#text = $stdin.read
# for testing, use
text = DATA.read
slash_lang = '/lang'
langs = %w(foo bar baz) # actual list of languages declared here
for lang in langs
  text.gsub!(Regexp.new("<(#{lang})>")) {"<lang #$1>"}
  text.gsub!(Regexp.new("</#{lang}>"), "<#{slash_lang}>")
end
text.gsub!(//, '<lang \1>')
text.gsub!(/<\/code>/, "<#{slash_lang}>")
print text

__END__
Lorem ipsum saepe audire elaboraret ne quo, id equidem
atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>,
ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu
altera electram. Tota adhuc altera te sea, soluta appetere ut mel</bar>.
Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu. Eam volumus perpetua
constituto id, mea an omittam fierent vituperatoribus.


extern crate regex;

use std::io;
use std::io::prelude::*;

use regex::Regex;

const LANGUAGES: &str =
    "_div abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit \
     avisynth bash basic4gl bf blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp \
     cpp-qt csharp css d delphi diff dos dot eiffel email fortran freebasic genero gettext glsl \
     gml gnuplot groovy haskell hq9plus html4strict idl ini inno intercal io java java5 \
     javascript kixtart klonec klonecpp latex lisp lolcode lotusformulas lotusscript lscript lua \
     m68k make matlab mirc modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11 \
     oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray powershell progress \
     prolog providex python qbasic rails reg robots ruby rust sas scala scheme scilab sdlbasic \
     smalltalk smarty sql tcl teraterm text thinbasic tsql typoscript vb vbnet verilog vhdl vim \
     visualfoxpro visualprolog whitespace winbatch xml xorg_conf xpp z80";

fn fix_tags(languages: &[&str], text: &str) -> String {
    let mut replaced_text = text.to_owned();

    for lang in languages.iter() {
        let bad_open = Regex::new(&format!("<{lang}>|<code {lang}>", lang = lang)).unwrap();
        let bad_close = Regex::new(&format!("</{lang}>|</code>", lang = lang)).unwrap();
        let open = format!("<lang {}>", lang);
        let close = "</lang>";

        replaced_text = bad_open.replace_all(&replaced_text, &open[..]).into_owned();
        replaced_text = bad_close
            .replace_all(&replaced_text, &close[..])
            .into_owned();
    }

    replaced_text
}

fn main() {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.lock().read_to_string(&mut buf).unwrap();
    println!(
        "{}",
        fix_tags(&LANGUAGES.split_whitespace().collect::<Vec<_>>(), &buf)
    );
}


object FixCodeTags extends App {
  val rx = // See for regex explanation: https://regex101.com/r/N8X4x7/3/
           // Flags ignore case, dot matching line breaks, unicode support
    s"(?is)<(?:(?:code\\s+)?(${langs.mkString("|")}))>(.+?|)<\\/(?:code|\\1)>".r

  def langs = // Real list of langs goes here
    Seq("bar", "baz", "foo", "Scala", "உயிர்/Uyir", "Müller")

  def markDown =
    """Lorem ipsum saepe audire elaboraret ne quo, id equidem
      |atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>, ius
      |ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu
      |altera electram. Tota adhuc altera te sea, soluta appetere ut mel
      |</bar>. Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu.
      |Eam volumus perpetua constituto id, mea an omittam fierent vituperatoribus.
      |Empty element: <Müller></Müller><scaLa></Scala><உயிர்/Uyir></உயிர்/Uyir>""".stripMargin

  println(rx.replaceAllIn(markDown, _ match {
    case rx(langName, langCode) => s"<lang ${langName.capitalize}>${langCode}<${"/lan"}g>"
  })) // ${"/lan"}g is the <noWiki> escape.

}


var langs = %w(ada cpp-qt pascal lscript z80 visualprolog
html4strict cil objc asm progress teraterm hq9plus genero tsql
email pic16 tcl apt_sources io apache vhdl avisynth winbatch
vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf
cobol powershell php kixtart visualfoxpro mirc make javascript
cpp sdlbasic cadlisp php-brief rails verilog xml csharp
actionscript nsis bash typoscript freebasic dot applescript
haskell dos oracle8 cfdg glsl lotusscript mpasm latex sql klonec
ruby ocaml smarty python oracle11 caddcl robots groovy smalltalk
diff fortran cfm lua modula3 vb autoit java text scala
lotusformulas pixelbender reg _div whitespace providex asp css
lolcode lisp inno mysql plsql matlab oobas vim delphi xorg_conf
gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl abap
intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel
povray c gettext).join('|');

var text = ARGF.slurp;

text.gsub!(Regex.new('<(' + langs + ')>'), {|s1| "<lang #{s1}>" });
text.gsub!(Regex.new('</(' + langs + ')>'), "</" + "lang>");
text.gsub!(
    Regex.new('<code\h+(' + langs + ')>(.*?)</code>', 's'),
    {|s1,s2| "<lang #{s1}>#{s2}</" + "lang>"}
);

print text;


set langs {
    ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm
    hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet
    ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart
    visualfoxpro mirc make javascript cpp sdlbasic cadlisp php-brief rails verilog xml
    csharp actionscript nsis bash typoscript freebasic dot applescript haskell dos oracle8
    cfdg glsl lotusscript mpasm latex sql klonec ruby ocaml smarty python oracle11 caddcl
    robots groovy smalltalk diff fortran cfm lua modula3 vb autoit java text scala lotusformulas
    pixelbender reg _div whitespace providex asp css lolcode lisp inno mysql plsql matlab
    oobas vim delphi xorg_conf gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl
    abap intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel povray c gettext
}

set text [read stdin]
set slang /lang
foreach lang $langs {
    set text [regsub -all "<$lang>" $text "<lang $lang>"]
    set text [regsub -all "</$lang>" $text "<$slang>"]
}
set text [regsub -all "<code (.+?)>(.+?)</code>" $text "<lang \\1>\\2<$slang>"]


import "./pattern" for Pattern

var source = """
Lorem ipsum saepe audire elaboraret ne quo, id equidem
atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>,
ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu
altera electram. Tota adhuc altera te sea, soluta appetere ut mel</bar>.
Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu. Eam volumus perpetua
constituto id, mea an omittam fierent vituperatoribus.
"""

// to avoid problems dispaying code on RC
var entag = Fn.new { |s| "<%(s)>" }

var langs = ["foo", "bar", "baz"] // in principle these can be anything

for (lang in langs) {
    var s = "[%(lang)]"
    var pairs = [
        ["<%(s)>", entag.call("lang $1")],
        ["<//%(s)>", entag.call("/lang")],
        ["", entag.call("lang $1")],
        ["<//code>", entag.call("/lang")]
    ]

    for (pair in pairs) {
        var p = Pattern.new(pair[0])
        source = p.replaceAll(source, pair[1])
    }
}

System.print(source)


fcn replace(data,src,dstpat){
   re,n,buf:=RegExp(src),0,Data();
   while(re.search(data,True,n)){
      matched:=re.matched;	// L(L(12,3),"c")
      data[matched[0].xplode()]=re.sub(data,dstpat,buf);  // "\1" --> "c"
      n=matched[0].sum(0);  // move past change
   }
}
data:=File.stdin.read();
foreach src,dst in (T(
     T(0'|<(\w+)>|,     0'|<lang \1>|), T(0'|</(\w+)>|,"</" "lang>"),
     T(0'|<code (\w+)>|,0'|<lang \1>|) )){
   replace(data,src,dst)
}
print(data.text);


F polar(r, theta)
   R r * (cos(theta) + sin(theta) * 1i)

F croots(n)
   R (0 .< n).map(k -> polar(1, 2 * k * math:pi / @n))

L(nr) 2..10
   print(nr‘ ’croots(nr))


with Ada.Text_IO;                 use Ada.Text_IO;
with Ada.Float_Text_IO;           use Ada.Float_Text_IO;
with Ada.Numerics.Complex_Types;  use Ada.Numerics.Complex_Types;

procedure Roots_Of_Unity is
   Root : Complex;
begin
   for N in 2..10 loop
      Put_Line ("N =" & Integer'Image (N));
      for K in 0..N - 1 loop
         Root :=
             Compose_From_Polar
             (  Modulus  => 1.0,
                Argument => Float (K),
                Cycle    => Float (N)
             );
            -- Output
         Put ("   k =" & Integer'Image (K) & ", ");
         if Re (Root) < 0.0 then
            Put ("-");
         else
            Put ("+");
         end if;
         Put (abs Re (Root), Fore => 1, Exp => 0);
         if Im (Root) < 0.0 then
            Put ("-");
         else
            Put ("+");
         end if;
         Put (abs Im (Root), Fore => 1, Exp => 0);
         Put_Line ("i");
      end loop;
   end loop;
end Roots_Of_Unity;


FORMAT complex fmt=$g(-6,4)"⊥"g(-6,4)$;
FOR root FROM 2 TO 10 DO
  printf(($g(4)$,root));
  FOR n FROM 0 TO root-1 DO
    printf(($xf(complex fmt)$,complex exp( 0 I 2*pi*n/root)))
  OD;
  printf($l$)
OD


rect: function [r,phi][
    to :complex @[ r * cos phi, r * sin phi ]
]
roots: function [n][
    map 0..dec n 'k -> rect 1.0 2 * k * pi / n
]

loop 2..10 'nr ->
    print [pad to :string nr 3 "=>" join.with:", " to [:string] .format:".3f" roots nr]


# syntax: GAWK -f ROOTS_OF_UNITY.AWK
BEGIN {
    pi = 3.1415926
    for (n=2; n<=5; n++) {
      printf("%d: ",n)
      for (root=0; root<=n-1; root++) {
        real = cos(2 * pi * root / n)
        imag = sin(2 * pi * root / n)
        printf("%8.5f %8.5fi",real,imag)
        if (root != n-1) { printf(", ") }
      }
      printf("\n")
    }
    exit(0)
}


 CLS
 PI = 3.1415926#
 n = 5 'this can be changed for any desired n
 angle = 0 'start at angle 0
 DO
 	real = COS(angle) 'real axis is the x axis
 	IF (ABS(real) < 10 ^ -5) THEN real = 0 'get rid of annoying sci notation
 	imag = SIN(angle) 'imaginary axis is the y axis
 	IF (ABS(imag) < 10 ^ -5) THEN imag = 0 'get rid of annoying sci notation
 	PRINT real; "+"; imag; "i" 'answer on every line
 	angle = angle + (2 * PI) / n
 'all the way around the circle at even intervals
 LOOP WHILE angle < 2 * PI


      @% = &20408
      FOR n% = 2 TO 5
        PRINT STR$(n%) ": " ;
        FOR root% = 0 TO n%-1
          real = COS(2*PI * root% / n%)
          imag = SIN(2*PI * root% / n%)
          PRINT real imag "i" ;
          IF root% <> n%-1 PRINT "," ;
        NEXT
        PRINT
      NEXT n%


using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

class Program
{
    static IEnumerable<Complex> RootsOfUnity(int degree)
    {
        return Enumerable
            .Range(0, degree)
            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
    }

    static void Main()
    {
        var degree = 3;
        foreach (var root in RootsOfUnity(degree))
        {
            Console.WriteLine(root);
        }
    }
}


#include <complex>
#include <cmath>
#include <iostream>

double const pi = 4 * std::atan(1);

int main()
{
  for (int n = 2; n <= 10; ++n)
  {
    std::cout << n << ": ";
    for (int k = 0; k < n; ++k)
      std::cout << std::polar(1, 2*pi*k/n) << " ";
    std::cout << std::endl;
  }
}


# Find the n nth-roots of 1
nth_roots_of_unity = (n) ->
  (complex_unit_vector(2*Math.PI*i/n) for i in [1..n])

complex_unit_vector = (rad) ->
  new Complex(Math.cos(rad), Math.sin(rad))

class Complex
  constructor: (@real, @imag) ->
  toString: ->
    round_z = (n) ->
      if Math.abs(n) < 0.00005 then 0 else n
    fmt = (n) -> n.toFixed(3)
    real = round_z @real
    imag = round_z @imag
    s = ''
    if real and imag
      "#{fmt real}+#{fmt imag}i"
    else if real or !imag
      "#{fmt real}"
    else
      "#{fmt imag}i"

do ->
  for n in [2..5]
    console.log "---1 to the 1/#{n}"
    for root in nth_roots_of_unity n
      console.log root.toString()


(defun roots-of-unity (n)
 (loop for i below n
       collect (cis (* pi (/ (* 2 i) n)))))


require "complex"

def roots_of_unity(n)
  (0...n).map { |k| Math.exp((2 * Math::PI * k / n).i) }
end

p roots_of_unity(3)


import std.stdio, std.range, std.algorithm, std.complex;
import std.math: PI;

auto nthRoots(in int n) pure nothrow {
    return n.iota.map!(k => expi(PI * 2 * (k + 1) / n));
}

void main() {
    foreach (immutable i; 1 .. 6)
        writefln("#%d: [%(%5.2f, %)]", i, i.nthRoots);
}


program Roots_of_unity;

{$APPTYPE CONSOLE}

uses
  System.VarCmplx;

function RootOfUnity(degree: integer): Tarray<Variant>;
var
  k: Integer;
begin
  SetLength(result, degree);
  for k := 0 to degree - 1 do
    Result[k] := VarComplexFromPolar(1, 2 * pi * k / degree);
end;

const
  n = 3;
var
  num: Variant;
begin
  Writeln('Root of unity from ', n, ':'#10);
  for num in RootOfUnity(n) do
    Writeln(num);
  Readln;
end.


PROGRAM UNITY_ROOTS

!
! for rosettacode.org
!

BEGIN
   PRINT(CHR$(12);) !CLS
   N=5                                       ! this can be changed for any desired n
   ANGLE=0                                   ! start at ANGLE 0
   REPEAT
     REAL=COS(ANGLE)                         ! real axis is the x axis
     IF (ABS(REAL)<10^-5) THEN REAL=0 END IF ! get rid of annoying sci notation
     IMAG=SIN(ANGLE)                         ! imaginary axis is the y axis
     IF (ABS(IMAG)<10^-5) THEN IMAG=0 END IF ! get rid of annoying sci notation
     PRINT(REAL;"+";IMAG;"i")                ! answer on every line
     ANGLE+=(2*π)/N
                                             ! all the way around the circle at even intervals
   UNTIL ANGLE>=2*π
END PROGRAM


USING: math.functions prettyprint ;

1 3 roots .


: f0. ( f -- )
  fdup 0e 0.001e f~ if fdrop 0e then f. ;
: .roots ( n -- )
  dup 1 do
    pi i 2* 0 d>f f* dup 0 d>f f/          ( F: radians )
    fsincos cr ." real " f0. ." imag " f0.
  loop drop ;

3 set-precision
5 .roots


PROGRAM Roots

  COMPLEX :: root
  INTEGER :: i, n
  REAL :: angle, pi

  pi = 4.0 * ATAN(1.0)
  DO n = 2, 7
    angle = 0.0
    WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
    DO i = 1, n
      root = CMPLX(COS(angle), SIN(angle))
      WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j  "
      angle = angle + (2.0*pi / REAL(n))
    END DO
    WRITE(*,*)
  END DO

END PROGRAM Roots


#define twopi 6.2831853071795864769252867665590057684

dim as uinteger m, n
dim as double real, imag, theta
input "n? ", n

for m = 0 to n-1
    theta = m*twopi/n
    real = cos(theta)
    imag = sin(theta)
    if imag >= 0 then
        print using "#.##### + #.##### i"; real; imag
    else
        print using "#.##### - #.##### i"; real; -imag
    end if
next m


roots[n] :=
{
    a = makeArray[[n], 0]
    alpha = 360/n degrees
    theta = 0 degrees
    for k = 0 to length[a] - 1
    {
        [email protected] = cos[theta] + i sin[theta]
        theta = theta + alpha
    }
    a
}


import math.{exp, Pi}

def rootsOfUnity( n ) = {exp( 2Pi i k/n ) | k <- 0:n}

println( rootsOfUnity(3) )


window 1, @"Roots of Unity", (0,0,1050,200)

long n, root
double real, imag

for n = 2 to 7
  print n;":" ;
  for root = 0 to n-1
    real = cos( 2 * pi * root / n)
    imag = sin( 2 * pi * root / n)
    print using "-##.#####"; real;using "-##.#####"; imag; "i";
    if root != n-1 then print ",";
  next
  print
next

HandleEvents


package main

import (
    "fmt"
    "math"
    "math/cmplx"
)

func main() {
    for n := 2; n <= 5; n++ {
        fmt.Printf("%d roots of 1:\n", n)
        for _, r := range roots(n) {
            fmt.Printf("  %18.15f\n", r)
        }
    }
}

func roots(n int) []complex128 {
    r := make([]complex128, n)
    for i := 0; i < n; i++ {
        r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
    }
    return r
}


/** The following closure creates a list of n evenly-spaced points around the unit circle,
  * useful in FFT calculations, among other things */
def rootsOfUnity = { n ->
    (0..<n).collect {
        Complex.fromPolar(1, 2 * Math.PI * it / n)
    }
}


import Data.Complex (Complex, cis)

rootsOfUnity :: (Enum a, Floating a) => a -> [Complex a]
rootsOfUnity n =
  [ cis (2 * pi * k / n)
  | k <- [0 .. n - 1] ]

main :: IO ()
main = mapM_ print $ rootsOfUnity 3


procedure main()
   roots(10)
end

procedure roots(n)
   every n := 2 to 10 do
       every writes(n | (str_rep((0 to (n-1)) * 2 * &pi / n)) | "\n")
end

procedure str_rep(k)
  return " " || cos(k) || "+" || sin(k) || "i"
end


n = 5
print,  exp( dcomplex( 0, 2*!dpi/n) ) ^ ( 1 + indgen(n) )


import java.util.Locale;

public class Test {

    public static void main(String[] a) {
        for (int n = 2; n < 6; n++)
            unity(n);
    }

    public static void unity(int n) {
        System.out.printf("%n%d: ", n);

        //all the way around the circle at even intervals
        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {

            double real = Math.cos(angle); //real axis is the x axis

            if (Math.abs(real) < 1.0E-3)
                real = 0.0; //get rid of annoying sci notation

            double imag = Math.sin(angle); //imaginary axis is the y axis

            if (Math.abs(imag) < 1.0E-3)
                imag = 0.0;

            System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
        }
    }
}


function Root(angle) {
	with (Math) { this.r = cos(angle); this.i = sin(angle) }
}

Root.prototype.toFixed = function(p) {
	return this.r.toFixed(p) + (this.i >= 0 ? '+' : '') + this.i.toFixed(p) + 'i'
}

function roots(n) {
	var rs = [], teta = 2*Math.PI/n
	for (var angle=0, i=0; i<n; angle+=teta, i+=1) rs.push( new Root(angle) )
	return rs
}

for (var n=2; n<8; n+=1) {
	document.write(n, ': ')
	var rs=roots(n); for (var i=0; i<rs.length; i+=1) document.write( i ? ', ' : '', rs[i].toFixed(5) )
	document.write('<br>')
}


def nthroots(n):
  (8 * (1|atan)) as $twopi
  | range(0;n) | (($twopi * .) / n) as $angle | [ ($angle | cos), ($angle | sin) ];

nthroots(10)


nthroots(n::Integer) = [ cospi(2k/n)+sinpi(2k/n)im for k = 0:n-1 ]


import java.lang.Math.*

data class Complex(val r: Double, val i: Double) {
    override fun toString() = when {
        i == 0.0 -> r.toString()
        r == 0.0 -> i.toString() + 'i'
        else -> "$r + ${i}i"
    }
}

fun unity_roots(n: Number) = (1..n.toInt() - 1).map {
    val a = it * 2 * PI / n.toDouble()
    var r = cos(a); if (abs(r) < 1e-6) r = 0.0
    var i = sin(a); if (abs(i) < 1e-6) i = 0.0
    Complex(r, i)
}

fun main(args: Array<String>) {
    (1..4).forEach { println(listOf(1) + unity_roots(it)) }
    println(listOf(1) + unity_roots(5.0))
}


WindowWidth  =400
WindowHeight =400

'nomainwin

open "N'th Roots of One" for graphics_nsb_nf as #w

#w "trapclose [quit]"

for n =1 To 10
    angle =0
    #w "font arial 16 bold"
    print n; "th roots."
    #w "cls"
    #w "size 1 ; goto 200 200 ; down ; color lightgray ; circle 150 ; size 10 ; set 200 200 ; size 2"
    #w "up ; goto 200 0 ; down ; goto 200 400 ; up ; goto 0 200 ; down ; goto 400 200"
    #w "up ; goto 40 20 ; down ; color black"
    #w "font arial 6"
    #w "\"; n; " roots of 1."

    for i = 1 To n
        x = cos( Radian( angle))
        y = sin( Radian( angle))

        print using( "##", i); ":  ( " + using( "##.######", x);_
          " +i *" +using( "##.######", y); ")      or     e^( i *"; i -1; " *2 *Pi/ "; n; ")"

        #w "color "; 255 *i /n; " 0 "; 256 -255 *i /n
        #w "up ; goto 200 200"
        #w "down ; goto "; 200 +150 *x; " "; 200 -150 *y
        #w "up   ; goto "; 200 +165 *x; " "; 200 -165 *y
        #w "\"; str$( i)
        #w "up"

        angle =angle +360 /n

    next i

    timer 500, [on]
    wait
  [on]
    timer 0
next n

wait

[quit]
    close #w

    end

function Radian( theta)
    Radian =theta *3.1415926535 /180
end function


--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs.
complex = setmetatable({
__add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end,
__sub = function(u, v) return complex(u.real - v.real, u.imag - v.imag) end,
__mul = function(u, v) return complex(u.real * v.real - u.imag * v.imag, u.real * v.imag + u.imag * v.real) end,
__div = function(u, v) return u * complex(v.real / v.norm, -v.imag / v.norm) end,
__unm = function(u) return complex(-u.real, -u.imag) end,
__concat = function(u, v)
    if type(u) == "table" then return u.real .. " + " .. u.imag .. "i" .. v
	elseif type(u) == "string" or type(u) == "number" then return u .. v.real .. " + " .. v.imag .. "i"
	end end,
__index = function(u, index)
  local operations = {
    norm = function(u) return u.real ^ 2 + u.imag ^ 2 end,
    conj = function(u) return complex(u.real, -u.imag) end,
  }
  return operations[index] and operations[index](u)
end,
__newindex = function() error() end
}, {
__call = function(z, realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end
} )
n = io.read() + 0
val = complex(math.cos(2*math.pi / n), math.sin(2*math.pi / n))
root = complex(1, 0)
for i = 1, n do
  root = root * val
  print(root .. "")
end


RootsOfUnity := proc( n )
    solve(z^n = 1, z);
end proc:


RootsUnity[nthroot_Integer?Positive] := Table[Exp[2 Pi I i/nthroot], {i, 0, nthroot - 1}]


function z = rootsOfUnity(n)

    assert(n >= 1,'n >= 1');
    z = roots([1 zeros(1,n-1) -1]);

end


complexRoots = function(n)
    result = []
    for i in range(0, n-1)
        real = cos(2*pi * i/n)
        if abs(real) < 1e-6 then real = 0
        imag = sin(2*pi * i/n)
        if abs(imag) < 1e-6 then imag = 0
        result.push real + " " + "+" * (imag>=0) + imag + "i"
    end for
    return result
end function

for i in range(2,5)
    print i + ": " + complexRoots(i).join(", ")
end for


П0	0	П1	ИП1	sin	ИП1	cos	С/П	2	пи
*	ИП0	/	ИП1	+	П1	БП	03


import complex, math, sequtils, strformat, strutils

proc roots(n: Positive): seq[Complex64] =
  for k in 0..<n:
    result.add rect(1.0, 2 * k.float * Pi / n.float)

proc toString(z: Complex64): string =
  &"{z.re:.3f} + {z.im:.3f}i"

for nr in 2..10:
  let result = roots(nr).map(toString).join(", ")
  echo &"{nr:2}: {result}"


open Complex

let pi = 4. *. atan 1.

let () =
  for n = 1 to 10 do
    Printf.printf "%2d " n;
    for k = 1 to n do
      let ret = polar 1. (2. *. pi *. float_of_int k /. float_of_int n) in
        Printf.printf "(%f + %f i)" ret.re ret.im
    done;
    print_newline ()
  done


for j = 2 : 10
  printf("*** %d\n", j);
  for n = 1 : j
    disp(exp(2i*pi*n/j));
  endfor
  disp("");
endfor


/*REXX program computes the  K  roots of unity  (which include complex roots).*/
parse Version v
Say v
parse arg n frac .                     /*get optional arguments from the C.L. */
if n==''    then n=1                   /*Not specified?  Then use the default.*/
if frac=''  then frac=5                /* "      "         "   "   "     "    */
start=abs(n)                           /*assume only one  K  is wanted.       */
if n<0      then start=1               /*Negative?  Then use a range of  K's. */
                                       /*display unity roots for a range,  or */
  do k=start  to abs(n)                /*                   just for one  K.  */
  say right(k 'roots of unity',40,"-") /*display a pretty separator with title*/
     do angle=0  by 360/k  for k       /*compute the angle for each root.     */
     rp=adjust(rxCalcCos(angle,,'D'))  /*compute real part via  COS  function.*/
     if left(rp,1)\=='-' then rp=" "rp /*not negative?  Then pad with a blank.*/
     ip=adjust(rxCalcSin(angle,,'D'))  /*compute imaginary part via SIN funct.*/
     if left(ip,1)\=='-' then ip="+"ip /*Not negative?  Then pad with  + char.*/
     if ip=0  then say rp              /*Only real part? Ignore imaginary part*/
              else say left(rp,frac+4)ip'i'   /*show the real & imaginary part*/
     end  /*angle*/
  end      /*k*/
exit                                   /*stick a fork in it,  we're all done. */
/*----------------------------------------------------------------------------*/
adjust: parse arg x; near0='1e-' || (digits()-digits()%10)   /*compute small #*/
        if abs(x)<near0  then x=0            /*if near zero, then assume zero.*/
        return format(x,,frac)/1             /*fraction digits past dec point.*/
::requires rxMath library


Program Roots;

var
  root: record  // poor man's complex type.
    r: real;
    i: real;
  end;
  i, n:  integer;
  angle: real;

begin
  for n := 2 to 7 do
  begin
    angle := 0.0;
    write(n, ': ');
    for i := 1 to n do
    begin
      root.r := cos(angle);
      root.i := sin(angle);
      write(root.r:8:5, root.i:8:5, 'i ');
      angle := angle + (2.0 * pi / n);
    end;
    writeln;
  end;
end.


use Math::Complex;

foreach my $n (2 .. 10) {
  printf "%2d", $n;
  my @roots = root(1,$n);
  foreach my $root (@roots) {
    $root->display_format(style => 'cartesian', format => '%.3f');
    print " $root";
  }
  print "\n";
}


with javascript_semantics
for n=2 to 10 do
    printf(1,"%2d:",n)
    for root=0 to n-1 do
        atom real = cos(2*PI*root/n)
        atom imag = sin(2*PI*root/n)
        printf(1,"%s %6.3f %6.3fi",{iff(root?",":""),real,imag})
    end for
    printf(1,"\n")
end for


(load "@lib/math.l")

(for N (range 2 10)
   (let Angle 0.0
      (prin N ": ")
      (for I N
         (let Ipart (sin Angle)
            (prin
               (round (cos Angle) 4)
               (if (lt0 Ipart) "-" "+")
               "j"
               (round (abs Ipart) 4)
               "  " ) )
         (inc 'Angle (*/ 2 pi N)) )
      (prinl) ) )


roots(N, Rs) :-
    succ(Pn, N), numlist(0, Pn, Ks),
    maplist(root(N), Ks, Rs).

root(N, M, R2) :-
    R0 is (2*M) rdiv N,  % multiple of PI
    (R0 > 1 -> R1 is R0 - 2; R1 = R0),  % adjust for principal values
    cis(R1, R2).

cis(0, 1) :- !.
cis(1, -1) :- !.
cis(1 rdiv 2, i) :- !.
cis(-1 rdiv 2, -i) :- !.
cis(-1 rdiv Q, exp(-i*pi/Q)) :- !.
cis(1 rdiv Q, exp(i*pi/Q)) :- !.
cis(P rdiv Q, exp(P*i*pi/Q)).


OpenConsole()
For n = 2 To 10
  angle = 0
  PrintN(Str(n))
  For i = 1 To n
    x.f = Cos(Radian(angle))
    y.f = Sin(Radian(angle))
    PrintN( Str(i) + ":  " + StrF(x, 6) +  " / " + StrF(y, 6))
    angle = angle + (360 / n)
  Next
Next
Input()


import cmath

class Complex(complex):
    def __repr__(self):
        rp = '%7.5f' % self.real if not self.pureImag() else ''
        ip = '%7.5fj' % self.imag if not self.pureReal() else ''
        conj = '' if (
            self.pureImag() or self.pureReal() or self.imag < 0.0
        ) else '+'
        return '0.0' if (
            self.pureImag() and self.pureReal()
        ) else rp + conj + ip

    def pureImag(self):
        return abs(self.real) < 0.000005

    def pureReal(self):
        return abs(self.imag) < 0.000005

def croots(n):
    if n <= 0:
        return None
    return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
    # in pre-Python 2.6:
    #   return (Complex(cmath.exp(2j*k*cmath.pi/n)) for k in range(n))

for nr in range(2, 11):
    print(nr, list(croots(nr)))


for(j in 2:10) {
  r <- sprintf("%d: ", j)
  for(n in 1:j) {
    r <- paste(r, format(exp(2i*pi*n/j), digits=4), ifelse(n<j, ",", ""))
  }
  print(r)
}


#lang racket

(define (roots-of-unity n)
  (for/list ([k n])
    (make-polar 1 (* k (/ (* 2 pi) n)))))


constant n = 10;
for ^n -> \k {
    say cis(k*τ/n);
}


/*REXX program computes the  K  roots of  unity  (which usually includes complex roots).*/
numeric digits length( pi() )  -  length(.)      /*use number of decimal digits in  pi. */
parse arg n frac .                               /*get optional arguments from the C.L. */
if   n=='' |    n==","  then     n= 1            /*Not specified?  Then use the default.*/
if frac='' | frac==","  then  frac= 5            /* "      "         "   "   "     "    */
                             start= abs(n)       /*assume only one  K  is wanted.       */
if n<0                  then start= 1            /*Negative?  Then use a range of  K's. */
      do #=start  to abs(n)                      /*show unity roots  (for a range or 1).*/
      say right(# 'roots of unity', 40, "─") ' (showing' frac "fractional decimal digits)"
         do angle=0  by pi*2/#  for #            /*compute the angle for each root.     */
         Rp= adj( cos(angle) )                   /*the    real   part via COS  function.*/
         Ip= adj( sin(angle) )                   /* "  imaginary   "   "  SIN      "    */
         if Rp>=0  then Rp= ' 'Rp                /*Not neg?  Then pad with a blank char.*/
         if Ip>=0  then Ip= '+'Ip                /* "   "      "   "    "  "  plus   "  */
         if Ip =0  then say Rp                   /*Only real part? Ignore imaginary part*/
                   else say left(Rp,frac+4)Ip'i' /*display the real and imaginary part. */
         end  /*angle*/
      end     /*#*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
adj: parse arg x; if abs(x) < ('1e-')(digits()*9%10)  then x= 0;  return format(x,,frac)/1
pi:  pi=3.141592653589793238462643383279502884197169399375105820974944592307816; return pi
r2r: pi2= pi() + pi;     return arg(1)  //  pi2  /*reduce #radians: -2pi ─► +2pi radians*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x;   x= r2r(x);   a= abs(x);   numeric fuzz min(9, digits() - 9)
     pi1_3=pi/3;      if a=pi1_3  then return .5;        if a=pi*.5 | a=pi2  then return 0
     if a=pi  then return -1;  if a=pi1_3*2  then return -.5;   z= 1;  _= 1;     $x= x * x
       do k=2  by 2  until p=z;  p=z;  _= -_ * $x / (k*(k-1));  z= z + _;  end;  return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x;   x= r2r(x);                numeric fuzz min(5, digits() - 3)
     if abs(x)=pi  then return 0;              $x= x * x;       z= x;  _= x
       do k=2  by 2  until p=z;  p=z;  _= -_ * $x / (k*(k+1));  z= z + _;  end;   return z


decimals(4)
for n = 2 to 5
    see string(n) + " : "
    for root = 0 to n-1
        real = cos(2*3.14 * root / n)
        imag = sin(2*3.14 * root / n)
        see "" + real + " " + imag + "i"
        if root != n-1 see ", " ok
    next
    see nl
next


def roots_of_unity(n)
  (0...n).map {|k| Complex.polar(1, 2 * Math::PI * k / n)}
end

p roots_of_unity(3)


PI = 3.1415926535
FOR n = 2 TO 5
  PRINT n;":" ;
   FOR root = 0 TO n-1
     real = COS(2*PI * root / n)
     imag = SIN(2*PI * root / n)
     PRINT using("-##.#####",real);using("-##.#####",imag);"i";
     IF root <> n-1 then PRINT "," ;
  NEXT
  PRINT
NEXT


use num::Complex;
fn main() {
    let n = 8;
    let z = Complex::from_polar(&1.0,&(1.0*std::f64::consts::PI/n as f64));
    for k in 0..=n-1 {
        println!("e^{:2}πi/{} ≈ {:>14.3}",2*k,n,z.powf(2.0*k as f64));
    }
}


def rootsOfUnity(n:Int)=for(k <- 0 until n) yield Complex.fromPolar(1.0, 2*math.Pi*k/n)


(define pi (* 4 (atan 1)))

(do ((n 2 (+ n 1)))
    ((> n 10))
    (display n)
    (do ((k 0 (+ k 1)))
        ((>= k n))
        (display " ")
        (display (make-polar 1 (* 2 pi (/ k n)))))
    (newline))


$ include "seed7_05.s7i";
  include "float.s7i";
  include "complex.s7i";

const proc: main is func
  local
    var integer: n is 0;
    var integer: k is 0;
  begin
    for n range 2 to 10 do
      write(n lpad 2 <& ": ");
      for k range 0 to pred(n) do
        write(polar(1.0, 2.0 * PI * flt(k) / flt(n)) digits 4 lpad 15 <& " ");
      end for;
      writeln;
    end for;
  end func;


func roots_of_unity(n) {
    n.of { |j|
        exp(2i * Num.pi / n * j)
    }
}

roots_of_unity(5).each { |c|
    printf("%+.5f%+.5fi\n", c.reals)
}


function unity_roots(n) {
	// nth-root(1) = cos(2 * k * pi / n) + i * sin(2 * k * pi / n)
	return map(range(n), function(idx, k) {
		return {
			"re": cos(2 * k * M_PI / n),
			"im": sin(2 * k * M_PI / n)
		};
	});
}

// pirnt 6th roots of unity
foreach(unity_roots(6), function(k, v) {
	printf("%.3f%+.3fi\n", v.re, v.im);
});


package require Tcl 8.5
namespace import tcl::mathfunc::*

set pi 3.14159265
for {set n 2} {$n <= 10} {incr n} {
    set angle 0.0
    set row $n:
    for {set i 1} {$i <= $n} {incr i} {
        lappend row [format %5.4f%+5.4fi [cos $angle] [sin $angle]]
        set angle [expr {$angle + 2*$pi/$n}]
    }
    puts $row
}


#import std
#import nat
#import flo

roots = ~&htxPC+ c..mul:-0^*DlSiiDlStK9\iota [email protected]+ c..cpow/-1.+ div/1.+ float

#cast %jLL

tests = roots* <1,2,3,4,5,6>


Public Sub roots_of_unity()
    For n = 2 To 9
        Debug.Print n; "th roots of 1:"
        For r00t = 0 To n - 1
            Debug.Print "   Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
                Sin(2 * WorksheetFunction.Pi() * r00t / n))
        Next r00t
        Debug.Print
    Next n
End Sub


import "/complex" for Complex
import "/fmt" for Fmt

var roots = Fn.new { |n|
    var r = List.filled(n, null)
    for (i in 0...n) r[i] = Complex.fromPolar(1, 2 * Num.pi * i / n)
    return r
}

for (n in 2..5) {
    Fmt.print("$d roots of 1:", n)
    for (r in roots.call(n)) Fmt.print("  $17.14z", r)
}


with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8;
with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line;
with Ada.Containers.Vectors;

use  Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
use Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
use Aws, Ada.Strings.Unbounded, Input_Sources.Strings;
use Ada.Text_IO, Ada.Command_Line;

procedure Not_Coded is

   package Members_Vectors is new Ada.Containers.Vectors (
      Index_Type => Positive,
      Element_Type => Unbounded_String);
   use Members_Vectors;

   All_Tasks, Language_Members : Vector;

   procedure Get_Vector (Category : in String; Mbr_Vector : in out Vector) is
      Reader : Tree_Reader;
      Doc    : Document;
      List   : Node_List;
      N      : Node;
      A      : Attr;
      Page   : Aws.Response.Data;
      S      : Messages.Status_Code;

      -- Query has cmlimit value of 100, so we need 5 calls to
      -- retrieve the complete list of Programming_category
      Uri_Xml    : constant String  :=
         "http://rosettacode.org/mw/api.php?action=query&list=categorymembers"
         &
         "&format=xml&cmlimit=100&cmtitle=Category:";
      Cmcontinue : Unbounded_String := Null_Unbounded_String;
   begin
      loop
         Page :=
            Aws.Client.Get (Uri_Xml & Category & (To_String (Cmcontinue)));
         S    := Response.Status_Code (Page);
         if S not  in Messages.Success then
            Put_Line
              ("Unable to retrieve data => Status Code :" &
               Image (S) &
               " Reason :" &
               Reason_Phrase (S));
            raise Connection_Error;
         end if;
         declare
            Xml    : constant String := Message_Body (Page);
            Source : String_Input;
         begin
            Open
              (Xml'Unrestricted_Access,
               Unicode.Ces.Utf8.Utf8_Encoding,
               Source);
            Parse (Reader, Source);
            Close (Source);
         end;
         Doc  := Get_Tree (Reader);
         List := Get_Elements_By_Tag_Name (Doc, "cm");
         for Index in 1 .. Length (List) loop
            N := Item (List, Index - 1);
            A := Get_Named_Item (Attributes (N), "title");
            Members_Vectors.Append
              (Mbr_Vector,
               To_Unbounded_String (Value (A)));
         end loop;
         Free (List);
         List := Get_Elements_By_Tag_Name (Doc, "query-continue");
         if Length (List) = 0 then
            -- we are done
            Free (List);
            Free (Reader);
            exit;
         end if;
         N          := First_Child (Item (List, 0));
         A          := Get_Named_Item (Attributes (N), "cmcontinue");
         Cmcontinue :=
            To_Unbounded_String
              ("&cmcontinue=" & Aws.Url.Encode (Value (A)));
         Free (List);
         Free (Reader);
      end loop;
   end Get_Vector;

   procedure Quick_Diff (From : in out Vector; Substract : in Vector) is
      Beginning, Position : Extended_Index;
   begin
      -- take adavantage that both lists are already sorted
      Beginning := First_Index (From);
      for I in First_Index (Substract) .. Last_Index (Substract) loop
         Position :=
            Find_Index
              (Container => From,
               Item      => Members_Vectors.Element (Substract, I),
               Index     => Beginning);
         if not (Position = No_Index) then
            Delete (From, Position);
            Beginning := Position;
         end if;
      end loop;
   end Quick_Diff;

begin
   if Argument_Count = 0 then
      Put_Line ("Can't process : No language given!");
      return;
   else
      Get_Vector (Argument (1), Language_Members);
   end if;

   Get_Vector ("Programming_Tasks", All_Tasks);
   Quick_Diff (All_Tasks, Language_Members);

   for I in First_Index (All_Tasks) .. Last_Index (All_Tasks) loop
      Put_Line (To_String (Members_Vectors.Element (All_Tasks, I)));
   end loop;
   Put_Line
     ("Numbers of tasks not implemented :=" &
      Integer'Image (Last_Index ((All_Tasks))));
end Not_Coded;


#NoEnv ; do not resolve environment variables (speed)
#SingleInstance force ; allow only one instance
SetBatchLines, -1 ; set to highest script speed
SetControlDelay, 0 ; set delay between control commands to lowest

; additional label, for clarity only
AutoExec:
  Gui, Add, DDL, x10 y10 w270 r20 vlngStr ; add drop-down list
  Gui, Add, Button, x290 y10 gShowLng, Show Unimplemented ; add button
  Gui, Add, ListView, x10 y36 w400 h300 vcatLst gOnLV, Unimplemented ; add listview
  Gui, Add, StatusBar, vsbStr, ; add statusbar
  Gui, Show, , RosettaCode unimplemented list ; show the gui
  allLng := getList("lng") ; get a list of all available languages
  selectStr = Select language... ; set selection string for ddl
  GuiControl, , LngStr, |%selectStr%||%allLng% ; set the ddl to new contents
  SB_SetIcon("user32.dll", 5) ; change statusbar icon
  SB_SetText("Done loading languages. Select from menu.") ; change statusbar text
Return ; end of the autoexec section. Script waits for input.

; subroutine for language list in ddl update
ShowLng:
  Gui, Submit, NoHide ; refresh all gui variables
  If (lngStr != selectStr) ; if the current selected language is not the selection string
  {
    SB_SetIcon("user32.dll", 2) ; set statusbar icon to exclamation
    SB_SetText("Loading unimplemented tasks... Please wait.") ; set statusbar text
    allTsk := getList("tsk") ; get a list of all tasks
    allThis := getList(lngStr) ; get a list of all done tasks for this language
    Loop, Parse, allTsk, | ; parse the list of all tasks
    {
      If !InStr(allThis,A_LoopField) ; if the current task is not found in the list of all tasks
        notImpl .= A_LoopField . "|" ; add the current field to the notImpl variable
      allTskCnt := A_Index ; save the index for final count
    }
    StringTrimRight, notImpl, notImpl, 1 ; remove last delimiter
    LV_Delete() ; emty the listview
    GuiControl, -Redraw, catLst ; set the listview to not redraw while adding (speed)
    Loop, Parse, notImpl, | ; parse the list of not implemented tasks
    {
      LV_Add("", A_LoopField) ; add them to the listview, field by field
      notImplCnt := A_Index ; save the index for final count
    }
    GuiControl, +Redraw, catLst ; set the listview back to normal
    SB_SetIcon("user32.dll", 5) ; change statusbar icon to information
    SB_SetText("There are " . notImplCnt . " of " . allTskCnt
      . " tasks unimplemented. Double-click task to open in browser.") ; set the statusbar text
    notImpl = ; empty the notImpl variable
    notImplCnt = 0 ; set the count back to 0
  }
Return

; subroutine for action on listview
OnLV:
  If (A_GuiEvent = "DoubleClick") ; if the listview was double-clicked
  {
    LV_GetText(rowTxt, A_EventInfo) ; get the text of the clicked row
    rowTxt := Enc_Uri(rowTxt) ; uri-encode the text
    StringReplace, rowTxt, rowTxt, `%20, _, All ; replace all space-encodings with underscores
    Run % "http://rosettacode.org/wiki/" . rowTxt ; run the resulting link in the default browser
  }
Return

; generic function to gather list
getList(category)
{
  fileName = temp.xml ; set temp-file name
  If (category = "lng") ; if the category received is lng
  {
    category = Programming_Languages ; set the category
    fileName = lng.xml ; set temp-file name
    IfExist, %fileName% ; if the file already exists
    {
      FileGetTime, modTime, %fileName% ; get the last modified time
      EnvSub, modTime, %A_Now%, days ; get the difference between now and last modified time in days
      If (modTime < 3) ; if the result is less than 3
        Goto, GetFileNoDL ; go to function-internal subroutine to parse
    }
    SB_SetIcon("user32.dll", 2) ; set statusbar icon
    SB_SetText("Loading languages... Please wait.") ; set statusbar text
  }
  If (category = "tsk") ; if the category received is tsk
    category = Programming_Tasks ; set the category

  getFile: ; function-internal subroutine for getting a file and parsing it
    ; construct the url
    url := "http://www.rosettacode.org/w/api.php?action=query&list="
          . "categorymembers&cmtitle=Category:" . category
          . "&cmlimit=500&format=xml" . doContinue
    UrlDownloadToFile, %url%, %fileName% ; download the url

  getFileNoDL: ; function-internal subroutine for parsing a file
    FileRead, data, %fileName% ; read file into variable
    pos = 1 ; set while-loop counter
    rxp = title="(.*?)" ; set regular expression
    While (pos := RegExMatch(data, rxp, title, pos)) ; get the contents of the title fields one-by-one
    {
      If InStr(title1, "Category:") ; if the contents contain Category:
        StringTrimLeft, title1, title1, 9 ; remove that from the contents
      StringReplace, title1, title1, |, `|, All ; escape all containing delimiters
      title1 := Dec_XML(UTF82Ansi(title1)) ; convert to ansi first and then decode html entities
      allTitles .= title1 . "|" ; add this title to list
      pos++ ; increment counter
    }
    rxp = cmcontinue="(.*?)" ; set regular expression
    If RegExMatch(data, rxp, next) ; when found
    {
      doContinue = &cmcontinue=%next1% ; set continuation string to add to url
      Goto getFile ; go to function-internal subroutine to redownload and parse
    }
    StringTrimRight, allTitles, allTitles, 1 ; remove last delimiter from result
  Return allTitles ; return result
}

; function to convert html entities to ansi equivalents
Dec_XML(str)
{
   Loop
      If RegexMatch(str, "S)(&#(\d+);)", dec)
         StringReplace, str, str, %dec1%, % Chr(dec2), All
      Else If   RegexMatch(str, "Si)(&#x([\da-f]+);)", hex)
         StringReplace, str, str, %hex1%, % Chr("0x" . hex2), All
      Else
         Break
   StringReplace, str, str,  , %A_Space%, All
   StringReplace, str, str, ", ", All
   StringReplace, str, str, ', ', All
   StringReplace, str, str, <,   <, All
   StringReplace, str, str, >,   >, All
   StringReplace, str, str, &,  &, All
   return, str
}

; function to uri-encode input string
Enc_Uri(str)
{
   f = %A_FormatInteger%
   SetFormat, Integer, Hex
   If RegExMatch(str, "^\w+:/{0,2}", pr)
      StringTrimLeft, str, str, StrLen(pr)
   StringReplace, str, str, `%, `%25, All
   Loop
      If RegExMatch(str, "i)[^\w\.~%/:]", char)
         StringReplace, str, str, %char%, % "%" . SubStr(Asc(char),3), All
      Else Break
   SetFormat, Integer, %f%
   Return, pr . str
}

; function to convert unicode to ansi text
UTF82Ansi(zString)
{
  Ansi2Unicode(zString, wString, 65001)
  Unicode2Ansi(wString, sString, 0)
  Return sString
}

; helper function for unicode to ansi function
Ansi2Unicode(ByRef sString, ByRef wString, CP = 0)
{
  nSize := DllCall("MultiByteToWideChar", "Uint", CP
    , "Uint", 0, "Uint", &sString, "int", -1
    , "Uint", 0, "int", 0)
  VarSetCapacity(wString, nSize * 2)
  DllCall("MultiByteToWideChar"
    , "Uint", CP, "Uint", 0, "Uint", &sString, "int", -1
    , "Uint", &wString, "int", nSize)
}

; helper function for unicode to ansi function
Unicode2Ansi(ByRef wString, ByRef sString, CP = 0)
{
  nSize := DllCall("WideCharToMultiByte"
    , "Uint", CP, "Uint", 0, "Uint", &wString, "int", -1
    , "Uint", 0, "int", 0, "Uint", 0, "Uint", 0)
  VarSetCapacity(sString, nSize)
  DllCall("WideCharToMultiByte"
    , "Uint", CP, "Uint", 0, "Uint", &wString, "int", -1
    , "str", sString, "int", nSize, "Uint", 0, "Uint", 0)
}

; subroutine called when user closes the gui
GuiClose:
  ExitApp ; exit the script
Return


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Net;

class Program {
    static List<string> GetTitlesFromCategory(string category) {
        string searchQueryFormat = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:{0}&format=json{1}";
        List<string> results = new List<string>();
        string cmcontinue = string.Empty;

        do {
            string cmContinueKeyValue;

            //append continue variable as needed
            if (cmcontinue.Length > 0)
                cmContinueKeyValue = String.Format("&cmcontinue={0}", cmcontinue);
            else
                cmContinueKeyValue = String.Empty;

            //execute query
            string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);
            string content = new WebClient().DownloadString(query);

            results.AddRange(new Regex("\"title\":\"(.+?)\"").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));

            //detect if more results are available
            cmcontinue = Regex.Match(content, @"{""cmcontinue"":""([^""]+)""}", RegexOptions.IgnoreCase).Groups["1"].Value;
        } while (cmcontinue.Length > 0);

        return results;
    }

    static string[] GetUnimplementedTasksFromLanguage(string language) {
        List<string> alltasks = GetTitlesFromCategory("Programming_Tasks");
        List<string> lang = GetTitlesFromCategory(language);

        return alltasks.Where(x => !lang.Contains(x)).ToArray();
    }

    static void Main(string[] args) {
        string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);

        foreach (string i in unimpl) Console.WriteLine(i);
    }
}


(require
  '[clojure.xml :as xml]
  '[clojure.set :as set]
  '[clojure.string :as string])
(import '[java.net URLEncoder])


#!/usr/bin/env rune

# NOTE: This program will not work in released E, because TermL is an
# imperfect superset of JSON in that version: it does not accept "\/".
# If you build E from the latest source in SVN then it will work.
#
# Usage: rosettacode-cat-subtract.e [<lang e>]
#
# Prints a list of tasks which have not been completed in the language.
# If unspecified, the default language is E.

pragma.syntax("0.9")
pragma.enable("accumulator")

def termParser := <import:org.quasiliteral.term.makeTermParser>
def jURLEncoder := <unsafe:java.net.makeURLEncoder>

def urlEncode(text) {
  return jURLEncoder.encode(text, "UTF-8")
}

/** Convert JSON-as-term-tree to the corresponding natural E data structures. */
def jsonTermToData(term) {
    switch (term) {

        # JSON object to E map
        match term`{@assocs*}` {
            return accum [].asMap() for term`@{key :String}: @valueJson` in assocs {
                _.with(key, jsonTermToData(valueJson))
            }
        }

        # JSON array to E list
        match term`[@elements*]` {
            return accum [] for elem in elements { _.with(jsonTermToData(elem)) }
        }

        # Literals just need to be coerced
        match lit :any[String, int, float64] {
            return lit
        }

        # Doesn't support true/false/null, but we don't need that for this application.
    }
}

def fetchCategoryAccum(name, membersSoFar :Set, extraArgs) {
    stderr.println(`Fetching Category:$name $extraArgs...`)

    def categoryAPIResource := <http>[`//rosettacode.org/w/api.php?` +
        `action=query&list=categorymembers&cmtitle=Category:${urlEncode(name)}&` +
        `format=json&cmlimit=500&cmprop=title$extraArgs`]

    def members :=
      when (def responseJSON := categoryAPIResource <- getTwine()) -> {
        # stderr.println(`Fetched Category:$name $extraArgs, parsing...`)
        def response := jsonTermToData(termParser(responseJSON))

        # stderr.println(`Parsed Category:$name $extraArgs response, extracting data...`)
        def [
          "query" => ["categorymembers" => records],
          "query-continue" => continueData := null
        ] := response
        def members := accum membersSoFar for record in records { _.with(record["title"]) }

        switch (continueData) {
          match ==null {
            stderr.println(`Got all ${members.size()} for Category:$name.`)
            members
          }
          match ["categorymembers" => ["cmcontinue" => continueParam]] {
            stderr.println(`Fetched ${members.size()} members for Category:$name...`)
            fetchCategoryAccum(name, members, `&cmcontinue=` + urlEncode(continueParam))
          }
        }
    } catch p { throw(p) }

    return members
}

def fetchCategory(name) {
  return fetchCategoryAccum(name, [].asSet(), "")
}

# Interpret program arguments
def lang := switch (interp.getArgs()) {
  match [lang] { lang }
  match [] { "E" }
}

# Fetch categories
when (def allTasks := fetchCategory("Programming_Tasks"),
      def doneTasks := fetchCategory(lang),
      def omitTasks := fetchCategory(lang + "/Omit")
     ) -> {

    # Compute difference and report
    def notDoneTasks := allTasks &! (doneTasks | omitTasks)
    println()
    println("\n".rjoin(notDoneTasks.getElements().sort()))

} catch p {
    # Whoops, something went wrong
    stderr.println(`$p${p.eStack()}`)
}


-module( find_unimplemented_tasks ).
-include_lib( "xmerl/include/xmerl.hrl" ).

-export( [init_http/0, per_language/1, rosetta_code_list_of/1] ).

init_http() ->
	application:start( inets ).

per_language( Language ) ->
	ok = init_http(),
	Tasks = rosetta_code_list_of( "Programming_Tasks" ),
	Uninplemented = Tasks -- rosetta_code_list_of( Language ),
	io:fwrite( "Unimplemented total: ~p~n", [erlang:length(Uninplemented)] ),
	[io:fwrite("~p~n", [X]) || X <- Uninplemented].

rosetta_code_list_of( Category ) ->
	URL = "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmlimit=500&format=xml&cmtitle=Category:"
	++ Category,
	title_contents( URL, "", [] ).

title_contents( URL, Continue, Acc ) ->
	{ok, {{_HTTP,200,"OK"}, _Headers, Body}} = httpc:request( URL ++ Continue ),
	{XML, _} = xmerl_scan:string( Body ),
	News = xml_selection( "title", XML ),
	New_continue = title_contents_url_continue( xml_selection("cmcontinue", XML) ),
	title_contents_continue( URL, New_continue, Acc ++ News ).

title_contents_continue( _URL, "", Acc ) -> Acc;
title_contents_continue( URL, Continue, Acc ) -> title_contents( URL, Continue, Acc ).

title_contents_url_continue( [] ) -> "";
title_contents_url_continue( [Continue | _] ) -> "&cmcontinue=" ++ Continue.

xml_selection( Selection, XML ) ->
	[lists:map( fun xml_8211/1, X) || #xmlAttribute{value=X} <- xmerl_xpath:string("//@" ++ Selection, XML)].

xml_8211( 8211 ) -> $-;
xml_8211( 924 ) -> $\s;
xml_8211( 1050 ) -> $\s;
xml_8211( 1052 ) -> $\s;
xml_8211( Character ) -> Character.


package main

import (
    "encoding/xml"
    "fmt"
    "io"
    "net/http"
    "net/url"
)

const language = "Go"

var baseQuery = "http://rosettacode.org/mw/api.php?action=query" +
    "&format=xml&list=categorymembers&cmlimit=100"

func req(u string, foundCm func(string)) string {
    resp, err := http.Get(u)
    if err != nil {
        fmt.Println(err) // connection or request fail
        return ""
    }
    defer resp.Body.Close()
    for p := xml.NewDecoder(resp.Body); ; {
        t, err := p.RawToken()
        switch s, ok := t.(xml.StartElement); {
        case err == io.EOF:
            return ""
        case err != nil:
            fmt.Println(err)
            return ""
        case !ok:
            continue
        case s.Name.Local == "cm":
            for _, a := range s.Attr {
                if a.Name.Local == "title" {
                    foundCm(a.Value)
                }
            }
        case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
            s.Attr[0].Name.Local == "cmcontinue":
            return url.QueryEscape(s.Attr[0].Value)
        }
    }
    return ""
}

func main() {
    // get language members, store in a map
    langMap := make(map[string]bool)
    storeLang := func(cm string) { langMap[cm] = true }
    languageQuery := baseQuery + "&cmtitle=Category:" + language
    continueAt := req(languageQuery, storeLang)
    for continueAt > "" {
        continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
    }

    // a quick check to avoid long output
    if len(langMap) == 0 {
        fmt.Println("no tasks implemented for", language)
        return
    }

    // get tasks, print as we go along
    printUnImp := func(cm string) {
        if !langMap[cm] {
            fmt.Println(cm)
        }
    }
    taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks"
    continueAt = req(taskQuery, printUnImp)
    for continueAt > "" {
        continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp)
    }
}


import Network.Browser
import Network.HTTP
import Network.URI
import Data.List
import Data.Maybe
import Text.XML.Light
import Control.Arrow
import Data.Char

getRespons url = do
  rsp <- Network.Browser.browse $ do
    setAllowRedirects True
    setOutHandler $ const (return ())   -- quiet
    request $ getRequest url
  return $ rspBody $ snd rsp

replaceWithSpace c = (\x -> if c==x then ' ' else x)

encl = chr 34

unimpTasks lang = do
  allTasks <- getRespons "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
  impl <-  getRespons ( "http://rosettacode.org/json/isb/" ++ lang ++ ".json")
  let langxx = map (map(replaceWithSpace '_')) $ filter (/=",") $ words $ map (replaceWithSpace encl ) $ init $ drop 1 impl
      xml = onlyElems $ parseXML allTasks
      allxx = concatMap (map (fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xml
  mapM_ putStrLn $ sort $ allxx \\ langxx


$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500"
$define RCTASK  "http://rosettacode.org/mw/index.php?action=raw&title="
$define RCUA    "User-Agent: Unicon Rosetta 0.1"
$define RCXUA   "X-Unicon: http://unicon.org/"
$define TASKTOT "* Total Tasks *"
$define TOTTOT  "* Total Headers*"

link strings
link hexcvt

procedure main(A)   # simple single threaded read all at once implementation
    lang := \A[1] | "Unicon"
    write("Unimplemented tasks for ",lang," as of ",&date)
    every task := taskNames() do {
       if lang == languages(task) then next
       write(task)
       }
end

# Generate task names
procedure taskNames()
    continue := ""
    while \(txt := ReadURL(RCINDEX||continue)) do {
        txt ? {
            while tab(find("<cm ") & find(s :="title=\"")+*s) do
                suspend tab(find("\""))\1
            if tab(find("cmcontinue=")) then {
                continue := "&"||tab(upto(' \t'))
                }
            else break
            }
        }
end

# Generate language headers in a task
procedure languages(task)
    static WS
    initial WS := ' \t'
    page := ReadURL(RCTASK||CleanURI(task))
    page ? while (tab(find("\n==")),tab(many(WS))|"",tab(find("{{"))) do {
               header := tab(find("=="))
               header ? {
                   while tab(find("{{header|")) do {
                       suspend 2(="{{header|",tab(find("}}")))\1
                       }
                   }
               }
end

procedure CleanURI(u)                  #: clean up a URI
    static tr,dxml                     # xml & http translation
    initial {
       tr := table()
       every c := !string(~(&digits++&letters++'-_.!~*()/\'`')) do
          tr[c] := "%"||hexstring(ord(c),2)
       every /tr[c := !string(&cset)] := c
       tr[" "] := "_"                                      # wiki convention
       every push(dxml := [],"&#"||right(ord(c := !"&<>'\""),3,"0")||";",c)
       }

    dxml[1] := u                       # insert URI as 1st arg
    u := replacem!dxml                 # de-xml it
    every (c := "") ||:= tr[!u]        # reencode everything
    c := replace(c,"%3E","'")          # Hack to put single quotes back in
    c := replace(c,"%26quot%3B","\"")  # Hack to put double quotes back in
    return c
end

procedure ReadURL(url)                 #: read URL into string
    page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url)
    text := ""
    if page["Status-Code"] < 300 then while text ||:= reads(page,-1)
    else write(&errout,image(url),": ",
                       page["Status-Code"]," ",page["Reason-Phrase"])
    close(page)
    return text
end


require 'strings web/gethttp'

findUnimpTasks=: ('Programming_Tasks' -.&getCategoryMembers ,&'/Omit') ([ #~ [email protected]) getCategoryMembers

getTagContents=: dyad define
  'starttag endtag'=. x
  ('\' -.~ endtag&taketo)&.>@(starttag&E. <@((#starttag)&}.);.1 ]) y
)

NB. RosettaCode Utilities
parseTitles=: ('"title":"';'"')&getTagContents
parseCMcontinue=:('"cmcontinue":"';'"')&getTagContents
getCMcontquery=: ('&cmcontinue=' , urlencode)^:(0 < #)@>@parseCMcontinue

getCategoryMembers=: monad define
  buildqry=. 'action=query&list=categorymembers&cmtitle=Category:' , ,&'&cmlimit=500&format=json'
  url=.'http://www.rosettacode.org/w/api.php'
  uri=. url ,'?', buildqry urlencode y
  catmbrs=. qrycont=. ''
  whilst. #qrycont=. getCMcontquery jsondat do.
    jsondat=. gethttp uri , qrycont
    catmbrs=. catmbrs, parseTitles jsondat
  end.
  catmbrs
)


(function (strXPath) {
  var xr = document.evaluate(
      strXPath,
      document,
      null, 0, 0
    ),

    oNode = xr.iterateNext(),
    lstTasks = [];

  while (oNode) {
    lstTasks.push(oNode.title);
    oNode = xr.iterateNext();
  }

  return [
    lstTasks.length + " items found in " + document.title,
    ''
  ].concat(lstTasks).join('\n')

})(
  '//*[@id="mw-content-text"]/div[2]/table/tbody/tr/td/ul/li/a'
);


using HTTP, JSON

const baseuri = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:"
const enduri = "&cmlimit=500&format=json"
queries(x) = baseuri * HTTP.Strings.escapehtml(x) * enduri

function getimplemented(query)
    tasksdone = Vector{String}()
    request = query
    while (resp = HTTP.request("GET", request)).status == 200
        fromjson = JSON.parse(String(resp.body))
        for d in fromjson["query"]["categorymembers"]
            if haskey(d, "title")
                push!(tasksdone, d["title"])
            end
        end
        if haskey(fromjson, "continue")
            cmcont, cont = fromjson["continue"]["cmcontinue"], fromjson["continue"]["continue"]
            request = query * "&cmcontinue=$cmcont&continue=$cont"
        else
            break
        end
    end
    tasksdone
end

alltasks = getimplemented(queries("Programming_Tasks"))

showunimp(x) = (println("\nUnimplemented in $x:"); for t in setdiff(alltasks,
    getimplemented(queries(x))) println(t) end)

showunimp("Julia")
showunimp("C++")


local requests = require('requests')
local lang = arg[1]

local function merge_tables(existing, from_req)
  local result = existing

  for _, v in ipairs(from_req) do
      result[v.title] = true
  end

  return result
end

local function get_task_list(category)
  local url = 'http://www.rosettacode.org/mw/api.php'
  local query = {
    action = 'query',
    list = 'categorymembers',
    cmtitle = string.format('Category:%s', category),
    cmlimit = 500,
    cmtype = 'page',
    format = 'json'
  }
  local categories = {}

  while true do
    local resp = assert(requests.get({ url, params = query }).json())

    categories = merge_tables(categories, resp.query.categorymembers)

    if resp.continue then
      query.cmcontinue = resp.continue.cmcontinue
    else
      break
    end
  end

  return categories
end

local function get_open_tasks(lang)
  if not lang then error('Language missing!') end
  local all_tasks = get_task_list('Programming_Tasks')
  local lang_tasks = get_task_list(lang)
  local task_list = {}

  for t, _ in pairs(all_tasks) do
    if not lang_tasks[t] then
      table.insert(task_list, t)
    end
  end

  table.sort(task_list)
  return task_list
end

local open_tasks = get_open_tasks(lang)

io.write(string.format('%s has %d unimplemented programming tasks: \n', lang, #open_tasks))
for _, t in ipairs(open_tasks) do
  io.write(string.format('  %s\n', t))
end


#Example with the Maple Language
lan := "Maple":
x := URL:-Get(cat("http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_", StringTools:-SubstituteAll(lan, " ", "_")), output = content):
x := StringTools:-StringSplit(x, "
Not implemented")[2]:
x := StringTools:-StringSplit(x, "Draft tasks without implementation")[1]:
x := StringTools:-StringSplit(x,"
<a href=\"/wiki/")[2..]:
for problem in x do
	printf("%s\n", StringTools:-SubstituteAll(StringTools:-Decode(StringTools:-StringSplit(problem, "\" title=")[1], 'percent'), "_", " "));
end do:


ClearAll[ImportAll]
ImportAll[lang_String] :=
 Module[{data, continue, cmcontinue, extra, xml, next},
  data = {};
  continue = True;
  cmcontinue = "";
  While[continue,
   extra = If[cmcontinue =!= "", "&cmcontinue=" <> cmcontinue, ""];
   xml = Import["http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:" <> lang <> "&cmlimit=500&format=xml" <> extra, "XML"];
   AppendTo[data, Cases[xml, XMLElement["cm", _, {}], \[Infinity]]];
   next = Flatten[Cases[xml, {"cmcontinue" -> _}, \[Infinity]]];
   If[Length[next] > 0,
    next = First[next];
    cmcontinue = "cmcontinue" /. next;
    ,
    continue = False;
    ];
   ];
  Cases[Flatten[data], HoldPattern["title" -> x_] :> x, \[Infinity]]
  ]
Complement[ImportAll["Programming_Tasks"], ImportAll["Mathematica"]]


import httpclient, strutils, xmltree, xmlparser, cgi, os

proc findrc(category: string): seq[string] =

  var
    name = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:$#&cmlimit=500&format=xml" % encodeUrl(category)
    cmcontinue = ""
    client = newHttpClient()

  while true:
    var x = client.getContent(name & cmcontinue).parseXml()
    for node in x.findAll("cm"):
      result.add node.attr("title")

    cmcontinue.setLen(0)
    for node in x.findAll("categorymembers"):
      let u = node.attr("cmcontinue")
      if u.len != 0: cmcontinue = u.encodeUrl()

    if cmcontinue.len > 0: cmcontinue = "&cmcontinue=" & cmcontinue
    else: break

proc chooselang(): string =
  if paramCount() < 1: "Nim" else: paramStr(1)

let alltasks = findrc("Programming_Tasks")
let lang = chooselang()
let langTasks = lang.findrc()
echo "Unimplemented tasks for language ", lang, ':'
for task in alltasks:
  if task notin langTasks:
    echo "  ", task


declare
  [HTTPClient] = {Link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
  [XMLParser] = {Link ['x-oz://system/xml/Parser.ozf']}

  fun {FindUnimplementedTasks Language}
     AllTasks = {FindCategory "Programming Tasks"}
     LangTasks = {FindCategory Language}
  in
     {ListDiff AllTasks LangTasks}
  end

  fun {FindCategory Cat}
     CatUrl = "http://www.rosettacode.org/mw/api.php?action=query"
     #"&list=categorymembers"
     #"&cmtitle=Category:"#{PercentEncode Cat}
     #"&cmlimit=500&format=xml"

     fun {Loop CMContinue}
        [_ Doc] = {Parse {GetPage CatUrl#CMContinue}}
        Titles = {XPath Doc
                  [api query categorymembers cm {Attribute title}]}
     in
        case {XPath Doc
              [api 'query-continue' categorymembers {Attribute cmcontinue}]}
        of nil then Titles
        [] [NewCMContinueAtom] then
           NewCMContinue = {PercentEncode {Atom.toString NewCMContinueAtom}}
        in
           {Append Titles
            {Loop "&cmcontinue="#NewCMContinue}}
        end
     end
  in
     {Loop nil}
  end

  %% XPath emulation
  fun {XPath Doc Path}
     P|Pr = Path
  in
     Doc.name = P %% assert
     {FoldL Pr XPathStep [Doc]}
  end

  Nothing = {NewName}
  fun {NotNothing X} X \= Nothing end

  fun {XPathStep Elements P}
     if {Atom.is P} then
        {FilteredChildren Elements P}
     elseif {Procedure.is P} then
        {Filter {Map Elements P} NotNothing}
     end
  end

  %% A flat list of all Type-children of all Elements.
  fun {FilteredChildren Elements Type}
     {Flatten
      {Map Elements
       fun {$ E}
          {Filter E.children
           fun {$ X}
              case X of element(name:!Type ...) then true
              else false
              end
           end}
       end}}
  end

  fun {Attribute Attr}
     fun {$ Element}
        case {Filter Element.attributes fun {$ A} A.name == Attr end}
        of [A] then A.value
        else Nothing
        end
     end
  end

  %% GetPage
  Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)}
  fun {GetPage RawUrl}
     Url = {VirtualString.toString RawUrl}
     OutParams
  in
     {Client getService(Url ?OutParams ?_)}
     OutParams.sOut
  end

  fun {PercentEncode Xs}
     case Xs of nil then nil
     [] X|Xr then
        if {Char.isDigit X} orelse {Member X [&- &_ &.  &~]}
           orelse X >= &a andthen X =< &z
           orelse X >= &z andthen X =< &Z then
           X|{PercentEncode Xr}
        else
           {Append &%|{ToHex2 X} {PercentEncode Xr}}
        end
     end
  end

  fun {ToHex2 X}
     [{ToHex1 X div 16} {ToHex1 X mod 16}]
  end

  fun {ToHex1 X}
     if X >= 0 andthen X =< 9 then &0 + X
     elseif X >= 10 andthen X =< 15 then &A + X - 10
     end
  end

  %% Parse
  local
     Parser = {New XMLParser.parser init}
  in
     fun {Parse Xs} {Parser parseVS(Xs $)} end
  end

  fun {ListDiff Xs Ys}
     {FoldL Ys List.subtract Xs}
  end
in
  %% show tasks not implemented in Oz
  {ForAll {FindUnimplementedTasks "Oz"} System.showInfo}


use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->agent('');

sub enc { join '', map {sprintf '%%%02x', ord} split //, shift }
sub get { $ua->request( HTTP::Request->new( GET => shift))->content }

sub tasks {
    my($category) = shift;
    my $fmt = 'http://www.rosettacode.org/mw/api.php?' .
              'action=query&generator=categorymembers&gcmtitle=Category:%s&gcmlimit=500&format=json&rawcontinue=';
    my @tasks;
    my $json = get(sprintf $fmt, $category);
    while (1) {
        push @tasks, $json =~ /"title":"(.+?)"\}/g;
        $json =~ /"gcmcontinue":"(.+?)"\}/ or last;
        $json = get(sprintf $fmt . '&gcmcontinue=%s', $category, enc $1);
    }
    @tasks;
}

my %language = map {$_, 1} tasks shift || 'perl';
$language{$_} or print "$_\n" foreach tasks('Programming_Tasks'), tasks('Draft_Programming_Tasks');


-- demo\rosetta\Find_unimplemented_tasks.exw
without js -- (libcurl, file i/o, peek, progress..)
constant language = "Phix",
--       language = "Go",
--       language = "Julia",
--       language = "Python",
--       language = "Wren",
         base_query = "http://rosettacode.org/mw/api.php?action=query"&
                      "&format=xml&list=categorymembers&cmlimit=100"

include builtins\libcurl.e
atom curl = NULL
atom pErrorBuffer
include builtins\xml.e

function req(string url, integer rid)
    if curl=NULL then
        curl_global_init()
        curl = curl_easy_init()
        pErrorBuffer = allocate(CURL_ERROR_SIZE)
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pErrorBuffer)
    end if
    curl_easy_setopt(curl, CURLOPT_URL, url)
    object res = curl_easy_perform_ex(curl)
    if integer(res) then
        string error = sprintf("%d [%s]",{res,peek_string(pErrorBuffer)})
        crash("Download error: %s\n",{error})
    end if
    if not string(res) then ?9/0 end if
    object xml = xml_parse(res)[XML_CONTENTS]
    res = xml_get_nodes(xml,"continue")
    res = iff(res=={}?"":xml_get_attribute(res[1],"cmcontinue"))
    xml = xml_get_nodes(xml,"query")[1]
    xml = xml_get_nodes(xml,"categorymembers")[1]
    xml = xml_get_nodes(xml,"cm")
    for i=1 to length(xml) do
        call_proc(rid,{xml_get_attribute(xml[i],"title")})
    end for
    return res
end function

function html_clean(string ri)
    ri = substitute(ri,`"`,`"`)
    ri = substitute(ri,`'`,`'`)
    ri = substitute(ri,"\xE2\x80\x99","'")
    ri = substitute(ri,"\xC3\xB6","o")
    ri = substitute(ri,"%3A",":")
    ri = substitute(ri,"%E2%80%93","-")
    ri = substitute(ri,"%E2%80%99","'")
    ri = substitute(ri,"%27","'")
    ri = substitute(ri,"%2B","+")
    ri = substitute(ri,"%C3%A8","e")
    ri = substitute(ri,"%C3%A9","e")
    ri = substitute(ri,"%C3%B6","o")
    ri = substitute(ri,"%C5%91","o")
    ri = substitute(ri,"%22",`"`)
    ri = substitute(ri,"%2A","*")
    return ri
end function

sequence titles = {}
procedure store_title(string title)
    titles = append(titles,title)
end procedure

integer unimplemented_count = 0,
        task_count = 0
procedure print_unimplemented(string title)
    if not find(title,titles) then
        title = html_clean(title)
        printf(1,"%s\n",{title})
        unimplemented_count += 1
    end if
    task_count += 1
end procedure

procedure main()
    printf(1,"Loading implemented tasks list...\n")
    -- get and store task itles
    string lang_query := base_query & "&cmtitle=Category:" & language,
           continue_at := req(lang_query, store_title)
    while continue_at!="" do
        continue_at = req(lang_query&"&cmcontinue="&continue_at, store_title)
    end while

    -- a quick check to avoid long output
    if length(titles)==0 then
        printf(1,"no tasks implemented for %s\n", {language})
        return
    end if

    -- get tasks, print as we go along
    printf(1,"Tasks:\n")
    string task_query := base_query & "&cmtitle=Category:Programming_Tasks"
    continue_at = req(task_query, print_unimplemented)
    while continue_at!="" do
        continue_at = req(task_query&"&cmcontinue="&continue_at, print_unimplemented)
    end while
    printf(1,"%d unimplemented tasks found for %s.\n",{unimplemented_count,language})

    integer full_tasks = unimplemented_count
    printf(1,"Draft tasks:\n")
    task_query := base_query & "&cmtitle=Category:Draft_Programming_Tasks"
    continue_at = req(task_query, print_unimplemented)
    while continue_at!="" do
        continue_at = req(task_query&"&cmcontinue="&continue_at, print_unimplemented)
    end while
    integer draft_tasks = unimplemented_count-full_tasks
    printf(1,"%d unimplemented draft tasks found for %s.\n",{draft_tasks,language})

    printf(1,"%d unimplemented tasks in total found for %s (out of %d).\n",{unimplemented_count,language,task_count})

end procedure
main()


(load "@lib/http.l" "@lib/xm.l")

(de rosettaCategory (Cat)
   (let (Cont NIL  Xml)
      (make
         (loop
            (client "rosettacode.org" 80
               (pack
                  "mw/api.php?action=query&list=categorymembers&cmtitle=Category:"
                  Cat
                  "&cmlimit=200&format=xml"
                  Cont )
               (while (line))
               (setq Xml (and (xml?) (xml))) )
            (NIL Xml)
            (for M (body Xml 'query 'categorymembers)
               (link (attr M 'title)) )
            (NIL (attr Xml 'query-continue' categorymembers 'cmcontinue))
            (setq Cont (pack "&cmcontinue=" @)) ) ) ) )

(de unimplemented (Task)
   (diff
      (rosettaCategory "Programming_Tasks")
      (rosettaCategory Task) ) )


function Find-UnimplementedTask
{
    [CmdletBinding()]
    [OutputType([string[]])]
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [string]
        $Language
    )

    $url = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_$Language"
    $web = Invoke-WebRequest $url
    $unimplemented = 1

    [string[]](($web.AllElements |
        Where-Object {$_.class -eq "mw-content-ltr"})[$unimplemented].outerText -split "`r`n" |
        Select-String -Pattern "[^0-9A-Z]$" -CaseSensitive)
}


"""
Given the name of a language on Rosetta Code,
finds all tasks which are not implemented in that language.
"""
from operator import attrgetter
from typing import Iterator

import mwclient

URL = 'www.rosettacode.org'
API_PATH = '/mw/'

def unimplemented_tasks(language: str,
                        *,
                        url: str,
                        api_path: str) -> Iterator[str]:
    """Yields all unimplemented tasks for a specified language"""
    site = mwclient.Site(url, path=api_path)
    all_tasks = site.categories['Programming Tasks']
    language_tasks = site.categories[language]
    name = attrgetter('name')
    all_tasks_names = map(name, all_tasks)
    language_tasks_names = set(map(name, language_tasks))
    for task in all_tasks_names:
        if task not in language_tasks_names:
            yield task

if __name__ == '__main__':
    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)
    print(*tasks, sep='\n')


library(XML)
find.unimplemented.tasks <- function(lang="R"){
	PT <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml",sep="") )
	PT.nodes <- getNodeSet(PT,"//cm")
	PT.titles = as.character( sapply(PT.nodes, xmlGetAttr, "title") )
	language <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:",
	lang, "&cmlimit=500&format=xml",sep="") )
	lang.nodes <- getNodeSet(language,"//cm")
	lang.titles = as.character( sapply(lang.nodes, xmlGetAttr, "title") )
	unimplemented <- setdiff(PT.titles, lang.titles)
	unimplemented
}
# Usage
find.unimplemented.tasks(lang="Python")
langs <- c("R","python","perl")
sapply(langs, find.unimplemented.tasks) # fetching data for multiple languages


#lang racket

(require net/url net/uri-codec json (only-in racket/dict [dict-ref ref]))

(define (RC-get verb params)
  ((compose1 get-pure-port string->url format)
   "http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params)))

(define (get-category catname)
  (let loop ([c #f])
    (define t
      ((compose1 read-json RC-get) 'api
       `([action . "query"] [format . "json"]
         [list . "categorymembers"] [cmtitle . ,(format "Category:~a" catname)]
         [cmcontinue . ,(and c (ref c 'cmcontinue))] [cmlimit . "500"])))
    (define (c-m key) (ref (ref t key '()) 'categorymembers #f))
    (append (for/list ([page (c-m 'query)]) (ref page 'title))
            (cond [(c-m 'query-continue) => loop] [else '()]))))

;; The above is the required "library" code, same as the "Rosetta
;; Code/Count" entry

(define (show-unimplemented lang)
  (for-each displayln (remove* (get-category lang)
                               (get-category 'Programming_Tasks))))

(show-unimplemented 'Racket) ; see all of the Racket entries


use HTTP::UserAgent;
use URI::Escape;
use JSON::Fast;
use Sort::Naturally;

unit sub MAIN( Str :$lang = 'Raku' );

my $client = HTTP::UserAgent.new;
my $url = 'http://rosettacode.org/mw';

my @total;
my @impl;

@total.append: .&get-cat for 'Programming_Tasks', 'Draft_Programming_Tasks';
@impl = get-cat $lang;

say "Unimplemented tasks in $lang:";
.say for (@total (-) @impl).keys.sort: &naturally;

sub get-cat ($category) {
    flat mediawiki-query(
        $url, 'pages',
        :generator<categorymembers>,
        :gcmtitle("Category:$category"),
        :gcmlimit<350>,
        :rawcontinue(),
        :prop<title>
    ).map({ .<title> });
}

sub mediawiki-query ($site, $type, *%query) {
    my $url = "$site/api.php?" ~ uri-query-string(
        :action<query>, :format<json>, :formatversion<2>, |%query);
    my $continue = '';

    gather loop {
        my $response = $client.get("$url&$continue");
        my $data = from-json($response.content);
        take $_ for $data.<query>.{$type}.values;
        $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);
    }
}

sub uri-query-string (*%fields) { %fields.map({ "{.key}={uri-escape .value}" }).join("&") }


# Project: Rosetta Code/Find unimplemented tasks

load "stdlib.ring"
ros= download("http://rosettacode.org/wiki/Category:Programming_Tasks")
lang = "Ring"
pos = 1
num = 0
totalros = 0
rosname = ""
rostitle = ""
see "Tasks not implemented in " + lang + " language:" + nl
for n = 1 to len(ros)
        nr = searchstring(ros,'
',sn)
       nr3 = searchstring(ros,"
",sn)
       rosname = substr(ros,nr2+2,nr3-nr2-2)
       return sn

func searchtitle(sn)
        st = searchstring(ros,"title=",sn)
        rostitle = substr(ros,sn+19,st-sn-21)
        rostitle = "rosettacode.org/wiki/" + rostitle
        rostitle = download(rostitle)
        s = substr(rostitle,lang)
        if s = 0
           num = num + 1
           totalros = totalros + 1
           see "" + num + ". " + rosname + nl
        ok
        return sn

func count(cstring,dstring)
       sum = 0
       while substr(cstring,dstring) > 0
               sum = sum + 1
              cstring = substr(cstring,substr(cstring,dstring)+len(string(sum)))
       end
       return sum


require 'rosettacode'
require 'time'

module RosettaCode
  def self.get_unimplemented(lang)
    programming_tasks = []
    category_members("Programming_Tasks") {|task| programming_tasks << task}

    lang_tasks = []
    category_members(lang) {|task| lang_tasks << task}

    lang_tasks_omit = []
    category_members("#{lang}/Omit") {|task| lang_tasks_omit << task}

    [programming_tasks - lang_tasks, lang_tasks_omit]
  end

  def self.created_time(title)
    url = get_api_url({
      "action" => "query",
      "titles" => title,
      "format" => "xml",
      "rvlimit" => 500,
      "prop" => "revisions",
      "rvprop" => "timestamp"
    })
    doc = REXML::Document.new open(url)
    REXML::XPath.each(doc, "//rev").collect do |node|
      Time.parse( node.attribute("timestamp").value )
    end.min
  end

end

puts Time.now
lang = ARGV[0] || "Ruby"
unimplemented, omitted = RosettaCode.get_unimplemented(lang)
unimplemented.collect {|title| [title, RosettaCode.created_time(title)]} .
              sort_by {|e| e[1]} .
              each do |title, date|
                puts "%s %6s %s" % [
                  date.strftime("%Y-%m-%d"),
                  omitted.include?(title) ? "[omit]" : "" ,
                  title
                ]
              end


WordWrap$ = "style='white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word'"
a$	= httpGet$("http://rosettacode.org/wiki/Category:Programming_Languages")
a$	= word$(a$,2,"mw-subcategories")
a$	= word$(a$,1,"
")
i	= instr(a$,"/wiki/Category:")
html "   Select language from list
"
html "<SELECT name='lang'>"
while i <> 0
  j	= instr(a$,""" title=""Category:",i)
  lang$	= mid$(a$,i+15,j-i-15)
  k	= instr(a$,""">",j + 18)
  langName$ = mid$(a$,j + 18,k-(j+18))
  count	= count + 1
  html  "<option value='";lang$;"'>";langName$;"</option>"
  i	= instr(a$,"/wiki/Category:",k)
wend
html "</select>"
html "
Number of Languages:";count;"
        "
button #go,"GO", [go]
html "        "
button #ex, "Exit", [exit]
wait

[go]
cls
lang$	= #request get$("lang")
h$	= "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_";lang$
a$	= httpGet$(h$)
a$	= word$(a$,3,"mw-content-ltr")
html "

"
i	= instr(a$," 0
  i	= instr(a$,"title=""",i)
  j	= instr(a$,""">",i+7)
  if c mod 4	= 0 then html "

"
  c	= c + 1
  html "";mid$(a$,i+7,j-(i+7));"	"
  i	= instr(a$,"<a href=""/wiki/",i+7)
wend
html "

"
print "Total unImplemented Tasks:";c
[exit]
end


use std::collections::{BTreeMap, HashSet};

use reqwest::Url;
use serde::Deserialize;
use serde_json::Value;

/// A Rosetta Code task.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Deserialize)]
pub struct Task {
    /// The ID of the page containing the task in the MediaWiki API.
    #[serde(rename = "pageid")]
    pub id: u64,

    /// The human-readable title of the task.
    pub title: String,
}

/// Encapsulates errors that might occur during JSON parsing.
#[derive(Debug)]
enum TaskParseError {
    /// Something went wrong with the HTTP request to the API.
    Http(reqwest::Error),

    /// There was a problem parsing the API response into JSON.
    Json(serde_json::Error),

    /// The response JSON contained unexpected keys or values.
    UnexpectedFormat,
}

impl From<serde_json::Error> for TaskParseError {
    fn from(err: serde_json::Error) -> Self {
        TaskParseError::Json(err)
    }
}

impl From<reqwest::Error> for TaskParseError {
    fn from(err: reqwest::Error) -> Self {
        TaskParseError::Http(err)
    }
}

/// Represents a category of pages on Rosetta Code, such as "Rust".
struct Category {
    name: String,
    continue_params: Option<BTreeMap<String, String>>,
}

impl Category {
    fn new(name: &str) -> Category {
        let mut continue_params = BTreeMap::new();
        continue_params.insert("continue".to_owned(), "".to_owned());

        Category {
            name: name.to_owned(),
            continue_params: Some(continue_params),
        }
    }
}

/// Sends a request to Rosetta Code through the MediaWiki API. If successful, returns the response
/// as a JSON object.
fn query_api(
    category_name: &str,
    continue_params: &BTreeMap<String, String>,
) -> Result<Value, TaskParseError> {
    let mut url = Url::parse("http://rosettacode.org/mw/api.php").expect("invalid URL");
    url.query_pairs_mut()
        .append_pair("action", "query")
        .append_pair("list", "categorymembers")
        .append_pair("cmtitle", &format!("Category:{}", category_name))
        .append_pair("cmlimit", "500")
        .append_pair("format", "json")
        .extend_pairs(continue_params);

    Ok(reqwest::blocking::get(url)?.json()?)
}

/// Given a JSON object, parses the task information from the MediaWiki API response.
fn parse_tasks(json: &Value) -> Result<Vec<Task>, TaskParseError> {
    let tasks_json = json
        .pointer("/query/categorymembers")
        .and_then(Value::as_array)
        .ok_or(TaskParseError::UnexpectedFormat)?;

    tasks_json
        .iter()
        .map(|json| Task::deserialize(json).map_err(From::from))
        .collect()
}

impl Iterator for Category {
    type Item = Vec<Task>;

    fn next(&mut self) -> Option<Self::Item> {
        self.continue_params.as_ref()?;

        query_api(&self.name, self.continue_params.as_ref()?)
            .and_then(|result| {
                // If there are more pages of results to request, save them for the next iteration.
                self.continue_params =
                    result
                        .get("continue")
                        .and_then(Value::as_object)
                        .map(|continue_params| {
                            continue_params
                                .iter()
                                .map(|(key, value)| {
                                    (key.to_owned(), value.as_str().unwrap().to_owned())
                                })
                                .collect()
                        });

                parse_tasks(&result)
            })
            .map_err(|err| println!("Error parsing response: {:?}", err))
            .ok()
    }
}

pub fn all_tasks() -> Vec<Task> {
    Category::new("Programming Tasks").flatten().collect()
}

pub fn unimplemented_tasks(lang: &str) -> Vec<Task> {
    let all_tasks = all_tasks().iter().cloned().collect::<HashSet<_>>();
    let implemented_tasks = Category::new(lang).flatten().collect::<HashSet<_>>();
    let mut unimplemented_tasks = all_tasks
        .difference(&implemented_tasks)
        .cloned()
        .collect::<Vec<Task>>();
    unimplemented_tasks.sort_by(|a, b| a.title.cmp(&b.title));
    unimplemented_tasks
}

fn main() {
    for task in find_unimplemented_tasks::unimplemented_tasks("Rust") {
        println!("{:6} {}", task.id, task.title);
    }
}