Rosetta Code/Count examples: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: bad link)
m (syntax highlighting fixup automation)
Line 18:
{{libheader|AWS}}
Parsing XML file with XMLAda from AdaCore
<langsyntaxhighlight Adalang="ada">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;
Line 119:
Put_Line ("Total :" & Integer'Image (Total) & " exemples.");
end Count_Examples;
</syntaxhighlight>
</lang>
Output :
<pre>
Line 130:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">UrlDownloadToFile
, http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml
, tasks.xml
Line 149:
}
MsgBox % output
Return</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 support
SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
Line 236:
WHEN "&quot;": = """"
ENDCASE
= h$</langsyntaxhighlight>
'''Sample output:'''
<pre>
Line 265:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( get-page
=
. sys$(str$("wget -q -O wget.out \"" !arg \"))
Line 305:
)
& lst$(list,taskfreq,NEW)
)</langsyntaxhighlight>
Output (in file <code>tasqfreq</code>):
<pre>list=
Line 353:
Object-oriented solution.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 412:
Console.WriteLine("\nTotal: {0} examples.", tasks.Select(x => x.Examples).Sum());
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns count-examples
(:import [java.net URLEncoder])
(:use [clojure.contrib.http.agent :only (http-agent string)]
Line 454:
(flush))
(println "Total: " (reduce #(+ %1 (second %2)) 0 task-counts))))
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="clojure">count-examples> (print-result)
100 doors: 73
24 game: 18
Line 471:
Total: 11216
nil
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{works with|Tango}}
<syntaxhighlight lang="d">
<lang D>
import tango.io.Stdout;
import tango.net.http.HttpClient;
Line 524:
}
}
</syntaxhighlight>
</lang>
 
=={{header|EGL}}==
Line 532:
 
User Interface: RosettaCodeHandler.egl
<langsyntaxhighlight EGLlang="egl">package com.eglexamples.client;
 
import org.eclipse.edt.rui.widgets.*;
Line 607:
title string;
count int;
end</langsyntaxhighlight>
 
Service Interface: ProxyFunctions.egl
<langsyntaxhighlight EGLlang="egl">package com.eglexamples.client;
 
library ProxyFunctions
Line 646:
record QueryContinue
categorymembers Categorymembers;
end</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 652:
{{libheader|xmerl}}
 
<langsyntaxhighlight lang="erlang">
-module(rosseta_examples).
-include_lib("xmerl/include/xmerl.hrl").
Line 715:
replace_chars([],Acc) ->
lists:reverse(Acc).
</syntaxhighlight>
</lang>
 
 
Line 735:
Using asynchronous workflows to perform downloads concurrently:
 
<langsyntaxhighlight lang="fsharp">#r "System.Xml.Linq.dll"
 
let uri1 = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
Line 752:
|> Async.Parallel
|> Async.RunSynchronously
|> fun xs -> printfn "Total: %d examples" (Seq.sum xs)</langsyntaxhighlight>
 
This is 21&#215; faster than the python thanks to the concurrency.
Line 759:
Runs in about a minute. The number of threads is limited to 10 avoid cloudfare's protection mechanism.
 
<langsyntaxhighlight lang="factor">USING: arrays assocs concurrency.combinators
concurrency.semaphores formatting hashtables http.client io
json.reader kernel math math.parser sequences splitting
Line 800:
all-programming-titles fetch-counts print-counts ;
 
MAIN: rosetta-examples</langsyntaxhighlight>
Outputs:
 
Line 812:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 886:
fmt.Printf("%s: %d\n", cm, examples)
total += examples
}</langsyntaxhighlight>
{{out|Output: (May 25, 2011)}}
<pre>
Line 900:
{{libheader|HTTP XML}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]
 
<langsyntaxhighlight lang="haskell">import Network.Browser
import Network.HTTP
import Network.URI
Line 936:
 
mapM_ putStrLn $ zipWith showFormatted tasks ns
putStrLn $ ("Total: " ++) $ show tot</langsyntaxhighlight>
some output:
<langsyntaxhighlight lang="haskell">*Main> progTaskExamples
100 doors: 56
24 game: 11
Line 947:
Active object: 9
...
Total: 9156</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
The following code uses features exclusive to Unicon. This version handles all tasks, not just the first 500.
 
<langsyntaxhighlight Uniconlang="unicon">$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"
Line 1,033:
close(page)
return text
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,065:
'''Solution:'''<br>
Using <code>getCategoryMembers</code> from [[Find unimplemented tasks#J|Find unimplemented tasks]].
<langsyntaxhighlight lang="j">require 'web/gethttp'
 
getAllTaskSolnCounts=: monad define
Line 1,084:
res=. ;:^:_1 tasks ,. (8!:0 counts) ,. <'examples.'
res , 'Total examples: ' , ": +/counts
)</langsyntaxhighlight>
 
'''Example Usage:'''
<langsyntaxhighlight lang="j"> formatSolnCounts getAllTaskSolnCounts ''
100 doors: 61 examples.
24 game: 15 examples.
24 game Player: 11 examples.
99 Bottles of Beer: 76 examples.
...</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">
import java.util.ArrayList;
import ScreenScrape;
Line 1,166:
}
}
</syntaxhighlight>
</lang>
[[Count programming examples/Java/ScreenScrape|ScreenScrape class]]
 
Line 1,174:
`@uri` filter in the bash function `titles`.
 
<langsyntaxhighlight lang="bash">#!/bin/bash
 
# Produce lines of the form: URI TITLE
Line 1,198:
n=$((n + i))
done < <(titles)
echo Total: $n examples.</langsyntaxhighlight>
 
{{out}}
Line 1,214:
=={{header|Julia}}==
Output by page is too long, so summaries only output shown.
<langsyntaxhighlight lang="julia">using HTTP, JSON, Dates
 
rosorg = "http://rosettacode.org"
Line 1,259:
println("Draft programming tasks:")
qdURI |> getpages |> processtaskpages
</langsyntaxhighlight>{{out}}
<pre>
Programming examples at 2019-02-16T21:04:15.583:
Line 1,269:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(root = json_deserialize(curl('http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json')->result))
local(tasks = array, title = string, urltitle = string, thiscount = 0, totalex = 0)
with i in #root->find('query')->find('categorymembers') do => {^
Line 1,285:
'\r'
^}
'Total: '+#totalex+' examples.'</langsyntaxhighlight>
 
{{out}}
Line 1,307:
2. Add a text field called "tasks"
 
n.b. The list of tasks is limited to 10 for demo purposes<langsyntaxhighlight LiveCodelang="livecode">on mouseUp
put empty into fld "taskurls"
put URL "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=xml" into apixml
Line 1,323:
end repeat
put "Total" & comma & allTaskTotal after fld "tasks"
end mouseUp</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">ConvertUTF8 := proc( str )
local i, tempstring, uniindex;
try
Line 1,363:
print_examples(x["query"]["categorymembers"]);
end do:
</syntaxhighlight>
</lang>
{{Out|Output}}
<pre>
Line 1,479:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">TaskList = Flatten[
Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]];
Print["Task \"", StringReplace[#, "_" -> " "], "\" has ",
Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]],
StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]&
~Map~ StringReplace[TaskList, " " -> "_"]</langsyntaxhighlight>
returns:
<pre>Task "100 doors" has 143 example(s)
Line 1,494:
 
The function count_examples() need to be saved in a file count_examples.m and its directory need to be included in the path.
<langsyntaxhighlight MATLABlang="matlab"> function c = count_examples(url)
c = 0;
[s, success] = urlread (url);
Line 1,511:
c = count_examples(['http://rosettacode.org',t]);
printf('Task "%s" has %i examples.\n',t(7:end), c);
end; </langsyntaxhighlight>
 
Output:
Line 1,523:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import httpclient, strutils, xmltree, xmlparser, cgi
 
proc count(s, sub: string): int =
Line 1,545:
inc sum, c
 
echo "\nTotal: ", sum, " examples."</langsyntaxhighlight>
 
{{out}}
Line 1,573:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use HTTP;
use XML;
 
Line 1,610:
return xml;
}
}</langsyntaxhighlight>
 
Output:<pre>Amb: 28
Line 1,643:
ocamlfind opt -linkpkg -package str,unix,xml-light,netclient countex.ml -o countex.opt
 
<langsyntaxhighlight lang="ocaml">open Http_client.Convenience
 
Line 1,704:
let catmb = get_child "categorymembers" query in
List.iter f catmb
| _ -> ()</langsyntaxhighlight>
 
outputs:
Line 1,731:
{{libheader|OzHttpClient}}
 
<langsyntaxhighlight lang="oz">declare
[HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Line 1,815:
end
in
{Main}</langsyntaxhighlight>
 
Example output:
Line 1,834:
=={{header|Perl}}==
{{libheader|HTTP:Tiny}}
<langsyntaxhighlight Perllang="perl">use HTTP::Tiny;
 
my $site = "http://rosettacode.org";
Line 1,845:
my $count = () = $response->{content} =~ /toclevel-1/g;
print "$_: $count examples\n";
}</langsyntaxhighlight>
 
{{libheader|Mojolicious}}
<langsyntaxhighlight Perllang="perl">use v5.10;
use Mojo::UserAgent;
 
Line 1,859:
my $count = $ua->get("$site/wiki/$slug")->res->dom->find("#toc .toclevel-1")->size;
say "$_->{title}: $count examples";
});</langsyntaxhighlight>
 
=={{header|Phix}}==
First, some common code used by several tasks:
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\rosettacode_cache.e
Line 2,013:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</langsyntaxhighlight>-->
The task itself:
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Count_examples.exw
Line 2,120:
<span style="color: #7060A8;">progress</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Total: %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count_tasks</span><span style="color: #0000FF;">()})</span>
<!--</langsyntaxhighlight>-->
{{out}} (as of 30/2/22, showing first two, every 200th, and last two)
<pre>
Line 2,139:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/http.l")
 
(client "rosettacode.org" 80
Line 2,150:
(unless (sub? "." (till "<" T))
(inc 'Cnt) ) )
(out NIL (prinl (ht:Pack Task) ": " Cnt)) ) ) ) ) )</langsyntaxhighlight>
Output (05may10):
<pre>100 doors: 79
Line 2,161:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure handleError(value, msg.s)
If value = 0
MessageRequester("Error", msg)
Line 2,224:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>100 doors: 224 examples
Line 2,242:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">from urllib.request import urlopen, Request
import xml.dom.minidom
 
Line 2,260:
 
print(f'\nTotal: {sum(tasks)} examples.')
</syntaxhighlight>
</lang>
 
=={{header|R}}==
Line 2,266:
 
{{libheader|RCurl}}
<syntaxhighlight lang="r">
<lang R>
library(XML)
library(RCurl)
Line 2,281:
}
cat("Total: ", length(unlist(counts)), "examples\n")
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,311:
(printf "~a: ~a\n" task s)
s))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,327:
 
For a full output, see [[Rosetta_Code/Count_examples/Full_list|Top tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_2|Second tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_3|Third tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_4|Fourth tier]]
<syntaxhighlight lang="raku" perl6line>use HTTP::UserAgent;
use URI::Escape;
use JSON::Fast;
Line 2,501:
sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~(65+$0.chars).chr~$0},:g) }
 
sub clear { "\r" ~ ' ' x 116 ~ "\r" }</langsyntaxhighlight>
 
{{out|Abridged output}}
Line 2,565:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project: Rosetta Code/Count examples
 
Line 2,621:
end
return sum
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,652:
{{libheader|REXML}}
First, a RosettaCode module, saved as <tt>rosettacode.rb</tt>:
<langsyntaxhighlight lang="ruby">require 'open-uri'
require 'rexml/document'
 
Line 2,702:
end
 
end</langsyntaxhighlight>
 
Then, we implement the task with:
<langsyntaxhighlight lang="ruby">require 'rosettacode'
 
total_examples = 0
Line 2,717:
 
puts
puts "Total: #{total_examples}"</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">html "<table border=1><tr bgcolor=wheat align=center><td>Num</td><td>Task</td><td>Examples</td></tr>"
 
a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Tasks")
Line 2,751:
wend
html "<tr bgcolor=wheat><td>**</td><td>** Total **</td><td align=right>";totExamp;"</td></tr></table>"
end</langsyntaxhighlight>
<table border=1><tr bgcolor=wheat align=center><td>Num</td><td>Task</td><td>Examples</td></tr>
<tr><td align=right>1</td><td>100 doors</td><td align=right>165</td></tr>
Line 2,775:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">extern crate reqwest;
extern crate url;
extern crate rustc_serialize;
Line 2,886:
let json: Json = query_api(query).unwrap();
count_number_examples(&json, task.page_id).unwrap()
}</langsyntaxhighlight>
 
The function is then run using the following:
<langsyntaxhighlight lang="rust">
extern crate count_examples;
fn main() {
Line 2,897:
println!("Task: {} has {} examples", task.title, count);
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala">import scala.language.postfixOps
 
object TaskCount extends App {
Line 2,924:
counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println
println("\nTotal: %d examples." format (counts map (_.apply._2) sum))
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var lwp = require('LWP::UserAgent').new(agent => 'Mozilla/5.0');
 
var site = 'http://rosettacode.org';
Line 2,940:
var count = lwp.get("#{site}/wiki/#{slug}").decoded_content.count(/toclevel-1/g);
say "#{m[0]}: #{count} examples";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,958:
=={{header|Tcl}}==
{{tcllib|json}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require http
package require json
Line 3,022:
}
 
puts "\nTotal: $total examples"</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
url="http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
data=REQUEST (url)
Line 3,064:
 
FILE "tasks" = line
</syntaxhighlight>
</lang>
Output in file "tasks":
<pre style='height:30ex;overflow:scroll'>
Line 3,090:
Requires the <tt>curl</tt> and <tt>jq</tt> command-line utilities.
 
<langsyntaxhighlight lang="sh">#!/usr/bin/env bash
SITE=https://www.rosettacode.org
API=$SITE/mw/api.php
Line 3,109:
| jq -r '.query.categorymembers[].title')
 
printf '\nTotal: %d examples.\n' "$total"</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 3,115:
{{libheader|Wren-pattern}}
An embedded program so we can use the libcurl library.
<langsyntaxhighlight lang="ecmascript">/* rc_count_examples.wren */
 
import "./pattern" for Pattern
Line 3,166:
}
 
curl.easyCleanup()</langsyntaxhighlight>
<br>
which we now embed in the following C program, build and run.
<langsyntaxhighlight lang="c">/* gcc rc_count_examples.c -o rc_count_examples -lcurl -lwren -lm */
 
#include <stdio.h>
Line 3,359:
free(script);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 3,394:
=={{header|zkl}}==
Uses shared libraries YAJL and cURL and handles "continue" responses.
<langsyntaxhighlight lang="zkl">var [const] YAJL=Import("zklYAJL")[0], CURL=Import("zklCurl");
 
fcn getTasks(language){
Line 3,421:
cnt,n:=0,0; while(re.search(page,True,n)){ cnt+=1; n=re.matched[0].sum(0); }
"%4d: %s".fmt(cnt,task).println();
}</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits